diff --git a/Android.mk b/Android.mk index d67a21e46e897f77ff43c431c69dcc9014c9e337..8013c9360c0a18407ea5ff5678a5d85d316f987a 100644 --- a/Android.mk +++ b/Android.mk @@ -97,7 +97,10 @@ LOCAL_SRC_FILES += \ core/java/android/view/IWindowManager.aidl \ core/java/android/view/IWindowSession.aidl \ core/java/com/android/internal/app/IBatteryStats.aidl \ - core/java/com/android/internal/gadget/IGadgetService.aidl \ + core/java/com/android/internal/app/IUsageStats.aidl \ + core/java/com/android/internal/appwidget/IAppWidgetService.aidl \ + core/java/com/android/internal/appwidget/IAppWidgetHost.aidl \ + core/java/com/android/internal/os/IResultReceiver.aidl \ core/java/com/android/internal/view/IInputContext.aidl \ core/java/com/android/internal/view/IInputContextCallback.aidl \ core/java/com/android/internal/view/IInputMethod.aidl \ @@ -165,7 +168,7 @@ aidl_files := \ frameworks/base/core/java/android/content/Intent.aidl \ frameworks/base/core/java/android/content/SyncStats.aidl \ frameworks/base/core/java/android/content/res/Configuration.aidl \ - frameworks/base/core/java/android/gadget/GadgetInfo.aidl \ + frameworks/base/core/java/android/appwidget/AppWidgetProviderInfo.aidl \ frameworks/base/core/java/android/net/Uri.aidl \ frameworks/base/core/java/android/os/Bundle.aidl \ frameworks/base/core/java/android/os/ParcelFileDescriptor.aidl \ @@ -173,6 +176,7 @@ aidl_files := \ frameworks/base/core/java/android/view/MotionEvent.aidl \ frameworks/base/core/java/android/view/Surface.aidl \ frameworks/base/core/java/android/view/WindowManager.aidl \ + frameworks/base/core/java/android/widget/RemoteViews.aidl \ frameworks/base/core/java/com/android/internal/view/IInputContext.aidl \ frameworks/base/core/java/com/android/internal/view/IInputMethod.aidl \ frameworks/base/core/java/com/android/internal/view/IInputMethodCallback.aidl \ diff --git a/api/3.xml b/api/3.xml index 9d9ce98b41a0436eacd8019e4234298b4ee48cb9..512fef8b184f850fc0acb109cc5d3ce16126d4b8 100644 --- a/api/3.xml +++ b/api/3.xml @@ -25763,17 +25763,6 @@ visibility="public" > - - + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + @@ -6602,7 +6800,7 @@ type="int" transient="false" volatile="false" - value="16843330" + value="16843324" static="true" final="true" deprecated="not deprecated" @@ -7324,6 +7522,17 @@ visibility="public" > + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -52128,6 +53971,17 @@ visibility="public" > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + @@ -57279,6 +59552,8 @@ > + + + + @@ -57360,6 +59637,21 @@ visibility="public" > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + + + + + + + + + + + + + + + + + + + + + + + + @@ -62653,6 +66542,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -70125,544 +74355,6 @@ > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -88896,329 +93093,138 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -91463,6 +95368,21 @@ deprecated="not deprecated" visibility="public" > + + + + + + @@ -96365,6 +100285,21 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -112204,6 +117282,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -113347,6 +118636,17 @@ visibility="public" > + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -120510,6 +125994,19 @@ + + + + + + + + + + @@ -121911,7 +127432,7 @@ synchronized="false" static="true" final="false" - deprecated="not deprecated" + deprecated="deprecated" visibility="public" > @@ -121955,7 +127476,7 @@ synchronized="false" static="true" final="false" - deprecated="not deprecated" + deprecated="deprecated" visibility="public" > @@ -121966,7 +127487,7 @@ synchronized="false" static="true" final="false" - deprecated="not deprecated" + deprecated="deprecated" visibility="public" > @@ -121981,6 +127502,83 @@ visibility="public" > + + + + + + + + + + + + + + @@ -122021,7 +127619,7 @@ synchronized="false" static="true" final="false" - deprecated="not deprecated" + deprecated="deprecated" visibility="public" > @@ -122032,7 +127630,7 @@ synchronized="false" static="true" final="false" - deprecated="not deprecated" + deprecated="deprecated" visibility="public" > @@ -125337,6 +130935,19 @@ + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + - + - + + + + + + + @@ -129439,6 +135375,21 @@ visibility="public" > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + - + + + + + + + + + + - - + - + - + + - + + + + + - + + + + + + + + + + - - + - + @@ -130385,6 +136622,10 @@ deprecated="not deprecated" visibility="public" > + + + + + + @@ -130439,6 +136682,8 @@ > + + - + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - - - - @@ -132525,6 +138956,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -132910,6 +139425,21 @@ visibility="public" > + + + + + + @@ -135016,7 +141546,7 @@ synchronized="false" static="false" final="false" - deprecated="not deprecated" + deprecated="deprecated" visibility="public" > @@ -136786,6 +143316,17 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -147755,6 +154906,323 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + CameraHardwareStub::getPreviewHeap() const { - return mHeap; + return mPreviewHeap; +} + +sp CameraHardwareStub::getRawHeap() const +{ + return mRawHeap; } // --------------------------------------------------------------------------- @@ -114,7 +124,7 @@ int CameraHardwareStub::previewThread() // Find the offset within the heap of the current buffer. ssize_t offset = mCurrentPreviewFrame * mPreviewFrameSize; - sp heap = mHeap; + sp heap = mPreviewHeap; // this assumes the internal state of fake camera doesn't change // (or is thread safe) @@ -187,6 +197,24 @@ bool CameraHardwareStub::previewEnabled() { return mPreviewThread != 0; } +status_t CameraHardwareStub::startRecording(recording_callback cb, void* user) +{ + return UNKNOWN_ERROR; +} + +void CameraHardwareStub::stopRecording() +{ +} + +bool CameraHardwareStub::recordingEnabled() +{ + return false; +} + +void CameraHardwareStub::releaseRecordingFrame(const sp& mem) +{ +} + // --------------------------------------------------------------------------- int CameraHardwareStub::beginAutoFocusThread(void *cookie) @@ -237,10 +265,9 @@ int CameraHardwareStub::pictureThread() // In the meantime just make another fake camera picture. int w, h; mParameters.getPictureSize(&w, &h); - sp heap = new MemoryHeapBase(w * 2 * h); - sp mem = new MemoryBase(heap, 0, w * 2 * h); + sp mem = new MemoryBase(mRawHeap, 0, w * 2 * h); FakeCamera cam(w, h); - cam.getNextFrameAsYuv422((uint8_t *)heap->base()); + cam.getNextFrameAsYuv422((uint8_t *)mRawHeap->base()); if (mRawPictureCallback) mRawPictureCallback(mem, mPictureCallbackCookie); } diff --git a/camera/libcameraservice/CameraHardwareStub.h b/camera/libcameraservice/CameraHardwareStub.h index 9f5ddf13ec655ff9500db7dea097e458c34d0b91..0d26d47ececb3db38b855542d32ebf5a8888e346 100644 --- a/camera/libcameraservice/CameraHardwareStub.h +++ b/camera/libcameraservice/CameraHardwareStub.h @@ -30,10 +30,17 @@ namespace android { class CameraHardwareStub : public CameraHardwareInterface { public: virtual sp getPreviewHeap() const; + virtual sp getRawHeap() const; virtual status_t startPreview(preview_callback cb, void* user); virtual void stopPreview(); virtual bool previewEnabled(); + + virtual status_t startRecording(recording_callback cb, void* user); + virtual void stopRecording(); + virtual bool recordingEnabled(); + virtual void releaseRecordingFrame(const sp& mem); + virtual status_t autoFocus(autofocus_callback, void *user); virtual status_t takePicture(shutter_callback, raw_callback, @@ -87,7 +94,8 @@ private: CameraParameters mParameters; - sp mHeap; + sp mPreviewHeap; + sp mRawHeap; sp mBuffers[kBufferCount]; FakeCamera *mFakeCamera; diff --git a/camera/libcameraservice/CameraService.cpp b/camera/libcameraservice/CameraService.cpp index 36c5ada97a9325d996e0415e313a6b149abba999..15e3b21aeaa03e2c122481c2e9be22845faa1f9c 100644 --- a/camera/libcameraservice/CameraService.cpp +++ b/camera/libcameraservice/CameraService.cpp @@ -86,18 +86,19 @@ sp CameraService::connect(const sp& cameraClient) LOGD("Connect E from ICameraClient %p", cameraClient->asBinder().get()); Mutex::Autolock lock(mLock); + sp client; if (mClient != 0) { sp currentClient = mClient.promote(); if (currentClient != 0) { sp currentCameraClient(currentClient->getCameraClient()); if (cameraClient->asBinder() == currentCameraClient->asBinder()) { // this is the same client reconnecting... - LOGD("Connect X same client is reconnecting..."); + LOGD("Connect X same client (%p) is reconnecting...", cameraClient->asBinder().get()); return currentClient; } else { - // it's another client... boot the previous one... - LOGD("new client connecting, booting the old one..."); - mClient.clear(); + // it's another client... reject it + LOGD("new client (%p) attempting to connect - rejected", cameraClient->asBinder().get()); + return client; } } else { // can't promote, the previous client has died... @@ -107,7 +108,7 @@ sp CameraService::connect(const sp& cameraClient) } // create a new Client object - sp client = new Client(this, cameraClient, IPCThreadState::self()->getCallingPid()); + client = new Client(this, cameraClient, IPCThreadState::self()->getCallingPid()); mClient = client; #if DEBUG_CLIENT_REFERENCES // Enable tracking for this object, and track increments and decrements of @@ -151,28 +152,30 @@ void CameraService::removeClient(const sp& cameraClient) } CameraService::Client::Client(const sp& cameraService, - const sp& cameraClient, pid_t clientPid) + const sp& cameraClient, pid_t clientPid) { LOGD("Client E constructor"); mCameraService = cameraService; mCameraClient = cameraClient; mClientPid = clientPid; mHardware = openCameraHardware(); + mUseOverlay = mHardware->useOverlay(); // Callback is disabled by default - mFrameCallbackFlag = FRAME_CALLBACK_FLAG_NOOP; + mPreviewCallbackFlag = FRAME_CALLBACK_FLAG_NOOP; LOGD("Client X constructor"); } status_t CameraService::Client::checkPid() { if (mClientPid == IPCThreadState::self()->getCallingPid()) return NO_ERROR; - LOGW("Attempt to use locked camera from different process"); + LOGW("Attempt to use locked camera (%p) from different process", getCameraClient()->asBinder().get()); return -EBUSY; } status_t CameraService::Client::lock() { + Mutex::Autolock _l(mLock); // lock camera to this client if the the camera is unlocked if (mClientPid == 0) { mClientPid = IPCThreadState::self()->getCallingPid(); @@ -184,8 +187,9 @@ status_t CameraService::Client::lock() status_t CameraService::Client::unlock() { + Mutex::Autolock _l(mLock); // allow anyone to use camera - LOGV("unlock"); + LOGV("unlock (%p)", getCameraClient()->asBinder().get()); status_t result = checkPid(); if (result == NO_ERROR) mClientPid = 0; return result; @@ -194,27 +198,40 @@ status_t CameraService::Client::unlock() status_t CameraService::Client::connect(const sp& client) { // connect a new process to the camera - LOGV("connect"); - - // hold a reference to the old client or we will deadlock if the client is - // in the same process and we hold the lock when we remove the reference - sp oldClient; + LOGV("connect (%p)", client->asBinder().get()); + + // I hate this hack, but things get really ugly when the media recorder + // service is handing back the camera to the app. The ICameraClient + // destructor will be called during the same IPC, making it look like + // the remote client is trying to disconnect. This hack temporarily + // sets the mClientPid to an invalid pid to prevent the hardware from + // being torn down. { - Mutex::Autolock _l(mLock); - if (mClientPid != 0) { - LOGW("Tried to connect to locked camera"); - return -EBUSY; - } - oldClient = mCameraClient; - // did the client actually change? - if (client->asBinder() == mCameraClient->asBinder()) return NO_ERROR; + // hold a reference to the old client or we will deadlock if the client is + // in the same process and we hold the lock when we remove the reference + sp oldClient; + { + Mutex::Autolock _l(mLock); + if (mClientPid != 0) { + LOGW("Tried to connect to locked camera"); + return -EBUSY; + } + oldClient = mCameraClient; + + // did the client actually change? + if (client->asBinder() == mCameraClient->asBinder()) return NO_ERROR; + + mCameraClient = client; + mClientPid = -1; + mPreviewCallbackFlag = FRAME_CALLBACK_FLAG_NOOP; + LOGV("connect new process (%d) to existing camera client", mClientPid); + } - LOGV("connect new process to existing camera client"); - mCameraClient = client; - mClientPid = IPCThreadState::self()->getCallingPid(); - mFrameCallbackFlag = FRAME_CALLBACK_FLAG_NOOP; } + // the old client destructor is called when oldClient goes out of scope + // now we set the new PID to lock the interface again + mClientPid = IPCThreadState::self()->getCallingPid(); return NO_ERROR; } @@ -232,8 +249,8 @@ static void *unregister_surface(void *arg) CameraService::Client::~Client() { // tear down client - LOGD("Client E destructor"); - if (mSurface != 0) { + LOGD("Client (%p) E destructor", getCameraClient()->asBinder().get()); + if (mSurface != 0 && !mUseOverlay) { #if HAVE_ANDROID_OS pthread_t thr; // We unregister the buffers in a different thread because binder does @@ -244,7 +261,7 @@ CameraService::Client::~Client() mSurface.get()); pthread_join(thr, NULL); #else - mSurface->unregisterBuffers(); + mSurface->unregisterBuffers(); #endif } @@ -256,16 +273,22 @@ CameraService::Client::~Client() void CameraService::Client::disconnect() { - LOGD("Client E disconnect"); + LOGD("Client (%p) E disconnect from (%d)", + getCameraClient()->asBinder().get(), + IPCThreadState::self()->getCallingPid()); Mutex::Autolock lock(mLock); - if (mClientPid == 0) { + if (mClientPid <= 0) { LOGV("camera is unlocked, don't tear down hardware"); return; } - if (checkPid() != NO_ERROR) return; + if (checkPid() != NO_ERROR) { + LOGV("Different client - don't disconnect"); + return; + } mCameraService->removeClient(mCameraClient); if (mHardware != 0) { + LOGV("hardware teardown"); // Before destroying mHardware, we must make sure it's in the // idle state. mHardware->stopPreview(); @@ -288,7 +311,7 @@ status_t CameraService::Client::setPreviewDisplay(const sp& surface) Mutex::Autolock surfaceLock(mSurfaceLock); // asBinder() is safe on NULL (returns NULL) if (surface->asBinder() != mSurface->asBinder()) { - if (mSurface != 0) { + if (mSurface != 0 && !mUseOverlay) { LOGD("clearing old preview surface %p", mSurface.get()); mSurface->unregisterBuffers(); } @@ -297,19 +320,20 @@ status_t CameraService::Client::setPreviewDisplay(const sp& surface) return NO_ERROR; } -// set the frame callback flag to affect how the received frames from +// set the preview callback flag to affect how the received frames from // preview are handled. -void CameraService::Client::setFrameCallbackFlag(int frame_callback_flag) +void CameraService::Client::setPreviewCallbackFlag(int callback_flag) { + LOGV("setPreviewCallbackFlag"); Mutex::Autolock lock(mLock); if (checkPid() != NO_ERROR) return; - mFrameCallbackFlag = frame_callback_flag; + mPreviewCallbackFlag = callback_flag; } // start preview mode, must call setPreviewDisplay first -status_t CameraService::Client::startPreview() +status_t CameraService::Client::startCameraMode(camera_mode mode) { - LOGD("startPreview()"); + LOGD("startCameraMode(%d)", mode); /* we cannot call into mHardware with mLock held because * mHardware has callbacks onto us which acquire this lock @@ -325,37 +349,124 @@ status_t CameraService::Client::startPreview() } if (mSurface == 0) { - LOGE("setPreviewDisplay must be called before startPreview!"); + LOGE("setPreviewDisplay must be called before startCameraMode!"); return INVALID_OPERATION; } - // do nothing if preview is already started - if (mHardware->previewEnabled()) return NO_ERROR; + switch(mode) { + case CAMERA_RECORDING_MODE: + return startRecordingMode(); - // XXX: This needs to be improved. remove all hardcoded stuff + default: // CAMERA_PREVIEW_MODE + return startPreviewMode(); + } +} - int w, h; - CameraParameters params(mHardware->getParameters()); - params.getPreviewSize(&w, &h); +status_t CameraService::Client::startRecordingMode() +{ + LOGV("startRecordingMode"); + status_t ret = UNKNOWN_ERROR; + + // if preview has not been started, start preview first + if (!mHardware->previewEnabled()) { + ret = startPreviewMode(); + if (ret != NO_ERROR) { + return ret; + } + } + + // if recording has been enabled, nothing needs to be done + if (mHardware->recordingEnabled()) { + return NO_ERROR; + } + + // start recording mode + ret = mHardware->startRecording(recordingCallback, + mCameraService.get()); + if (ret != NO_ERROR) { + LOGE("mHardware->startRecording() failed with status %d", ret); + } + return ret; +} + +status_t CameraService::Client::startPreviewMode() +{ + LOGV("startPreviewMode"); + + // if preview has been enabled, nothing needs to be done + if (mHardware->previewEnabled()) { + return NO_ERROR; + } + + // start preview mode #if DEBUG_DUMP_PREVIEW_FRAME_TO_FILE debug_frame_cnt = 0; #endif + status_t ret = UNKNOWN_ERROR; + int w, h; + CameraParameters params(mHardware->getParameters()); + params.getPreviewSize(&w, &h); - status_t ret = mHardware->startPreview(previewCallback, - mCameraService.get()); - if (ret == NO_ERROR) { - mSurface->unregisterBuffers(); - mSurface->registerBuffers(w,h,w,h, - PIXEL_FORMAT_YCbCr_420_SP, - mHardware->getPreviewHeap()); - } - else LOGE("mHardware->startPreview() failed with status %d\n", - ret); + if (mUseOverlay) { + const char *format = params.getPreviewFormat(); + int fmt; + LOGD("Use Overlays"); + if (!strcmp(format, "yuv422i")) + fmt = OVERLAY_FORMAT_YCbCr_422_I; + else if (!strcmp(format, "rgb565")) + fmt = OVERLAY_FORMAT_RGB_565; + else { + LOGE("Invalid preview format for overlays"); + return -EINVAL; + } + sp ref = mSurface->createOverlay(w, h, fmt); + ret = mHardware->setOverlay(new Overlay(ref)); + if (ret != NO_ERROR) { + LOGE("mHardware->setOverlay() failed with status %d\n", ret); + return ret; + } + ret = mHardware->startPreview(NULL, mCameraService.get()); + if (ret != NO_ERROR) + LOGE("mHardware->startPreview() failed with status %d\n", ret); + + } else { + ret = mHardware->startPreview(previewCallback, + mCameraService.get()); + if (ret == NO_ERROR) { + + mSurface->unregisterBuffers(); + + uint32_t transform = 0; + if (params.getOrientation() == + CameraParameters::CAMERA_ORIENTATION_PORTRAIT) { + LOGV("portrait mode"); + transform = ISurface::BufferHeap::ROT_90; + } + ISurface::BufferHeap buffers(w, h, w, h, + PIXEL_FORMAT_YCbCr_420_SP, + transform, + 0, + mHardware->getPreviewHeap()); + mSurface->registerBuffers(buffers); + } else { + LOGE("mHardware->startPreview() failed with status %d", ret); + } + } return ret; } +status_t CameraService::Client::startPreview() +{ + return startCameraMode(CAMERA_PREVIEW_MODE); +} + +status_t CameraService::Client::startRecording() +{ + return startCameraMode(CAMERA_RECORDING_MODE); +} + // stop preview mode void CameraService::Client::stopPreview() { @@ -372,12 +483,46 @@ void CameraService::Client::stopPreview() mHardware->stopPreview(); LOGD("stopPreview(), hardware stopped OK"); - if (mSurface != 0) { + if (mSurface != 0 && !mUseOverlay) { mSurface->unregisterBuffers(); } mPreviewBuffer.clear(); } +// stop recording mode +void CameraService::Client::stopRecording() +{ + LOGV("stopRecording()"); + + Mutex::Autolock lock(mLock); + if (checkPid() != NO_ERROR) return; + + if (mHardware == 0) { + LOGE("mHardware is NULL, returning."); + return; + } + + mHardware->stopRecording(); + LOGV("stopRecording(), hardware stopped OK"); + mPreviewBuffer.clear(); +} + +// release a recording frame +void CameraService::Client::releaseRecordingFrame(const sp& mem) +{ + LOGV("releaseRecordingFrame()"); + + Mutex::Autolock lock(mLock); + if (checkPid() != NO_ERROR) return; + + if (mHardware == 0) { + LOGE("mHardware is NULL, returning."); + return; + } + + mHardware->releaseRecordingFrame(mem); +} + bool CameraService::Client::previewEnabled() { Mutex::Autolock lock(mLock); @@ -385,6 +530,13 @@ bool CameraService::Client::previewEnabled() return mHardware->previewEnabled(); } +bool CameraService::Client::recordingEnabled() +{ + Mutex::Autolock lock(mLock); + if (mHardware == 0) return false; + return mHardware->recordingEnabled(); +} + // Safely retrieves a strong pointer to the client during a hardware callback. sp CameraService::Client::getClientFromCookie(void* user) { @@ -476,7 +628,7 @@ void CameraService::Client::previewCallback(const sp& mem, void* user) #endif // The strong pointer guarantees the client will exist, but no lock is held. - client->postFrame(mem); + client->postPreviewFrame(mem); #if DEBUG_CLIENT_REFERENCES //**** if the client's refcount is 1, then we are about to destroy it here, @@ -488,6 +640,18 @@ void CameraService::Client::previewCallback(const sp& mem, void* user) #endif } +// recording callback +void CameraService::Client::recordingCallback(const sp& mem, void* user) +{ + LOGV("recordingCallback"); + sp client = getClientFromCookie(user); + if (client == 0) { + return; + } + // The strong pointer guarantees the client will exist, but no lock is held. + client->postRecordingFrame(mem); +} + // take a picture - image is returned in callback status_t CameraService::Client::autoFocus() { @@ -520,9 +684,6 @@ status_t CameraService::Client::takePicture() return INVALID_OPERATION; } - if (mSurface != NULL) - mSurface->unregisterBuffers(); - return mHardware->takePicture(shutterCallback, yuvPictureCallback, jpegPictureCallback, @@ -537,7 +698,29 @@ void CameraService::Client::shutterCallback(void *user) return; } + // Screen goes black after the buffer is unregistered. + if (client->mSurface != 0 && !client->mUseOverlay) { + client->mSurface->unregisterBuffers(); + } + client->postShutter(); + + // It takes some time before yuvPicture callback to be called. + // Register the buffer for raw image here to reduce latency. + if (client->mSurface != 0 && !client->mUseOverlay) { + int w, h; + CameraParameters params(client->mHardware->getParameters()); + params.getPictureSize(&w, &h); + uint32_t transform = 0; + if (params.getOrientation() == CameraParameters::CAMERA_ORIENTATION_PORTRAIT) { + LOGV("portrait mode"); + transform = ISurface::BufferHeap::ROT_90; + } + ISurface::BufferHeap buffers(w, h, w, h, + PIXEL_FORMAT_YCbCr_420_SP, transform, 0, client->mHardware->getRawHeap()); + + client->mSurface->registerBuffers(buffers); + } } // picture callback - raw image ready @@ -568,15 +751,7 @@ void CameraService::Client::yuvPictureCallback(const sp& mem, #endif // Put the YUV version of the snapshot in the preview display. - int w, h; - CameraParameters params(client->mHardware->getParameters()); - params.getPictureSize(&w, &h); - -// Mutex::Autolock clientLock(client->mLock); - if (client->mSurface != 0) { - client->mSurface->unregisterBuffers(); - client->mSurface->registerBuffers(w,h,w,h, - PIXEL_FORMAT_YCbCr_420_SP, heap); + if (client->mSurface != 0 && !client->mUseOverlay) { client->mSurface->postBuffer(offset); } @@ -730,12 +905,22 @@ void CameraService::Client::copyFrameAndPostCopiedFrame(sp heap, si LOGE("failed to allocate space for frame callback"); return; } - mCameraClient->frameCallback(frame); + mCameraClient->previewCallback(frame); } -void CameraService::Client::postFrame(const sp& mem) +void CameraService::Client::postRecordingFrame(const sp& frame) { - LOGV("postFrame"); + LOGV("postRecordingFrame"); + if (frame == 0) { + LOGW("frame is a null pointer"); + return; + } + mCameraClient->recordingCallback(frame); +} + +void CameraService::Client::postPreviewFrame(const sp& mem) +{ + LOGV("postPreviewFrame"); if (mem == 0) { LOGW("mem is a null pointer"); return; @@ -752,31 +937,32 @@ void CameraService::Client::postFrame(const sp& mem) } // Is the callback enabled or not? - if (!(mFrameCallbackFlag & FRAME_CALLBACK_FLAG_ENABLE_MASK)) { + if (!(mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ENABLE_MASK)) { // If the enable bit is off, the copy-out and one-shot bits are ignored LOGV("frame callback is diabled"); return; } // Is the received frame copied out or not? - if (mFrameCallbackFlag & FRAME_CALLBACK_FLAG_COPY_OUT_MASK) { + if (mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_COPY_OUT_MASK) { LOGV("frame is copied out"); copyFrameAndPostCopiedFrame(heap, offset, size); } else { LOGV("frame is directly sent out without copying"); - mCameraClient->frameCallback(mem); + mCameraClient->previewCallback(mem); } // Is this is one-shot only? - if (mFrameCallbackFlag & FRAME_CALLBACK_FLAG_ONE_SHOT_MASK) { + if (mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ONE_SHOT_MASK) { LOGV("One-shot only, thus clear the bits and disable frame callback"); - mFrameCallbackFlag &= ~(FRAME_CALLBACK_FLAG_ONE_SHOT_MASK | + mPreviewCallbackFlag &= ~(FRAME_CALLBACK_FLAG_ONE_SHOT_MASK | FRAME_CALLBACK_FLAG_COPY_OUT_MASK | FRAME_CALLBACK_FLAG_ENABLE_MASK); } } -void CameraService::Client::postError(status_t error) { +void CameraService::Client::postError(status_t error) +{ mCameraClient->errorCallback(error); } @@ -796,6 +982,11 @@ status_t CameraService::dump(int fd, const Vector& args) AutoMutex lock(&mLock); if (mClient != 0) { sp currentClient = mClient.promote(); + sprintf(buffer, "Client (%p) PID: %d\n", + currentClient->getCameraClient()->asBinder().get(), + currentClient->mClientPid); + result.append(buffer); + write(fd, result.string(), result.size()); currentClient->mHardware->dump(fd, args); } else { result.append("No camera client yet.\n"); @@ -880,5 +1071,3 @@ status_t CameraService::onTransact( #endif // DEBUG_HEAP_LEAKS }; // namespace android - - diff --git a/camera/libcameraservice/CameraService.h b/camera/libcameraservice/CameraService.h index cd8c1e9a41cfa80bfe53ce715df582706071dc39..d9b79276a72a8e9955675b2b9cac3678d68b31bd 100644 --- a/camera/libcameraservice/CameraService.h +++ b/camera/libcameraservice/CameraService.h @@ -82,9 +82,9 @@ private: // pass the buffered ISurface to the camera service virtual status_t setPreviewDisplay(const sp& surface); - // set the frame callback flag to affect how the received frames from + // set the preview callback flag to affect how the received frames from // preview are handled. - virtual void setFrameCallbackFlag(int frame_callback_flag); + virtual void setPreviewCallbackFlag(int callback_flag); // start preview mode, must call setPreviewDisplay first virtual status_t startPreview(); @@ -95,6 +95,18 @@ private: // get preview state virtual bool previewEnabled(); + // start recording mode + virtual status_t startRecording(); + + // stop recording mode + virtual void stopRecording(); + + // get recording state + virtual bool recordingEnabled(); + + // release a recording frame + virtual void releaseRecordingFrame(const sp& mem); + // auto focus virtual status_t autoFocus(); @@ -120,6 +132,7 @@ private: status_t checkPid(); + static void recordingCallback(const sp& mem, void* user); static void previewCallback(const sp& mem, void* user); static void shutterCallback(void *user); static void yuvPictureCallback(const sp& mem, void* user); @@ -130,17 +143,28 @@ private: void postShutter(); void postRaw(const sp& mem); void postJpeg(const sp& mem); - void postFrame(const sp& mem); + void postPreviewFrame(const sp& mem); + void postRecordingFrame(const sp& frame); void copyFrameAndPostCopiedFrame(sp heap, size_t offset, size_t size); void postError(status_t error); void postAutoFocus(bool focused); - // Ensures atomicity among the public methods + // camera operation mode + enum camera_mode { + CAMERA_PREVIEW_MODE = 0, // frame automatically released + CAMERA_RECORDING_MODE = 1, // frame has to be explicitly released by releaseRecordingFrame() + }; + status_t startCameraMode(camera_mode mode); + status_t startPreviewMode(); + status_t startRecordingMode(); + + // Ensures atomicity among the public methods mutable Mutex mLock; + // mSurfaceLock synchronizes access to mSurface between - // setPreviewSurface() and postFrame(). Note that among + // setPreviewSurface() and postPreviewFrame(). Note that among // the public methods, all accesses to mSurface are - // syncrhonized by mLock. However, postFrame() is called + // syncrhonized by mLock. However, postPreviewFrame() is called // by the CameraHardwareInterface callback, and needs to // access mSurface. It cannot hold mLock, however, because // stopPreview() may be holding that lock while attempting @@ -152,13 +176,14 @@ private: sp mCameraService; sp mSurface; sp mPreviewBuffer; - int mFrameCallbackFlag; + int mPreviewCallbackFlag; // these are immutable once the object is created, // they don't need to be protected by a lock sp mCameraClient; sp mHardware; pid_t mClientPid; + bool mUseOverlay; }; // ---------------------------------------------------------------------------- diff --git a/cmds/am/src/com/android/commands/am/Am.java b/cmds/am/src/com/android/commands/am/Am.java index b86d40a2b85abb42b93ce2c8b9ba22bfdc303ae8..6d4b4552bbc06dbf2d48349e7825ea0e81989d78 100644 --- a/cmds/am/src/com/android/commands/am/Am.java +++ b/cmds/am/src/com/android/commands/am/Am.java @@ -75,6 +75,8 @@ public class Am { runInstrument(); } else if (op.equals("broadcast")) { sendBroadcast(); + } else if (op.equals("profile")) { + runProfile(); } else { System.err.println("Error: Unknown command: " + op); showUsage(); @@ -423,6 +425,49 @@ public class Am { } } + private void runProfile() { + String profileFile = null; + boolean start = false; + + String process = nextArg(); + if (process == null) { + System.err.println("Error: No profile process supplied"); + showUsage(); + return; + } + + String cmd = nextArg(); + if ("start".equals(cmd)) { + start = true; + profileFile = nextArg(); + if (profileFile == null) { + System.err.println("Error: No profile file path supplied"); + showUsage(); + return; + } + } else if (!"stop".equals(cmd)) { + System.err.println("Error: Profile command " + cmd + " not valid"); + showUsage(); + return; + } + + try { + if (!mAm.profileControl(process, start, profileFile)) { + System.out.println("PROFILE FAILED on process " + process); + return; + } + } catch (IllegalArgumentException e) { + System.out.println("PROFILE FAILED: " + e.getMessage()); + return; + } catch (IllegalStateException e) { + System.out.println("PROFILE FAILED: " + e.getMessage()); + return; + } catch (RemoteException e) { + System.out.println("PROFILE FAILED: activity manager gone"); + return; + } + } + private String nextOption() { if (mNextArg >= mArgs.length) { return null; @@ -470,11 +515,12 @@ public class Am { } private void showUsage() { - System.err.println("usage: am [start|broadcast|instrument]"); + System.err.println("usage: am [start|broadcast|instrument|profile]"); System.err.println(" am start -D INTENT"); System.err.println(" am broadcast INTENT"); System.err.println(" am instrument [-r] [-e ] [-p ]"); System.err.println(" [-w] "); + System.err.println(" am profile [start |stop]"); System.err.println(""); System.err.println(" INTENT is described with:"); System.err.println(" [-a ] [-d ] [-t ]"); diff --git a/cmds/dumpstate/dumpstate.c b/cmds/dumpstate/dumpstate.c index dea269dcf3bed31672782d78a6f71115a60b926f..eabf98e8d0e0feaae8144aaaf89bfa86692a17dc 100644 --- a/cmds/dumpstate/dumpstate.c +++ b/cmds/dumpstate/dumpstate.c @@ -40,6 +40,18 @@ static void dumpstate(int full) { PRINT("========================================================"); PRINT("== dumpstate"); PRINT("========================================================"); + PRINT("------ MEMORY INFO ------"); + DUMP("/proc/meminfo"); + PRINT("------ CPU INFO ------"); + EXEC7("top", "-n", "1", "-d", "1", "-m", "30", "-t"); + PRINT("------ PROCRANK ------"); + EXEC_XBIN("procrank"); + PRINT("------ VIRTUAL MEMORY STATS ------"); + DUMP("/proc/vmstat"); + PRINT("------ SLAB INFO ------"); + DUMP("/proc/slabinfo"); + PRINT("------ ZONEINFO ------"); + DUMP("/proc/zoneinfo"); PRINT("------ SYSTEM LOG ------"); EXEC4("logcat", "-v", "time", "-d", "*:v"); PRINT("------ VM TRACES ------"); @@ -67,20 +79,8 @@ static void dumpstate(int full) { EXEC("ps"); PRINT("------ PROCESSES AND THREADS ------"); EXEC2("ps", "-t", "-p"); - PRINT("------ MEMORY INFO ------"); - DUMP("/proc/meminfo"); - PRINT("------ PSS INFO ------"); - EXEC8("top", "-n", "1", "-d", "0", "-m", "15", "-s", "pss"); - PRINT("------ PROCRANK ------"); - EXEC("procrank"); PRINT("------ LIBRANK ------"); - EXEC("librank"); - PRINT("------ VIRTUAL MEMORY STATS ------"); - DUMP("/proc/vmstat"); - PRINT("------ SLAB INFO ------"); - DUMP("/proc/slabinfo"); - PRINT("------ ZONEINFO ------"); - DUMP("/proc/zoneinfo"); + EXEC_XBIN("librank"); PRINT("------ BINDER FAILED TRANSACTION LOG ------"); DUMP("/proc/binder/failed_transaction_log"); PRINT(""); @@ -127,7 +127,10 @@ static void dumpstate(int full) { PRINT("========================================================"); PRINT("== dumpsys"); PRINT("========================================================"); - EXEC("dumpsys"); + /* the full dumpsys is starting to take a long time, so we need + to increase its timeout. we really need to do the timeouts in + dumpsys itself... */ + EXEC_TIMEOUT("dumpsys", 60); } } @@ -224,6 +227,8 @@ int main(int argc, char *argv[]) { } if (compress) strcat(path, ".gz"); + else + strcat(path, ".txt"); /* ensure that all directories in the path exist */ create_directories(path); diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h index b956f99ce9dba355c9016b1be31eaac2c24afe48..6862e5a3edb415862259c62a1053531a9f17ea5a 100644 --- a/cmds/dumpstate/dumpstate.h +++ b/cmds/dumpstate/dumpstate.h @@ -19,8 +19,8 @@ #include -// Commands time out after 15 seconds -#define TIMEOUT 15 +// Commands time out after 60 seconds +#define TIMEOUT 60 #define PRINT(s) printf("%s\n", s) @@ -43,6 +43,24 @@ run_command(&c, TIMEOUT); \ } +#define EXEC_TIMEOUT(cmd, tmout)\ +{ \ + static struct Command c = { \ + "/system/bin/" cmd, \ + { cmd, 0 } \ + }; \ + run_command(&c, tmout); \ +} + +#define EXEC_XBIN(cmd) \ +{ \ + static struct Command c = { \ + "/system/xbin/" cmd, \ + { cmd, 0 } \ + }; \ + run_command(&c, TIMEOUT); \ +} + #define EXEC2(cmd, a1, a2) \ { \ static struct Command c = { \ @@ -70,6 +88,15 @@ run_command(&c, TIMEOUT); \ } +#define EXEC7(cmd, a1, a2, a3, a4, a5, a6, a7) \ +{ \ + static struct Command c = { \ + "/system/bin/" cmd, \ + { cmd, a1, a2, a3, a4, a5, a6, a7, 0 } \ + }; \ + run_command(&c, TIMEOUT); \ +} + #define EXEC8(cmd, a1, a2, a3, a4, a5, a6, a7, a8) \ { \ static struct Command c = { \ diff --git a/cmds/installd/commands.c b/cmds/installd/commands.c index a3651b23e5190c0352abc1e4096c22939f1ce189..70a1206b11ecbad1cafaa8da22aa45d79101e5e1 100644 --- a/cmds/installd/commands.c +++ b/cmds/installd/commands.c @@ -413,7 +413,8 @@ int create_cache_path(char path[PKG_PATH_MAX], const char *src) return 0; } -static void run_dexopt(int zip_fd, int odex_fd, const char* input_file_name) +static void run_dexopt(int zip_fd, int odex_fd, const char* input_file_name, + const char* dexopt_flags) { static const char* DEX_OPT_BIN = "/system/bin/dexopt"; static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig @@ -424,7 +425,7 @@ static void run_dexopt(int zip_fd, int odex_fd, const char* input_file_name) sprintf(odex_num, "%d", odex_fd); execl(DEX_OPT_BIN, DEX_OPT_BIN, "--zip", zip_num, odex_num, input_file_name, - (char*) NULL); + dexopt_flags, (char*) NULL); LOGE("execl(%s) failed: %s\n", DEX_OPT_BIN, strerror(errno)); } @@ -465,6 +466,7 @@ int dexopt(const char *apk_path, uid_t uid, int is_public) struct utimbuf ut; struct stat apk_stat, dex_stat; char dex_path[PKG_PATH_MAX]; + char dexopt_flags[PROPERTY_VALUE_MAX]; char *end; int res, zip_fd=-1, odex_fd=-1; @@ -475,6 +477,9 @@ int dexopt(const char *apk_path, uid_t uid, int is_public) return -1; } + /* platform-specific flags affecting optimization and verification */ + property_get("dalvik.vm.dexopt-flags", dexopt_flags, ""); + strcpy(dex_path, apk_path); end = strrchr(dex_path, '.'); if (end != NULL) { @@ -533,8 +538,8 @@ int dexopt(const char *apk_path, uid_t uid, int is_public) exit(66); } - run_dexopt(zip_fd, odex_fd, apk_path); /* does not return */ - exit(67); + run_dexopt(zip_fd, odex_fd, apk_path, dexopt_flags); + exit(67); /* only get here on exec failure */ } else { res = wait_dexopt(pid, apk_path); if (res != 0) { diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java index 4dc4b6a48b85f9caad4234b8e29fafdc9260840c..849a37dc95a964dfcac7637ea5dfc3135e84396b 100644 --- a/core/java/android/app/Activity.java +++ b/core/java/android/app/Activity.java @@ -53,6 +53,7 @@ import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; +import android.view.ViewManager; import android.view.Window; import android.view.WindowManager; import android.view.ContextMenu.ContextMenuInfo; @@ -93,11 +94,11 @@ import java.util.HashMap; * {@link android.R.styleable#AndroidManifestActivity <activity>} * declaration in their package's AndroidManifest.xml.

* - *

The Activity class is an important part of an - * application's overall lifecycle, + *

The Activity class is an important part of an application's overall lifecycle, * and the way activities are launched and put together is a fundamental - * part of the platform's - * application model.

+ * part of the platform's application model. For a detailed perspective on the structure of + * Android applications and lifecycles, please read the Dev Guide document on + * Application Fundamentals.

* *

Topics covered here: *

    @@ -527,7 +528,7 @@ import java.util.HashMap; * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>} * element in their own manifest to be able to start that activity. * - *

    See the Security Model + *

    See the Security and Permissions * document for more information on permissions and security in general. * * @@ -629,6 +630,9 @@ public class Activity extends ContextThemeWrapper private WindowManager mWindowManager; /*package*/ View mDecor = null; + /*package*/ boolean mWindowAdded = false; + /*package*/ boolean mVisibleFromServer = false; + /*package*/ boolean mVisibleFromClient = true; private CharSequence mTitle; private int mTitleColor = 0; @@ -779,6 +783,8 @@ public class Activity extends ContextThemeWrapper * @see #onPostCreate */ protected void onCreate(Bundle savedInstanceState) { + mVisibleFromClient = mWindow.getWindowStyle().getBoolean( + com.android.internal.R.styleable.Window_windowNoDisplay, true); mCalled = true; } @@ -884,9 +890,9 @@ public class Activity extends ContextThemeWrapper } /** - * Called after {@link #onCreate} or {@link #onStop} when the current - * activity is now being displayed to the user. It will - * be followed by {@link #onRestart}. + * Called after {@link #onCreate} — or after {@link #onRestart} when + * the activity had been stopped, but is now again being displayed to the + * user. It will be followed by {@link #onResume}. * *

    Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be @@ -901,9 +907,9 @@ public class Activity extends ContextThemeWrapper } /** - * Called after {@link #onStart} when the current activity is being + * Called after {@link #onStop} when the current activity is being * re-displayed to the user (the user has navigated back to it). It will - * be followed by {@link #onResume}. + * be followed by {@link #onStart} and then {@link #onResume}. * *

    For activities that are using raw {@link Cursor} objects (instead of * creating them through @@ -917,6 +923,7 @@ public class Activity extends ContextThemeWrapper * thrown.

    * * @see #onStop + * @see #onStart * @see #onResume */ protected void onRestart() { @@ -1134,12 +1141,19 @@ public class Activity extends ContextThemeWrapper /** * Called as part of the activity lifecycle when an activity is about to go * into the background as the result of user choice. For example, when the - * user presses the Home key, {@link #onUserLeaving} will be called, but + * user presses the Home key, {@link #onUserLeaveHint} will be called, but * when an incoming phone call causes the in-call Activity to be automatically - * brought to the foreground, {@link #onUserLeaving} will not be called on - * the activity being interrupted. + * brought to the foreground, {@link #onUserLeaveHint} will not be called on + * the activity being interrupted. In cases when it is invoked, this method + * is called right before the activity's {@link #onPause} callback. + * + *

    This callback and {@link #onUserInteraction} are intended to help + * activities manage status bar notifications intelligently; specifically, + * for helping activities determine the proper time to cancel a notfication. + * + * @see #onUserInteraction() */ - protected void onUserLeaving() { + protected void onUserLeaveHint() { } /** @@ -1207,7 +1221,7 @@ public class Activity extends ContextThemeWrapper /** * Called when you are no longer visible to the user. You will next - * receive either {@link #onStart}, {@link #onDestroy}, or nothing, + * receive either {@link #onRestart}, {@link #onDestroy}, or nothing, * depending on later user activity. * *

    Note that this method may never be called, in low memory situations @@ -1443,7 +1457,6 @@ public class Activity extends ContextThemeWrapper * @return The Cursor that was returned by query(). * * @see ContentResolver#query(android.net.Uri , String[], String, String[], String) - * @see #managedCommitUpdates * @see #startManagingCursor * @hide */ @@ -1475,7 +1488,6 @@ public class Activity extends ContextThemeWrapper * @return The Cursor that was returned by query(). * * @see ContentResolver#query(android.net.Uri , String[], String, String[], String) - * @see #managedCommitUpdates * @see #startManagingCursor */ public final Cursor managedQuery(Uri uri, @@ -1863,6 +1875,28 @@ public class Activity extends ContextThemeWrapper return false; } + /** + * Called whenever a key, touch, or trackball event is dispatched to the + * activity. Implement this method if you wish to know that the user has + * interacted with the device in some way while your activity is running. + * This callback and {@link #onUserLeaveHint} are intended to help + * activities manage status bar notifications intelligently; specifically, + * for helping activities determine the proper time to cancel a notfication. + * + *

    All calls to your activity's {@link #onUserLeaveHint} callback will + * be accompanied by calls to {@link #onUserInteraction}. This + * ensures that your activity will be told of relevant user activity such + * as pulling down the notification pane and touching an item there. + * + *

    Note that this callback will be invoked for the touch down action + * that begins a touch gesture, but may not be invoked for the touch-moved + * and touch-up actions that follow. + * + * @see #onUserLeaveHint() + */ + public void onUserInteraction() { + } + public void onWindowAttributesChanged(WindowManager.LayoutParams params) { // Update window manager if: we have a view, that view is // attached to its parent (which will be a RootView), and @@ -1935,6 +1969,7 @@ public class Activity extends ContextThemeWrapper * @return boolean Return true if this event was consumed. */ public boolean dispatchKeyEvent(KeyEvent event) { + onUserInteraction(); if (getWindow().superDispatchKeyEvent(event)) { return true; } @@ -1952,6 +1987,9 @@ public class Activity extends ContextThemeWrapper * @return boolean Return true if this event was consumed. */ public boolean dispatchTouchEvent(MotionEvent ev) { + if (ev.getAction() == MotionEvent.ACTION_DOWN) { + onUserInteraction(); + } if (getWindow().superDispatchTouchEvent(ev)) { return true; } @@ -1969,6 +2007,7 @@ public class Activity extends ContextThemeWrapper * @return boolean Return true if this event was consumed. */ public boolean dispatchTrackballEvent(MotionEvent ev) { + onUserInteraction(); if (getWindow().superDispatchTrackballEvent(ev)) { return true; } @@ -2864,6 +2903,35 @@ public class Activity extends ContextThemeWrapper } } + /** + * Control whether this activity's main window is visible. This is intended + * only for the special case of an activity that is not going to show a + * UI itself, but can't just finish prior to onResume() because it needs + * to wait for a service binding or such. Setting this to false allows + * you to prevent your UI from being shown during that time. + * + *

    The default value for this is taken from the + * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme. + */ + public void setVisible(boolean visible) { + if (mVisibleFromClient != visible) { + mVisibleFromClient = visible; + if (mVisibleFromServer) { + if (visible) makeVisible(); + else mDecor.setVisibility(View.INVISIBLE); + } + } + } + + void makeVisible() { + if (!mWindowAdded) { + ViewManager wm = getWindowManager(); + wm.addView(mDecor, getWindow().getAttributes()); + mWindowAdded = true; + } + mDecor.setVisibility(View.VISIBLE); + } + /** * Check to see whether this activity is in the process of finishing, * either because you called {@link #finish} on it or someone else @@ -3482,7 +3550,8 @@ public class Activity extends ContextThemeWrapper } final void performUserLeaving() { - onUserLeaving(); + onUserInteraction(); + onUserLeaveHint(); } final void performStop() { diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java index f9b92218c56a97acb3df75155d27c2d498f2e406..07520c9d65f7dc57cc2bb9ee08bfe621006fe32d 100644 --- a/core/java/android/app/ActivityManager.java +++ b/core/java/android/app/ActivityManager.java @@ -19,16 +19,14 @@ package android.app; import android.content.ComponentName; import android.content.Context; import android.content.Intent; +import android.content.pm.ConfigurationInfo; import android.content.pm.IPackageDataObserver; import android.graphics.Bitmap; import android.os.RemoteException; import android.os.Handler; -import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; -import android.os.Parcelable.Creator; import android.text.TextUtils; -import android.util.Log; import java.util.List; /** @@ -617,7 +615,59 @@ public class ActivityManager { public String pkgList[]; + /** + * Constant for {@link #importance}: this process is running the + * foreground UI. + */ + public static final int IMPORTANCE_FOREGROUND = 100; + + /** + * Constant for {@link #importance}: this process is running something + * that is considered to be actively visible to the user. + */ + public static final int IMPORTANCE_VISIBLE = 200; + + /** + * Constant for {@link #importance}: this process is contains services + * that should remain running. + */ + public static final int IMPORTANCE_SERVICE = 300; + + /** + * Constant for {@link #importance}: this process process contains + * background code that is expendable. + */ + public static final int IMPORTANCE_BACKGROUND = 400; + + /** + * Constant for {@link #importance}: this process is empty of any + * actively running code. + */ + public static final int IMPORTANCE_EMPTY = 500; + + /** + * The relative importance level that the system places on this + * process. May be one of {@link #IMPORTANCE_FOREGROUND}, + * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE}, + * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}. These + * constants are numbered so that "more important" values are always + * smaller than "less important" values. + */ + public int importance; + + /** + * An additional ordering within a particular {@link #importance} + * category, providing finer-grained information about the relative + * utility of processes within a category. This number means nothing + * except that a smaller values are more recently used (and thus + * more important). Currently an LRU value is only maintained for + * the {@link #IMPORTANCE_BACKGROUND} category, though others may + * be maintained in the future. + */ + public int lru; + public RunningAppProcessInfo() { + importance = IMPORTANCE_FOREGROUND; } public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) { @@ -634,12 +684,16 @@ public class ActivityManager { dest.writeString(processName); dest.writeInt(pid); dest.writeStringArray(pkgList); + dest.writeInt(importance); + dest.writeInt(lru); } public void readFromParcel(Parcel source) { processName = source.readString(); pid = source.readInt(); pkgList = source.readStringArray(); + importance = source.readInt(); + lru = source.readInt(); } public static final Creator CREATOR = @@ -671,4 +725,37 @@ public class ActivityManager { return null; } } + + /** + * Have the system perform a force stop of everything associated with + * the given application package. All processes that share its uid + * will be killed, all services it has running stopped, all activities + * removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED} + * broadcast will be sent, so that any of its registered alarms can + * be stopped, notifications removed, etc. + * + *

    You must hold the permission + * {@link android.Manifest.permission#RESTART_PACKAGES} to be able to + * call this method. + * + * @param packageName The name of the package to be stopped. + */ + public void restartPackage(String packageName) { + try { + ActivityManagerNative.getDefault().restartPackage(packageName); + } catch (RemoteException e) { + } + } + + /** + * Get the device configuration attributes. + */ + public ConfigurationInfo getDeviceConfigurationInfo() { + try { + return ActivityManagerNative.getDefault().getDeviceConfigurationInfo(); + } catch (RemoteException e) { + } + return null; + } + } diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java index ae9f3bf15029c2d664531aa4f4cedf94f5d5abe7..53e6f34a691564b24565339eb7f813c68101550e 100644 --- a/core/java/android/app/ActivityManagerNative.java +++ b/core/java/android/app/ActivityManagerNative.java @@ -20,6 +20,7 @@ import android.content.ComponentName; import android.content.ContentResolver; import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.ConfigurationInfo; import android.content.pm.IPackageDataObserver; import android.content.res.Configuration; import android.graphics.Bitmap; @@ -82,6 +83,17 @@ public abstract class ActivityManagerNative extends Binder implements IActivityM return gDefault; } + /** + * Convenience for checking whether the system is ready. For internal use only. + */ + static public boolean isSystemReady() { + if (!sSystemReady) { + sSystemReady = getDefault().testIsSystemReady(); + } + return sSystemReady; + } + static boolean sSystemReady = false; + /** * Convenience for sending a sticky broadcast. For internal use only. * If you don't care about permission, use null. @@ -959,6 +971,34 @@ public abstract class ActivityManagerNative extends Binder implements IActivityM return true; } + case GET_DEVICE_CONFIGURATION_TRANSACTION: { + data.enforceInterface(IActivityManager.descriptor); + ConfigurationInfo config = getDeviceConfigurationInfo(); + reply.writeNoException(); + config.writeToParcel(reply, 0); + return true; + } + + case PROFILE_CONTROL_TRANSACTION: { + data.enforceInterface(IActivityManager.descriptor); + String process = data.readString(); + boolean start = data.readInt() != 0; + String path = data.readString(); + boolean res = profileControl(process, start, path); + reply.writeNoException(); + reply.writeInt(res ? 1 : 0); + return true; + } + + case PEEK_SERVICE_TRANSACTION: { + data.enforceInterface(IActivityManager.descriptor); + Intent service = Intent.CREATOR.createFromParcel(data); + String resolvedType = data.readString(); + IBinder binder = peekService(service, resolvedType); + reply.writeNoException(); + reply.writeStrongBinder(binder); + return true; + } } return super.onTransact(code, data, reply, flags); @@ -1604,6 +1644,20 @@ class ActivityManagerProxy implements IActivityManager data.recycle(); reply.recycle(); } + + public IBinder peekService(Intent service, String resolvedType) throws RemoteException { + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + data.writeInterfaceToken(IActivityManager.descriptor); + service.writeToParcel(data, 0); + data.writeString(resolvedType); + mRemote.transact(PEEK_SERVICE_TRANSACTION, data, reply, 0); + reply.readException(); + IBinder binder = reply.readStrongBinder(); + reply.recycle(); + data.recycle(); + return binder; + } public boolean startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher) @@ -2028,6 +2082,11 @@ class ActivityManagerProxy implements IActivityManager data.recycle(); reply.recycle(); } + public boolean testIsSystemReady() + { + /* this base class version is never called */ + return true; + } public int handleApplicationError(IBinder app, int flags, String tag, String shortMsg, String longMsg, byte[] crashData) throws RemoteException @@ -2071,5 +2130,35 @@ class ActivityManagerProxy implements IActivityManager reply.recycle(); } + public ConfigurationInfo getDeviceConfigurationInfo() throws RemoteException + { + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + data.writeInterfaceToken(IActivityManager.descriptor); + mRemote.transact(GET_DEVICE_CONFIGURATION_TRANSACTION, data, reply, 0); + reply.readException(); + ConfigurationInfo res = ConfigurationInfo.CREATOR.createFromParcel(reply); + reply.recycle(); + data.recycle(); + return res; + } + + public boolean profileControl(String process, boolean start, + String path) throws RemoteException + { + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + data.writeInterfaceToken(IActivityManager.descriptor); + data.writeString(process); + data.writeInt(start ? 1 : 0); + data.writeString(path); + mRemote.transact(PROFILE_CONTROL_TRANSACTION, data, reply, 0); + reply.readException(); + boolean res = reply.readInt() != 0; + reply.recycle(); + data.recycle(); + return res; + } + private IBinder mRemote; } diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java index e4c1057e3878de2c12e28bc16b7be4bbc37a42f2..f49005ec0e5c9a7380a0a8334e489259d59f1b65 100644 --- a/core/java/android/app/ActivityThread.java +++ b/core/java/android/app/ActivityThread.java @@ -144,13 +144,19 @@ public final class ActivityThread { return sPackageManager; } - DisplayMetrics getDisplayMetricsLocked() { + DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) { + if (mDisplayMetrics != null && !forceUpdate) { + return mDisplayMetrics; + } if (mDisplay == null) { WindowManager wm = WindowManagerImpl.getDefault(); mDisplay = wm.getDefaultDisplay(); } - DisplayMetrics metrics = new DisplayMetrics(); + DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics(); mDisplay.getMetrics(metrics); + //Log.i("foo", "New metrics: w=" + metrics.widthPixels + " h=" + // + metrics.heightPixels + " den=" + metrics.density + // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi); return metrics; } @@ -173,7 +179,7 @@ public final class ActivityThread { if (assets.addAssetPath(appDir) == 0) { return null; } - DisplayMetrics metrics = getDisplayMetricsLocked(); + DisplayMetrics metrics = getDisplayMetricsLocked(false); r = new Resources(assets, metrics, getConfiguration()); //Log.i(TAG, "Created app resources " + r + ": " + r.getConfiguration()); // XXX need to remove entries when weak references go away @@ -235,7 +241,7 @@ public final class ActivityThread { ApplicationContext.createSystemContext(mainThread); mSystemContext.getResources().updateConfiguration( mainThread.getConfiguration(), - mainThread.getDisplayMetricsLocked()); + mainThread.getDisplayMetricsLocked(false)); //Log.i(TAG, "Created system resources " // + mSystemContext.getResources() + ": " // + mSystemContext.getResources().getConfiguration()); @@ -1205,7 +1211,10 @@ public final class ActivityThread { private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s"; private static final String ONE_COUNT_COLUMN = "%17s %8d"; private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d"; - + + // Formatting for checkin service - update version if row format changes + private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1; + public final void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges) { queueOrSendMessage( @@ -1440,6 +1449,10 @@ public final class ActivityThread { } } + public void profilerControl(boolean start, String path) { + queueOrSendMessage(H.PROFILER_CONTROL, path, start ? 1 : 0); + } + @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { long nativeMax = Debug.getNativeHeapSize() / 1024; @@ -1462,7 +1475,101 @@ public final class ActivityThread { long dalvikMax = runtime.totalMemory() / 1024; long dalvikFree = runtime.freeMemory() / 1024; long dalvikAllocated = dalvikMax - dalvikFree; - + long viewInstanceCount = ViewDebug.getViewInstanceCount(); + long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount(); + long appContextInstanceCount = ApplicationContext.getInstanceCount(); + long activityInstanceCount = Activity.getInstanceCount(); + int globalAssetCount = AssetManager.getGlobalAssetCount(); + int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount(); + int binderLocalObjectCount = Debug.getBinderLocalObjectCount(); + int binderProxyObjectCount = Debug.getBinderProxyObjectCount(); + int binderDeathObjectCount = Debug.getBinderDeathObjectCount(); + int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount(); + long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024; + SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats(); + SQLiteDebug.getPagerStats(stats); + + // Check to see if we were called by checkin server. If so, print terse format. + boolean doCheckinFormat = false; + if (args != null) { + for (String arg : args) { + if ("-c".equals(arg)) doCheckinFormat = true; + } + } + + // For checkin, we print one long comma-separated list of values + if (doCheckinFormat) { + // NOTE: if you change anything significant below, also consider changing + // ACTIVITY_THREAD_CHECKIN_VERSION. + String processName = (mBoundApplication != null) + ? mBoundApplication.processName : "unknown"; + + // Header + pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(','); + pw.print(Process.myPid()); pw.print(','); + pw.print(processName); pw.print(','); + + // Heap info - max + pw.print(nativeMax); pw.print(','); + pw.print(dalvikMax); pw.print(','); + pw.print("N/A,"); + pw.print(nativeMax + dalvikMax); pw.print(','); + + // Heap info - allocated + pw.print(nativeAllocated); pw.print(','); + pw.print(dalvikAllocated); pw.print(','); + pw.print("N/A,"); + pw.print(nativeAllocated + dalvikAllocated); pw.print(','); + + // Heap info - free + pw.print(nativeFree); pw.print(','); + pw.print(dalvikFree); pw.print(','); + pw.print("N/A,"); + pw.print(nativeFree + dalvikFree); pw.print(','); + + // Heap info - proportional set size + pw.print(memInfo.nativePss); pw.print(','); + pw.print(memInfo.dalvikPss); pw.print(','); + pw.print(memInfo.otherPss); pw.print(','); + pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(','); + + // Heap info - shared + pw.print(nativeShared); pw.print(','); + pw.print(dalvikShared); pw.print(','); + pw.print(otherShared); pw.print(','); + pw.print(nativeShared + dalvikShared + otherShared); pw.print(','); + + // Heap info - private + pw.print(nativePrivate); pw.print(','); + pw.print(dalvikPrivate); pw.print(','); + pw.print(otherPrivate); pw.print(','); + pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(','); + + // Object counts + pw.print(viewInstanceCount); pw.print(','); + pw.print(viewRootInstanceCount); pw.print(','); + pw.print(appContextInstanceCount); pw.print(','); + pw.print(activityInstanceCount); pw.print(','); + + pw.print(globalAssetCount); pw.print(','); + pw.print(globalAssetManagerCount); pw.print(','); + pw.print(binderLocalObjectCount); pw.print(','); + pw.print(binderProxyObjectCount); pw.print(','); + + pw.print(binderDeathObjectCount); pw.print(','); + pw.print(openSslSocketCount); pw.print(','); + + // SQL + pw.print(sqliteAllocated); pw.print(','); + pw.print(stats.databaseBytes / 1024); pw.print(','); + pw.print(stats.numPagers); pw.print(','); + pw.print((stats.totalBytes - stats.referencedBytes) / 1024); pw.print(','); + pw.print(stats.referencedBytes / 1024); pw.print('\n'); + + return; + } + + // otherwise, show human-readable format printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total"); printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax); printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A", @@ -1480,26 +1587,22 @@ public final class ActivityThread { pw.println(" "); pw.println(" Objects"); - printRow(pw, TWO_COUNT_COLUMNS, "Views:", ViewDebug.getViewInstanceCount(), "ViewRoots:", - ViewDebug.getViewRootInstanceCount()); + printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:", + viewRootInstanceCount); - printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", ApplicationContext.getInstanceCount(), - "Activities:", Activity.getInstanceCount()); + printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount, + "Activities:", activityInstanceCount); - printRow(pw, TWO_COUNT_COLUMNS, "Assets:", AssetManager.getGlobalAssetCount(), - "AssetManagers:", AssetManager.getGlobalAssetManagerCount()); + printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount, + "AssetManagers:", globalAssetManagerCount); - printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", Debug.getBinderLocalObjectCount(), - "Proxy Binders:", Debug.getBinderProxyObjectCount()); - printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", Debug.getBinderDeathObjectCount()); - - printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", OpenSSLSocketImpl.getInstanceCount()); + printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount, + "Proxy Binders:", binderProxyObjectCount); + printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount); + printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount); + // SQLite mem info - long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024; - SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats(); - SQLiteDebug.getPagerStats(stats); - pw.println(" "); pw.println(" SQL"); printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "dbFiles:", @@ -1542,6 +1645,7 @@ public final class ActivityThread { public static final int LOW_MEMORY = 124; public static final int ACTIVITY_CONFIGURATION_CHANGED = 125; public static final int RELAUNCH_ACTIVITY = 126; + public static final int PROFILER_CONTROL = 127; String codeToString(int code) { if (localLOGV) { switch (code) { @@ -1572,6 +1676,7 @@ public final class ActivityThread { case LOW_MEMORY: return "LOW_MEMORY"; case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED"; case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY"; + case PROFILER_CONTROL: return "PROFILER_CONTROL"; } } return "(unknown)"; @@ -1671,6 +1776,9 @@ public final class ActivityThread { case ACTIVITY_CONFIGURATION_CHANGED: handleActivityConfigurationChanged((IBinder)msg.obj); break; + case PROFILER_CONTROL: + handleProfilerControl(msg.arg1 != 0, (String)msg.obj); + break; } } } @@ -1751,6 +1859,7 @@ public final class ActivityThread { final HashMap> mResourcePackages = new HashMap>(); Display mDisplay = null; + DisplayMetrics mDisplayMetrics = null; HashMap > mActiveResources = new HashMap >(); @@ -1918,7 +2027,7 @@ public final class ActivityThread { PackageInfo info = new PackageInfo(this, "android", context); context.init(info, null, this); context.getResources().updateConfiguration( - getConfiguration(), getDisplayMetricsLocked()); + getConfiguration(), getDisplayMetricsLocked(false)); mSystemContext = context; //Log.i(TAG, "Created system resources " + context.getResources() // + ": " + context.getResources().getConfiguration()); @@ -2557,7 +2666,10 @@ public final class ActivityThread { a.mDecor = decor; l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; l.softInputMode |= forwardBit; - wm.addView(decor, l); + if (a.mVisibleFromClient) { + a.mWindowAdded = true; + wm.addView(decor, l); + } // If the window has already been added, but during resume // we started another activity, then don't yet make the @@ -2576,7 +2688,8 @@ public final class ActivityThread { performConfigurationChanged(r.activity, r.newConfig); r.newConfig = null; } - Log.v(TAG, "Resuming " + r + " with isForward=" + isForward); + if (localLOGV) Log.v(TAG, "Resuming " + r + " with isForward=" + + isForward); WindowManager.LayoutParams l = r.window.getAttributes(); if ((l.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) @@ -2588,8 +2701,11 @@ public final class ActivityThread { View decor = r.window.getDecorView(); wm.updateViewLayout(decor, l); } - r.activity.mDecor.setVisibility(View.VISIBLE); + r.activity.mVisibleFromServer = true; mNumVisibleActivities++; + if (r.activity.mVisibleFromClient) { + r.activity.makeVisible(); + } } r.nextIdle = mNewActivities; @@ -2800,18 +2916,22 @@ public final class ActivityThread { View v = r.activity.mDecor; if (v != null) { if (show) { - if (v.getVisibility() != View.VISIBLE) { - v.setVisibility(View.VISIBLE); + if (!r.activity.mVisibleFromServer) { + r.activity.mVisibleFromServer = true; mNumVisibleActivities++; + if (r.activity.mVisibleFromClient) { + r.activity.makeVisible(); + } } if (r.newConfig != null) { performConfigurationChanged(r.activity, r.newConfig); r.newConfig = null; } } else { - if (v.getVisibility() == View.VISIBLE) { - v.setVisibility(View.INVISIBLE); + if (r.activity.mVisibleFromServer) { + r.activity.mVisibleFromServer = false; mNumVisibleActivities--; + v.setVisibility(View.INVISIBLE); } } } @@ -3037,11 +3157,13 @@ public final class ActivityThread { WindowManager wm = r.activity.getWindowManager(); View v = r.activity.mDecor; if (v != null) { - if (v.getVisibility() == View.VISIBLE) { + if (r.activity.mVisibleFromServer) { mNumVisibleActivities--; } IBinder wtoken = v.getWindowToken(); - wm.removeViewImmediate(v); + if (r.activity.mWindowAdded) { + wm.removeViewImmediate(v); + } if (wtoken != null) { WindowManagerImpl.getDefault().closeAll(wtoken, r.activity.getClass().getName(), "Activity"); @@ -3271,6 +3393,7 @@ public final class ActivityThread { mConfiguration = new Configuration(); } mConfiguration.updateFrom(config); + DisplayMetrics dm = getDisplayMetricsLocked(true); // set it for java, this also affects newly created Resources if (config.locale != null) { @@ -3290,7 +3413,7 @@ public final class ActivityThread { WeakReference v = it.next(); Resources r = v.get(); if (r != null) { - r.updateConfiguration(config, null); + r.updateConfiguration(config, dm); //Log.i(TAG, "Updated app resources " + v.getKey() // + " " + r + ": " + r.getConfiguration()); } else { @@ -3318,6 +3441,21 @@ public final class ActivityThread { performConfigurationChanged(r.activity, mConfiguration); } + final void handleProfilerControl(boolean start, String path) { + if (start) { + File file = new File(path); + file.getParentFile().mkdirs(); + try { + Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024); + } catch (RuntimeException e) { + Log.w(TAG, "Profiling failed on path " + path + + " -- can the process access this path?"); + } + } else { + Debug.stopMethodTracing(); + } + } + final void handleLowMemory() { ArrayList callbacks = new ArrayList(); diff --git a/core/java/android/app/ApplicationContext.java b/core/java/android/app/ApplicationContext.java index 4236a00e1b58f2a4e6de9b8cb19ce0eb578e05ba..3b5ad862710f53fd9f962b7594c7208d27a6a30d 100644 --- a/core/java/android/app/ApplicationContext.java +++ b/core/java/android/app/ApplicationContext.java @@ -1487,7 +1487,7 @@ class ApplicationContext extends Context { static final class ApplicationPackageManager extends PackageManager { @Override public PackageInfo getPackageInfo(String packageName, int flags) - throws NameNotFoundException { + throws NameNotFoundException { try { PackageInfo pi = mPM.getPackageInfo(packageName, flags); if (pi != null) { @@ -1500,6 +1500,43 @@ class ApplicationContext extends Context { throw new NameNotFoundException(packageName); } + public Intent getLaunchIntentForPackage(String packageName) + throws NameNotFoundException { + // First see if the package has an INFO activity; the existence of + // such an activity is implied to be the desired front-door for the + // overall package (such as if it has multiple launcher entries). + Intent intent = getLaunchIntentForPackageCategory(this, packageName, + Intent.CATEGORY_INFO); + if (intent != null) { + return intent; + } + + // Otherwise, try to find a main launcher activity. + return getLaunchIntentForPackageCategory(this, packageName, + Intent.CATEGORY_LAUNCHER); + } + + // XXX This should be implemented as a call to the package manager, + // to reduce the work needed. + static Intent getLaunchIntentForPackageCategory(PackageManager pm, + String packageName, String category) { + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + Intent intentToResolve = new Intent(Intent.ACTION_MAIN, null); + intentToResolve.addCategory(category); + final List apps = + pm.queryIntentActivities(intentToResolve, 0); + // I wish there were a way to directly get the "main" activity of a + // package but ... + for (ResolveInfo app : apps) { + if (app.activityInfo.packageName.equals(packageName)) { + intent.setClassName(packageName, app.activityInfo.name); + return intent; + } + } + return null; + } + @Override public int[] getPackageGids(String packageName) throws NameNotFoundException { @@ -1629,6 +1666,15 @@ class ApplicationContext extends Context { throw new NameNotFoundException(className.toString()); } + @Override + public String[] getSystemSharedLibraryNames() { + try { + return mPM.getSystemSharedLibraryNames(); + } catch (RemoteException e) { + throw new RuntimeException("Package manager has died", e); + } + } + @Override public int checkPermission(String permName, String pkgName) { try { @@ -1974,6 +2020,18 @@ class ApplicationContext extends Context { getApplicationInfo(appPackageName, 0)); } + int mCachedSafeMode = -1; + @Override public boolean isSafeMode() { + try { + if (mCachedSafeMode < 0) { + mCachedSafeMode = mPM.isSafeMode() ? 1 : 0; + } + return mCachedSafeMode != 0; + } catch (RemoteException e) { + throw new RuntimeException("Package manager has died", e); + } + } + static void configurationChanged() { synchronized (sSync) { sIconCache.clear(); diff --git a/core/java/android/app/ApplicationThreadNative.java b/core/java/android/app/ApplicationThreadNative.java index d2cf55a427cce5ed3c2b671f1fada389122034a7..bcc9302082060c1ec0e8177d50cfe054432bfd41 100644 --- a/core/java/android/app/ApplicationThreadNative.java +++ b/core/java/android/app/ApplicationThreadNative.java @@ -322,6 +322,15 @@ public abstract class ApplicationThreadNative extends Binder requestPss(); return true; } + + case PROFILER_CONTROL_TRANSACTION: + { + data.enforceInterface(IApplicationThread.descriptor); + boolean start = data.readInt() != 0; + String path = data.readString(); + profilerControl(start, path); + return true; + } } return super.onTransact(code, data, reply, flags); @@ -654,5 +663,14 @@ class ApplicationThreadProxy implements IApplicationThread { data.recycle(); } + public void profilerControl(boolean start, String path) throws RemoteException { + Parcel data = Parcel.obtain(); + data.writeInterfaceToken(IApplicationThread.descriptor); + data.writeInt(start ? 1 : 0); + data.writeString(path); + mRemote.transact(PROFILER_CONTROL_TRANSACTION, data, null, + IBinder.FLAG_ONEWAY); + data.recycle(); + } } diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java index 951b48d5fad6dcd7336fb6b4a4084d3c20451cef..b09a57fb27a524b8e6ed5ae885d979e826d4cccc 100644 --- a/core/java/android/app/Dialog.java +++ b/core/java/android/app/Dialog.java @@ -122,7 +122,7 @@ public class Dialog implements DialogInterface, Window.Callback, * uses the window manager and theme from this context to * present its UI. * @param theme A style resource describing the theme to use for the - * window. See Style + * window. See Style * and Theme Resources for more information about defining and using * styles. This theme is applied on top of the current theme in * context. If 0, the default dialog theme will be used. @@ -518,7 +518,7 @@ public class Dialog implements DialogInterface, Window.Callback, private boolean isOutOfBounds(MotionEvent event) { final int x = (int) event.getX(); final int y = (int) event.getY(); - final int slop = ViewConfiguration.getWindowTouchSlop(); + final int slop = ViewConfiguration.get(mContext).getScaledWindowTouchSlop(); final View decorView = getWindow().getDecorView(); return (x < -slop) || (y < -slop) || (x > (decorView.getWidth()+slop)) diff --git a/core/java/android/app/ExpandableListActivity.java b/core/java/android/app/ExpandableListActivity.java index 75dfcae5a8f912083d3bfc42687bea7a391a0c33..a2e048f53f484dd28fcddcb7da838ee3841f8f2d 100644 --- a/core/java/android/app/ExpandableListActivity.java +++ b/core/java/android/app/ExpandableListActivity.java @@ -63,21 +63,21 @@ import java.util.Map; * *

      * <?xml version="1.0" encoding="UTF-8"?>
    - * <LinearLayout
    + * <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      *         android:orientation="vertical"
      *         android:layout_width="fill_parent" 
      *         android:layout_height="fill_parent"
    - *         android:paddingLeft="8"
    - *         android:paddingRight="8">
    + *         android:paddingLeft="8dp"
    + *         android:paddingRight="8dp">
      * 
    - *     <ExpandableListView id="android:list"
    + *     <ExpandableListView android:id="@id/android:list"
      *               android:layout_width="fill_parent" 
      *               android:layout_height="fill_parent"
      *               android:background="#00FF00"
      *               android:layout_weight="1"
      *               android:drawSelectorOnTop="false"/>
      * 
    - *     <TextView id="android:empty"
    + *     <TextView android:id="@id/android:empty"
      *               android:layout_width="fill_parent" 
      *               android:layout_height="fill_parent"
      *               android:background="#FF0000"
    @@ -113,19 +113,19 @@ import java.util.Map;
      * 
      * 
      * <?xml version="1.0" encoding="utf-8"?>
    - * <LinearLayout
    + * <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      *     android:layout_width="fill_parent"
      *     android:layout_height="wrap_content"
      *     android:orientation="vertical">
      * 
    - *     <TextView id="text1"
    - *         android:textSize="16"
    + *     <TextView android:id="@+id/text1"
    + *         android:textSize="16sp"
      *         android:textStyle="bold"
      *         android:layout_width="fill_parent"
      *         android:layout_height="wrap_content"/>
      * 
    - *     <TextView id="text2"
    - *         android:textSize="16"
    + *     <TextView android:id="@+id/text2"
    + *         android:textSize="16sp"
      *         android:layout_width="fill_parent"
      *         android:layout_height="wrap_content"/>
      * </LinearLayout>
    @@ -162,7 +162,8 @@ public class ExpandableListActivity extends Activity implements
     
         /**
          * Override this to populate the context menu when an item is long pressed. menuInfo
    -     * will contain a {@link AdapterContextMenuInfo} whose position is a packed position
    +     * will contain an {@link android.widget.ExpandableListView.ExpandableListContextMenuInfo}
    +     * whose packedPosition is a packed position
          * that should be used with {@link ExpandableListView#getPackedPositionType(long)} and
          * the other similar methods.
          * 

    diff --git a/core/java/android/app/IActivityManager.java b/core/java/android/app/IActivityManager.java index 353500e923459210aea7b38d1d27fdaa2661f53f..2ac6160cf83eb9a39a9e6bb9aacc8a190d092ae8 100644 --- a/core/java/android/app/IActivityManager.java +++ b/core/java/android/app/IActivityManager.java @@ -22,6 +22,7 @@ import android.content.ContentProviderNative; import android.content.IContentProvider; import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.ConfigurationInfo; import android.content.pm.IPackageDataObserver; import android.content.pm.ProviderInfo; import android.content.res.Configuration; @@ -127,7 +128,8 @@ public interface IActivityManager extends IInterface { boolean doRebind) throws RemoteException; /* oneway */ public void serviceDoneExecuting(IBinder token) throws RemoteException; - + public IBinder peekService(Intent service, String resolvedType) throws RemoteException; + public boolean startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher) throws RemoteException; @@ -216,6 +218,17 @@ public interface IActivityManager extends IInterface { // Retrieve running application processes in the system public List getRunningAppProcesses() throws RemoteException; + // Get device configuration + public ConfigurationInfo getDeviceConfigurationInfo() throws RemoteException; + + // Turn on/off profiling in a particular process. + public boolean profileControl(String process, boolean start, + String path) throws RemoteException; + + /* + * Private non-Binder interfaces + */ + /* package */ boolean testIsSystemReady(); /** Information you can retrieve about a particular application. */ public static class ContentProviderHolder implements Parcelable { @@ -354,4 +367,7 @@ public interface IActivityManager extends IInterface { int GET_SERVICES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+80; int REPORT_PSS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+81; int GET_RUNNING_APP_PROCESSES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+82; + int GET_DEVICE_CONFIGURATION_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+83; + int PEEK_SERVICE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+84; + int PROFILE_CONTROL_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+85; } diff --git a/core/java/android/app/IApplicationThread.java b/core/java/android/app/IApplicationThread.java index 47476b5da211675af00567c6c106ce1569127fbf..9f3534b0924acf594a16ae20e806d7932ee45ae9 100644 --- a/core/java/android/app/IApplicationThread.java +++ b/core/java/android/app/IApplicationThread.java @@ -86,6 +86,7 @@ public interface IApplicationThread extends IInterface { void scheduleLowMemory() throws RemoteException; void scheduleActivityConfigurationChanged(IBinder token) throws RemoteException; void requestPss() throws RemoteException; + void profilerControl(boolean start, String path) throws RemoteException; String descriptor = "android.app.IApplicationThread"; @@ -115,4 +116,5 @@ public interface IApplicationThread extends IInterface { int SCHEDULE_ACTIVITY_CONFIGURATION_CHANGED_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+24; int SCHEDULE_RELAUNCH_ACTIVITY_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+25; int REQUEST_PSS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+26; + int PROFILER_CONTROL_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+27; } diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java index f96d78710463ac3d16f186b9b7e2404babba604c..f6a28b23a3a89b362864751d8ebbea08dadfc20e 100644 --- a/core/java/android/app/Instrumentation.java +++ b/core/java/android/app/Instrumentation.java @@ -1267,7 +1267,7 @@ public class Instrumentation { } /** - * Perform calling of an activity's {@link Activity#onUserLeaving} method. + * Perform calling of an activity's {@link Activity#onUserLeaveHint} method. * The default implementation simply calls through to that method. * * @param activity The activity being notified that the user has navigated away diff --git a/core/java/android/app/IntentService.java b/core/java/android/app/IntentService.java new file mode 100644 index 0000000000000000000000000000000000000000..2b12a2a1304d133861d743bb9af145d3aefd4c3a --- /dev/null +++ b/core/java/android/app/IntentService.java @@ -0,0 +1,74 @@ +package android.app; + +import android.content.Intent; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.IBinder; +import android.os.Looper; +import android.os.Message; + +/** + * An abstract {@link Service} that serializes the handling of the Intents passed upon service + * start and handles them on a handler thread. + * + *

    To use this class extend it and implement {@link #onHandleIntent}. The {@link Service} will + * automatically be stopped when the last enqueued {@link Intent} is handled. + */ +public abstract class IntentService extends Service { + private volatile Looper mServiceLooper; + private volatile ServiceHandler mServiceHandler; + private String mName; + + private final class ServiceHandler extends Handler { + public ServiceHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + onHandleIntent((Intent)msg.obj); + stopSelf(msg.arg1); + } + } + + public IntentService(String name) { + super(); + mName = name; + } + + @Override + public void onCreate() { + super.onCreate(); + HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); + thread.start(); + + mServiceLooper = thread.getLooper(); + mServiceHandler = new ServiceHandler(mServiceLooper); + } + + @Override + public void onStart(Intent intent, int startId) { + super.onStart(intent, startId); + Message msg = mServiceHandler.obtainMessage(); + msg.arg1 = startId; + msg.obj = intent; + mServiceHandler.sendMessage(msg); + } + + @Override + public void onDestroy() { + mServiceLooper.quit(); + } + + @Override + public IBinder onBind(Intent intent) { + return null; + } + + /** + * Invoked on the Handler thread with the {@link Intent} that is passed to {@link #onStart}. + * Note that this will be invoked from a different thread than the one that handles the + * {@link #onStart} call. + */ + protected abstract void onHandleIntent(Intent intent); +} diff --git a/core/java/android/app/LauncherActivity.java b/core/java/android/app/LauncherActivity.java index 8f0a4f58fe5fc553bc567ee3ffeeb3bb63940a89..d6fcbb1a6aa7ec8004eb6d85ae4451e1f125f36c 100644 --- a/core/java/android/app/LauncherActivity.java +++ b/core/java/android/app/LauncherActivity.java @@ -18,14 +18,23 @@ package android.app; import android.content.Context; import android.content.Intent; -import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.PaintFlagsDrawFilter; +import android.graphics.PixelFormat; +import android.graphics.Rect; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.PaintDrawable; import android.os.Bundle; -import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.view.Window; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; @@ -43,33 +52,59 @@ import java.util.List; * */ public abstract class LauncherActivity extends ListActivity { + + Intent mIntent; + PackageManager mPackageManager; + /** + * An item in the list + */ + public static class ListItem { + public CharSequence label; + //public CharSequence description; + public Drawable icon; + public String packageName; + public String className; + + ListItem(PackageManager pm, ResolveInfo resolveInfo, IconResizer resizer) { + label = resolveInfo.loadLabel(pm); + if (label == null && resolveInfo.activityInfo != null) { + label = resolveInfo.activityInfo.name; + } + + /* + if (resolveInfo.activityInfo != null && + resolveInfo.activityInfo.applicationInfo != null) { + description = resolveInfo.activityInfo.applicationInfo.loadDescription(pm); + } + */ + + icon = resizer.createIconThumbnail(resolveInfo.loadIcon(pm)); + packageName = resolveInfo.activityInfo.applicationInfo.packageName; + className = resolveInfo.activityInfo.name; + } + + public ListItem() { + } + } + /** * Adapter which shows the set of activities that can be performed for a given intent. */ private class ActivityAdapter extends BaseAdapter implements Filterable { private final Object lock = new Object(); - private ArrayList mOriginalValues; + private ArrayList mOriginalValues; - protected final Context mContext; - protected final Intent mIntent; protected final LayoutInflater mInflater; - protected List mActivitiesList; + protected List mActivitiesList; private Filter mFilter; - - public ActivityAdapter(Context context, Intent intent) { - mContext = context; - mIntent = new Intent(intent); - mIntent.setComponent(null); - mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - PackageManager pm = context.getPackageManager(); - mActivitiesList = pm.queryIntentActivities(intent, 0); - if (mActivitiesList != null) { - Collections.sort(mActivitiesList, new ResolveInfo.DisplayNameComparator(pm)); - } + + public ActivityAdapter() { + mInflater = (LayoutInflater) LauncherActivity.this.getSystemService( + Context.LAYOUT_INFLATER_SERVICE); + mActivitiesList = makeListItems(); } public Intent intentForPosition(int position) { @@ -78,8 +113,8 @@ public abstract class LauncherActivity extends ListActivity { } Intent intent = new Intent(mIntent); - ActivityInfo ai = mActivitiesList.get(position).activityInfo; - intent.setClassName(ai.applicationInfo.packageName, ai.name); + ListItem item = mActivitiesList.get(position); + intent.setClassName(item.packageName, item.className); return intent; } @@ -99,7 +134,7 @@ public abstract class LauncherActivity extends ListActivity { View view; if (convertView == null) { view = mInflater.inflate( - com.android.internal.R.layout.simple_list_item_1, parent, false); + com.android.internal.R.layout.activity_list_item_2, parent, false); } else { view = convertView; } @@ -107,35 +142,22 @@ public abstract class LauncherActivity extends ListActivity { return view; } - private char getCandidateLetter(ResolveInfo info) { - PackageManager pm = mContext.getPackageManager(); - CharSequence label = info.loadLabel(pm); - - if (label == null) { - label = info.activityInfo.name; - } - - return Character.toLowerCase(label.charAt(0)); + private void bindView(View view, ListItem item) { + TextView text = (TextView) view; + text.setText(item.label); + text.setCompoundDrawablesWithIntrinsicBounds(item.icon, null, null, null); } - - private void bindView(View view, ResolveInfo info) { - TextView text = (TextView) view.findViewById(com.android.internal.R.id.text1); - - PackageManager pm = mContext.getPackageManager(); - CharSequence label = info.loadLabel(pm); - text.setText(label != null ? label : info.activityInfo.name); - } - + public Filter getFilter() { if (mFilter == null) { mFilter = new ArrayFilter(); } return mFilter; } - + /** - *

    An array filters constrains the content of the array adapter with a prefix. Each item that - * does not start with the supplied prefix is removed from the list.

    + * An array filters constrains the content of the array adapter with a prefix. Each + * item that does not start with the supplied prefix is removed from the list. */ private class ArrayFilter extends Filter { @Override @@ -144,39 +166,35 @@ public abstract class LauncherActivity extends ListActivity { if (mOriginalValues == null) { synchronized (lock) { - mOriginalValues = new ArrayList(mActivitiesList); + mOriginalValues = new ArrayList(mActivitiesList); } } if (prefix == null || prefix.length() == 0) { synchronized (lock) { - ArrayList list = new ArrayList(mOriginalValues); + ArrayList list = new ArrayList(mOriginalValues); results.values = list; results.count = list.size(); } } else { - final PackageManager pm = mContext.getPackageManager(); final String prefixString = prefix.toString().toLowerCase(); - ArrayList values = mOriginalValues; + ArrayList values = mOriginalValues; int count = values.size(); - ArrayList newValues = new ArrayList(count); + ArrayList newValues = new ArrayList(count); for (int i = 0; i < count; i++) { - ResolveInfo value = values.get(i); + ListItem item = values.get(i); - final CharSequence label = value.loadLabel(pm); - final CharSequence name = label != null ? label : value.activityInfo.name; - - String[] words = name.toString().toLowerCase().split(" "); + String[] words = item.label.toString().toLowerCase().split(" "); int wordCount = words.length; for (int k = 0; k < wordCount; k++) { final String word = words[k]; if (word.startsWith(prefixString)) { - newValues.add(value); + newValues.add(item); break; } } @@ -192,7 +210,7 @@ public abstract class LauncherActivity extends ListActivity { @Override protected void publishResults(CharSequence constraint, FilterResults results) { //noinspection unchecked - mActivitiesList = (List) results.values; + mActivitiesList = (List) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { @@ -201,19 +219,119 @@ public abstract class LauncherActivity extends ListActivity { } } } - - + + /** + * Utility class to resize icons to match default icon size. + */ + public class IconResizer { + // Code is borrowed from com.android.launcher.Utilities. + private int mIconWidth = -1; + private int mIconHeight = -1; + + private final Rect mOldBounds = new Rect(); + private Canvas mCanvas = new Canvas(); + + public IconResizer() { + mCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG, + Paint.FILTER_BITMAP_FLAG)); + + final Resources resources = LauncherActivity.this.getResources(); + mIconWidth = mIconHeight = (int) resources.getDimension( + android.R.dimen.app_icon_size); + } + + /** + * Returns a Drawable representing the thumbnail of the specified Drawable. + * The size of the thumbnail is defined by the dimension + * android.R.dimen.launcher_application_icon_size. + * + * This method is not thread-safe and should be invoked on the UI thread only. + * + * @param icon The icon to get a thumbnail of. + * + * @return A thumbnail for the specified icon or the icon itself if the + * thumbnail could not be created. + */ + public Drawable createIconThumbnail(Drawable icon) { + int width = mIconWidth; + int height = mIconHeight; + + final int iconWidth = icon.getIntrinsicWidth(); + final int iconHeight = icon.getIntrinsicHeight(); + + if (icon instanceof PaintDrawable) { + PaintDrawable painter = (PaintDrawable) icon; + painter.setIntrinsicWidth(width); + painter.setIntrinsicHeight(height); + } + + if (width > 0 && height > 0) { + if (width < iconWidth || height < iconHeight) { + final float ratio = (float) iconWidth / iconHeight; + + if (iconWidth > iconHeight) { + height = (int) (width / ratio); + } else if (iconHeight > iconWidth) { + width = (int) (height * ratio); + } + + final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ? + Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; + final Bitmap thumb = Bitmap.createBitmap(mIconWidth, mIconHeight, c); + final Canvas canvas = mCanvas; + canvas.setBitmap(thumb); + // Copy the old bounds to restore them later + // If we were to do oldBounds = icon.getBounds(), + // the call to setBounds() that follows would + // change the same instance and we would lose the + // old bounds + mOldBounds.set(icon.getBounds()); + final int x = (mIconWidth - width) / 2; + final int y = (mIconHeight - height) / 2; + icon.setBounds(x, y, x + width, y + height); + icon.draw(canvas); + icon.setBounds(mOldBounds); + icon = new BitmapDrawable(thumb); + } else if (iconWidth < width && iconHeight < height) { + final Bitmap.Config c = Bitmap.Config.ARGB_8888; + final Bitmap thumb = Bitmap.createBitmap(mIconWidth, mIconHeight, c); + final Canvas canvas = mCanvas; + canvas.setBitmap(thumb); + mOldBounds.set(icon.getBounds()); + final int x = (width - iconWidth) / 2; + final int y = (height - iconHeight) / 2; + icon.setBounds(x, y, x + iconWidth, y + iconHeight); + icon.draw(canvas); + icon.setBounds(mOldBounds); + icon = new BitmapDrawable(thumb); + } + } + + return icon; + } + } + @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + mPackageManager = getPackageManager(); + + requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); + setProgressBarIndeterminateVisibility(true); + setContentView(com.android.internal.R.layout.activity_list); - mAdapter = new ActivityAdapter(this, getTargetIntent()); + + mIntent = new Intent(getTargetIntent()); + mIntent.setComponent(null); + mAdapter = new ActivityAdapter(); setListAdapter(mAdapter); getListView().setTextFilterEnabled(true); + + setProgressBarIndeterminateVisibility(false); } - @Override protected void onListItemClick(ListView l, View v, int position, long id) { Intent intent = ((ActivityAdapter)mAdapter).intentForPosition(position); @@ -221,6 +339,42 @@ public abstract class LauncherActivity extends ListActivity { startActivity(intent); } - protected abstract Intent getTargetIntent(); - + /** + * Return the actual Intent for a specific position in our + * {@link android.widget.ListView}. + * @param position The item whose Intent to return + */ + protected Intent intentForPosition(int position) { + ActivityAdapter adapter = (ActivityAdapter) mAdapter; + return adapter.intentForPosition(position); + } + + /** + * Get the base intent to use when running + * {@link PackageManager#queryIntentActivities(Intent, int)}. + */ + protected Intent getTargetIntent() { + return new Intent(); + } + + /** + * Perform the query to determine which results to show and return a list of them. + */ + public List makeListItems() { + // Load all matching activities and sort correctly + List list = mPackageManager.queryIntentActivities(mIntent, + /* no flags */ 0); + Collections.sort(list, new ResolveInfo.DisplayNameComparator(mPackageManager)); + + IconResizer resizer = new IconResizer(); + + ArrayList result = new ArrayList(list.size()); + int listSize = list.size(); + for (int i = 0; i < listSize; i++) { + ResolveInfo resolveInfo = list.get(i); + result.add(new ListItem(mPackageManager, resolveInfo, resizer)); + } + + return result; + } } diff --git a/core/java/android/app/ListActivity.java b/core/java/android/app/ListActivity.java index 281893734b0d9e4af0a54d0adc2ebf5cfa241052..5523c185f21aeed363ee06e53e288dd42b74b0cf 100644 --- a/core/java/android/app/ListActivity.java +++ b/core/java/android/app/ListActivity.java @@ -53,22 +53,22 @@ import android.widget.ListView; *

    * *
    - * <?xml version="1.0" encoding="UTF-8"?>
    - * <LinearLayout
    + * <?xml version="1.0" encoding="utf-8"?>
    + * <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      *         android:orientation="vertical"
      *         android:layout_width="fill_parent" 
      *         android:layout_height="fill_parent"
    - *         android:paddingLeft="8"
    - *         android:paddingRight="8">
    + *         android:paddingLeft="8dp"
    + *         android:paddingRight="8dp">
      * 
    - *     <ListView id="android:list"
    + *     <ListView android:id="@id/android:list"
      *               android:layout_width="fill_parent" 
      *               android:layout_height="fill_parent"
      *               android:background="#00FF00"
      *               android:layout_weight="1"
      *               android:drawSelectorOnTop="false"/>
      * 
    - *     <TextView id="android:empty"
    + *     <TextView id="@id/android:empty"
      *               android:layout_width="fill_parent" 
      *               android:layout_height="fill_parent"
      *               android:background="#FF0000"
    @@ -99,19 +99,19 @@ import android.widget.ListView;
      * 
      * 
      * <?xml version="1.0" encoding="utf-8"?>
    - * <LinearLayout
    + * <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      *     android:layout_width="fill_parent"
      *     android:layout_height="wrap_content"
      *     android:orientation="vertical">
      * 
    - *     <TextView id="text1"
    - *         android:textSize="16"
    + *     <TextView android:id="@+id/text1"
    + *         android:textSize="16sp"
      *         android:textStyle="bold"
      *         android:layout_width="fill_parent"
      *         android:layout_height="wrap_content"/>
      * 
    - *     <TextView id="text2"
    - *         android:textSize="16"
    + *     <TextView android:id="@+id/text2"
    + *         android:textSize="16sp"
      *         android:layout_width="fill_parent"
      *         android:layout_height="wrap_content"/>
      * </LinearLayout>
    @@ -142,8 +142,8 @@ import android.widget.ListView;
      * public class MyListAdapter extends ListActivity {
      * 
      *     @Override
    - *     protected void onCreate(Bundle icicle){
    - *         super.onCreate(icicle);
    + *     protected void onCreate(Bundle savedInstanceState){
    + *         super.onCreate(savedInstanceState);
      * 
      *         // We'll define a custom screen layout here (the one shown above), but
      *         // typically, you could just use the standard ListActivity layout.
    diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
    index ea67cdbd474385a4c9b7d5ed0dfd09eabdac9378..51fddb1145cbbd50122aa7479b667419e235e0f9 100644
    --- a/core/java/android/app/Notification.java
    +++ b/core/java/android/app/Notification.java
    @@ -90,8 +90,9 @@ public class Notification implements Parcelable
          * The intent to execute when the expanded status entry is clicked.  If
          * this is an activity, it must include the
          * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
    -     * that you take care of task management as described in the
    -     * application model document.
    +     * that you take care of task management as described in the Activities and Tasks
    +     * section of the Application 
    +     * Fundamentals document.
          */
         public PendingIntent contentIntent;
     
    @@ -420,8 +421,8 @@ public class Notification implements Parcelable
          * @param contentIntent The intent to launch when the user clicks the expanded notification.
          * If this is an activity, it must include the
          * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
    -     * that you take care of task management as described in the
    -     * application model document.
    +     * that you take care of task management as described in 
    +     * Application Fundamentals: Activities and Tasks.
          */
         public void setLatestEventInfo(Context context,
                 CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
    diff --git a/core/java/android/app/NotificationManager.java b/core/java/android/app/NotificationManager.java
    index afb3827878edeb64903895c8279edcb9d0d1d43a..39edab70d141584cdb1638e67db0cf955e7a5209 100644
    --- a/core/java/android/app/NotificationManager.java
    +++ b/core/java/android/app/NotificationManager.java
    @@ -82,9 +82,7 @@ public class NotificationManager
          * @param id An identifier for this notification unique within your
          *        application.
          * @param notification A {@link Notification} object describing how to
    -     *        notify the user, other than the view you're providing.  If you
    -     *        pass null, there will be no persistent notification and no
    -     *        flashing, vibration, etc.
    +     *        notify the user, other than the view you're providing. Must not be null.
          */
         public void notify(int id, Notification notification)
         {
    diff --git a/core/java/android/app/PendingIntent.java b/core/java/android/app/PendingIntent.java
    index b59e9dc435499eaa465abe931764e93d4b051b53..1bed706763a1a0c11a1ca803fd1c754643a8a1af 100644
    --- a/core/java/android/app/PendingIntent.java
    +++ b/core/java/android/app/PendingIntent.java
    @@ -426,13 +426,9 @@ public final class PendingIntent implements Parcelable {
          */
         @Override
         public boolean equals(Object otherObj) {
    -        if (otherObj == null) {
    -            return false;
    -        }
    -        try {
    +        if (otherObj instanceof PendingIntent) {
                 return mTarget.asBinder().equals(((PendingIntent)otherObj)
                         .mTarget.asBinder());
    -        } catch (ClassCastException e) {
             }
             return false;
         }
    @@ -442,6 +438,13 @@ public final class PendingIntent implements Parcelable {
             return mTarget.asBinder().hashCode();
         }
     
    +    @Override
    +    public String toString() {
    +        return "PendingIntent{"
    +                + Integer.toHexString(System.identityHashCode(this))
    +                + " target " + (mTarget != null ? mTarget.asBinder() : null) + "}";
    +    }
    +    
         public int describeContents() {
             return 0;
         }
    diff --git a/core/java/android/app/SearchDialog.java b/core/java/android/app/SearchDialog.java
    index 2e2a1a17a52e8519db444f178b9279abbe556f0b..64288d2e0af3b0e1f23ef1dcccec4ebc1aed0db9 100644
    --- a/core/java/android/app/SearchDialog.java
    +++ b/core/java/android/app/SearchDialog.java
    @@ -16,11 +16,14 @@
     
     package android.app;
     
    +import android.content.ActivityNotFoundException;
     import android.content.BroadcastReceiver;
     import android.content.ComponentName;
     import android.content.Context;
     import android.content.Intent;
     import android.content.IntentFilter;
    +import android.content.pm.PackageManager;
    +import android.content.pm.ResolveInfo;
     import android.content.res.Configuration;
     import android.content.res.Resources;
     import android.content.res.Resources.NotFoundException;
    @@ -29,11 +32,11 @@ import android.graphics.drawable.Drawable;
     import android.net.Uri;
     import android.os.Bundle;
     import android.os.Handler;
    -import android.os.Message;
     import android.os.RemoteException;
     import android.os.ServiceManager;
     import android.os.SystemClock;
     import android.server.search.SearchableInfo;
    +import android.speech.RecognizerIntent;
     import android.text.Editable;
     import android.text.InputType;
     import android.text.TextUtils;
    @@ -50,6 +53,7 @@ import android.widget.AdapterView;
     import android.widget.AutoCompleteTextView;
     import android.widget.Button;
     import android.widget.CursorAdapter;
    +import android.widget.ImageButton;
     import android.widget.ImageView;
     import android.widget.ListView;
     import android.widget.SimpleCursorAdapter;
    @@ -94,6 +98,7 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
         private TextView mBadgeLabel;
         private AutoCompleteTextView mSearchTextField;
         private Button mGoButton;
    +    private ImageButton mVoiceButton;
     
         // interaction with searchable application
         private ComponentName mLaunchComponent;
    @@ -115,10 +120,13 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
         private Uri mSuggestionData = null;
         private String mSuggestionQuery = null;
         
    +    // For voice searching
    +    private Intent mVoiceWebSearchIntent;
    +    private Intent mVoiceAppSearchIntent;
    +
         // support for AutoCompleteTextView suggestions display
         private SuggestionsAdapter mSuggestionsAdapter;
     
    -
         /**
          * Constructor - fires it up and makes it look like the search UI.
          * 
    @@ -153,12 +161,15 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
             mSearchTextField = (AutoCompleteTextView) 
                     findViewById(com.android.internal.R.id.search_src_text);
             mGoButton = (Button) findViewById(com.android.internal.R.id.search_go_btn);
    +        mVoiceButton = (ImageButton) findViewById(com.android.internal.R.id.search_voice_btn);
             
             // attach listeners
             mSearchTextField.addTextChangedListener(mTextWatcher);
             mSearchTextField.setOnKeyListener(mTextKeyListener);
             mGoButton.setOnClickListener(mGoButtonClickListener);
             mGoButton.setOnKeyListener(mButtonsKeyListener);
    +        mVoiceButton.setOnClickListener(mVoiceButtonClickListener);
    +        mVoiceButton.setOnKeyListener(mButtonsKeyListener);
     
             // pre-hide all the extraneous elements
             mBadgeLabel.setVisibility(View.GONE);
    @@ -169,13 +180,19 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
             setCanceledOnTouchOutside(true);
             
             // Set up broadcast filters
    -        mCloseDialogsFilter = new
    -        IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    +        mCloseDialogsFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
             mPackageFilter = new IntentFilter();
             mPackageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
             mPackageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
             mPackageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
             mPackageFilter.addDataScheme("package");
    +        
    +        // Save voice intent for later queries/launching
    +        mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
    +        mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
    +                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
    +        
    +        mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
         }
     
         /**
    @@ -236,7 +253,8 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
                 mSearchTextField.setAdapter(mSuggestionsAdapter);
                 mSearchTextField.setText(initialQuery);
             } else {
    -            mSuggestionsAdapter = new SuggestionsAdapter(getContext(), mSearchable);
    +            mSuggestionsAdapter = new SuggestionsAdapter(getContext(), mSearchable, 
    +                    mSearchTextField);
                 mSearchTextField.setAdapter(mSuggestionsAdapter);
     
                 // finally, load the user's initial text (which may trigger suggestions)
    @@ -261,16 +279,15 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
         }
     
         /**
    -     * Dismiss the search dialog.
    +     * The search dialog is being dismissed, so handle all of the local shutdown operations.
          * 
    -     * This function is designed to be idempotent so it can be safely called at any time
    +     * This function is designed to be idempotent so that dismiss() can be safely called at any time
          * (even if already closed) and more likely to really dump any memory.  No leaks!
          */
         @Override
    -    public void dismiss() {
    -        if (isShowing()) {
    -            super.dismiss();
    -        }
    +    public void onStop() {
    +        super.onStop();
    +        
             setOnCancelListener(null);
             setOnDismissListener(null);
             
    @@ -281,6 +298,11 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
                 // This is OK - it just means we didn't have any registered
             }
             
    +        // close any leftover cursor
    +        if (mSuggestionsAdapter != null) {
    +            mSuggestionsAdapter.changeCursor(null);
    +        }
    +        
             // dump extra memory we're hanging on to
             mLaunchComponent = null;
             mAppSearchData = null;
    @@ -408,6 +430,7 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
                 updateSearchButton();
                 updateSearchBadge();
                 updateQueryHint();
    +            updateVoiceButton();
                 
                 // In order to properly configure the input method (if one is being used), we
                 // need to let it know if we'll be providing suggestions.  Although it would be
    @@ -426,6 +449,7 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
                     }
                 }
                 mSearchTextField.setInputType(inputType);
    +            mSearchTextField.setImeOptions(mSearchable.getImeOptions());
             }
         }
     
    @@ -499,6 +523,30 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
             }
         }
     
    +    /**
    +     * Update the visibility of the voice button.  There are actually two voice search modes, 
    +     * either of which will activate the button.
    +     */
    +    private void updateVoiceButton() {
    +        int visibility = View.GONE;
    +        if (mSearchable.getVoiceSearchEnabled()) {
    +            Intent testIntent = null;
    +            if (mSearchable.getVoiceSearchLaunchWebSearch()) {
    +                testIntent = mVoiceWebSearchIntent;
    +            } else if (mSearchable.getVoiceSearchLaunchRecognizer()) {
    +                testIntent = mVoiceAppSearchIntent;
    +            }      
    +            if (testIntent != null) {
    +                ResolveInfo ri = getContext().getPackageManager().
    +                        resolveActivity(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
    +                if (ri != null) {
    +                    visibility = View.VISIBLE;
    +                }
    +            }
    +        }
    +        mVoiceButton.setVisibility(visibility);
    +    }
    +    
         /**
          * Listeners of various types
          */
    @@ -641,12 +689,98 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
             }
         };
         
    +    /**
    +     * React to a click in the voice search button.
    +     */
    +    View.OnClickListener mVoiceButtonClickListener = new View.OnClickListener() {
    +        public void onClick(View v) {
    +            try {
    +                if (mSearchable.getVoiceSearchLaunchWebSearch()) {
    +                    getContext().startActivity(mVoiceWebSearchIntent);
    +                    dismiss();
    +                } else if (mSearchable.getVoiceSearchLaunchRecognizer()) {
    +                    Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent);
    +                    getContext().startActivity(appSearchIntent);
    +                    dismiss();
    +                }
    +            } catch (ActivityNotFoundException e) {
    +                // Should not happen, since we check the availability of
    +                // voice search before showing the button. But just in case...
    +                Log.w(LOG_TAG, "Could not find voice search activity");
    +            }
    +         }
    +    };
    +    
    +    /**
    +     * Create and return an Intent that can launch the voice search activity, perform a specific
    +     * voice transcription, and forward the results to the searchable activity.
    +     * 
    +     * @param baseIntent The voice app search intent to start from
    +     * @return A completely-configured intent ready to send to the voice search activity
    +     */
    +    private Intent createVoiceAppSearchIntent(Intent baseIntent) {
    +        // create the necessary intent to set up a search-and-forward operation
    +        // in the voice search system.   We have to keep the bundle separate,
    +        // because it becomes immutable once it enters the PendingIntent
    +        Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
    +        queryIntent.setComponent(mSearchable.mSearchActivity);
    +        PendingIntent pending = PendingIntent.getActivity(
    +                getContext(), 0, queryIntent, PendingIntent.FLAG_ONE_SHOT);
    +        
    +        // Now set up the bundle that will be inserted into the pending intent
    +        // when it's time to do the search.  We always build it here (even if empty)
    +        // because the voice search activity will always need to insert "QUERY" into
    +        // it anyway.
    +        Bundle queryExtras = new Bundle();
    +        if (mAppSearchData != null) {
    +            queryExtras.putBundle(SearchManager.APP_DATA, mAppSearchData);
    +        }
    +        
    +        // Now build the intent to launch the voice search.  Add all necessary
    +        // extras to launch the voice recognizer, and then all the necessary extras
    +        // to forward the results to the searchable activity
    +        Intent voiceIntent = new Intent(baseIntent);
    +        
    +        // Add all of the configuration options supplied by the searchable's metadata
    +        String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
    +        String prompt = null;
    +        String language = null;
    +        int maxResults = 1;
    +        Resources resources = mActivityContext.getResources();
    +        if (mSearchable.getVoiceLanguageModeId() != 0) {
    +            languageModel = resources.getString(mSearchable.getVoiceLanguageModeId());
    +        }
    +        if (mSearchable.getVoicePromptTextId() != 0) {
    +            prompt = resources.getString(mSearchable.getVoicePromptTextId());
    +        }
    +        if (mSearchable.getVoiceLanguageId() != 0) {
    +            language = resources.getString(mSearchable.getVoiceLanguageId());
    +        }
    +        if (mSearchable.getVoiceMaxResults() != 0) {
    +            maxResults = mSearchable.getVoiceMaxResults();
    +        }
    +        voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
    +        voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
    +        voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
    +        voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
    +        
    +        // Add the values that configure forwarding the results
    +        voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
    +        voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
    +        
    +        return voiceIntent;
    +    }
    +
         /**
          * React to the user typing "enter" or other hardwired keys while typing in the search box.
          * This handles these special keys while the edit box has focus.
          */
         View.OnKeyListener mTextKeyListener = new View.OnKeyListener() {
             public boolean onKey(View v, int keyCode, KeyEvent event) {
    +            if (keyCode == KeyEvent.KEYCODE_BACK) {
    +                cancel();
    +                return true;
    +            }
                 // also guard against possible race conditions (late arrival after dismiss)
                 if (mSearchable != null && 
                         TextUtils.getTrimmedLength(mSearchTextField.getText()) > 0) {
    @@ -661,7 +795,6 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
                     // otherwise, dispatch an "edit view" key
                     switch (keyCode) {
                     case KeyEvent.KEYCODE_ENTER:
    -                case KeyEvent.KEYCODE_DPAD_CENTER:
                         if (event.getAction() == KeyEvent.ACTION_UP) {
                             v.cancelLongPress();
                             launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null);                    
    @@ -700,9 +833,6 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
             // also guard against possible race conditions (late arrival after dismiss)
             if (mSearchable != null) {
                 handled = doSuggestionsKey(v, keyCode, event);
    -            if (!handled) {
    -                handled = refocusingKeyListener(v, keyCode, event);
    -            }
             }
             return handled;
         }
    @@ -792,24 +922,6 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
             }
         };
     
    -    /**
    -     * UI-thread handling of dialog dismiss.  Called by mBroadcastReceiver.onReceive().
    -     *
    -     * TODO: This is a really heavyweight solution for something that should be so simple.
    -     * For example, we already have a handler, in our superclass, why aren't we sharing that?
    -     * I think we need to investigate simplifying this entire methodology, or perhaps boosting
    -     * it up into the Dialog class.
    -     */
    -    private static final int MESSAGE_DISMISS = 0;
    -    private Handler mDismissHandler = new Handler() {
    -        @Override
    -        public void handleMessage(Message msg) {
    -            if (msg.what == MESSAGE_DISMISS) {
    -                dismiss();
    -            }
    -        }
    -    };
    -    
         /**
          * Various ways to launch searches
          */
    @@ -907,6 +1019,11 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
          * @param jamQuery True means to set the query, false means to reset it to the user's choice
          */
         private void jamSuggestionQuery(boolean jamQuery, AdapterView parent, int position) {
    +        // quick check against race conditions
    +        if (mSearchable == null) {
    +            return;
    +        }
    +        
             mSuggestionsAdapter.setNonUserQuery(true);       // disables any suggestions processing
             if (jamQuery) {
                 CursorAdapter ca = getSuggestionsAdapter(parent);
    @@ -1180,10 +1297,13 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
             // These private variables are shared by the filter thread and must be protected
             private WeakReference mRecentCursor = new WeakReference(null);
             private boolean mNonUserQuery = false;
    +        private AutoCompleteTextView mParentView;
     
    -        public SuggestionsAdapter(Context context, SearchableInfo searchable) {
    +        public SuggestionsAdapter(Context context, SearchableInfo searchable,
    +                AutoCompleteTextView actv) {
                 super(context, -1, null, null, null);
                 mSearchable = searchable;
    +            mParentView = actv;
                 
                 // set up provider resources (gives us icons, etc.)
                 Context activityContext = mSearchable.getActivityContext(mContext);
    @@ -1296,9 +1416,12 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS
                             to = ONE_LINE_TO;
                         }
                     }
    +                // Force the underlying ListView to discard and reload all layouts
    +                // (Note, this should be optimized for cases where layout/cursor remain same)
    +                mParentView.resetListAndClearViews();
                     // Now actually set up the cursor, columns, and the list view
                     changeCursorAndColumns(c, from, to);
    -                setViewResource(layout);              
    +                setViewResource(layout);          
                 } else {
                     // Provide some help for developers instead of just silently discarding
                     Log.w(LOG_TAG, "Suggestions cursor discarded due to missing required columns.");
    diff --git a/core/java/android/app/SearchManager.java b/core/java/android/app/SearchManager.java
    index 0a37e81320229aff40bd6238599ac109827fdcc7..c1d66f4e7d7bcc7f0c269c35ae96a7b7b2b677a5 100644
    --- a/core/java/android/app/SearchManager.java
    +++ b/core/java/android/app/SearchManager.java
    @@ -168,7 +168,8 @@ import android.view.KeyEvent;
      * 

    Managing focus and knowing if Search is active. The search UI is not a separate * activity, and when the UI is invoked or dismissed, your activity will not typically be paused, * resumed, or otherwise notified by the methods defined in - * Activity Lifecycle. The search UI is + * Application Fundamentals: + * Activity Lifecycle. The search UI is * handled in the same way as other system UI elements which may appear from time to time, such as * notifications, screen locks, or other system alerts: *

    When the search UI appears, your activity will lose input focus. @@ -212,11 +213,11 @@ import android.view.KeyEvent; * {@link #QUERY getStringExtra(SearchManager.QUERY)}. *

  1. To identify and support your searchable activity, you'll need to * provide an XML file providing searchability configuration parameters, a reference to that - * in your searchable activity's manifest + * in your searchable activity's manifest * entry, and an intent-filter declaring that you can * receive ACTION_SEARCH intents. This is described in more detail in the * Searchability Metadata section.
  2. - *
  3. Your manifest also needs a metadata entry + *
  4. Your manifest also needs a metadata entry * providing a global reference to the searchable activity. This is the "glue" directing the search * UI, when invoked from any of your other activities, to use your application as the * default search context. This is also described in more detail in the @@ -359,7 +360,7 @@ import android.view.KeyEvent; *
  5. Implement a Content Provider that provides suggestions. If you already have one, and it * has access to your suggestions data. If not, you'll have to create one. * You'll also provide information about your Content Provider in your - * package's manifest.
  6. + * package's manifest. *
  7. Update your searchable activity's XML configuration file. There are two categories of * information used for suggestions: *
    • The first is (required) data that the search manager will @@ -634,7 +635,7 @@ import android.view.KeyEvent; * *

      Metadata for searchable activity. As with your search implementations described * above, you must first identify which of your activities is searchable. In the - * manifest entry for this activity, you must + * manifest entry for this activity, you must * provide two elements: *

      • An intent-filter specifying that you can receive and process the * {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} {@link android.content.Intent Intent}. @@ -643,7 +644,7 @@ import android.view.KeyEvent; * remaining configuration information for how your application implements search.
      * *

      Here is a snippet showing the necessary elements in the - * manifest entry for your searchable activity. + * manifest entry for your searchable activity. *

        *        <!-- Search Activity - searchable -->
        *        <activity android:name="MySearchActivity" 
      @@ -746,6 +747,14 @@ import android.view.KeyEvent;
        *             inputType attribute.
        *         No
        *     
      + *     android:imeOptions
      + *         If provided, supplies additional options for the input method.
      + *             For most searches, in which free form text is expected, this attribute
      + *             need not be provided, and will default to "actionSearch".
      + *             Suitable values for this attribute are described in the
      + *             imeOptions attribute.
      + *         No
      + *     
        *     
        *     
        * 
      @@ -765,9 +774,8 @@ import android.view.KeyEvent;
        * 
    • .../res/values/strings.xml
    * *

    For more complete documentation on this capability, see - * Resources and - * Internationalization: Supporting Alternate Resources for Alternate Languages and Configurations - * . + * Resources and + * Internationalization: Alternate Resources. * *

    Metadata for non-searchable activities. Activities which are part of a searchable * application, but don't implement search itself, require a bit of "glue" in order to cause @@ -775,7 +783,7 @@ import android.view.KeyEvent; * provided, then searches from these activities will use the system default search context. * *

    The simplest way to specify this is to add a search reference element to the - * application entry in the manifest file. + * application entry in the manifest file. * The value of this reference can be either of: *

    • The name of your searchable activity. * It is typically prefixed by '.' to indicate that it's in the same package.
    • @@ -803,7 +811,7 @@ import android.view.KeyEvent; * to generate search suggestions, you'll need to publish it to the system, and you'll need to * provide a bit of additional XML metadata in order to configure communications with it. * - *

      First, in your manifest, you'll add the + *

      First, in your manifest, you'll add the * following lines. *

        *        <!-- Content provider for search suggestions -->
      @@ -832,7 +840,7 @@ import android.view.KeyEvent;
        *     
        *     android:searchSuggestAuthority
        *         This value must match the authority string provided in the provider section 
      - *             of your manifest.
      + *             of your manifest.
        *         Yes
        *     
        *     
      diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
      index 6c08e750c7d7af28409ef4d4d38b208eed103fb1..a6a436f4fd09747787e26cd0f60649bc72fedfb1 100644
      --- a/core/java/android/app/Service.java
      +++ b/core/java/android/app/Service.java
      @@ -42,12 +42,12 @@ import java.io.PrintWriter;
        * thread of their hosting process.  This means that, if your service is going
        * to do any CPU intensive (such as MP3 playback) or blocking (such as
        * networking) operations, it should spawn its own thread in which to do that
      - * work.  More information on this can be found in the
      - * Threading section of the
      - * Application Model overview.

      + * work. More information on this can be found in + * Application Fundamentals: + * Processes and Threads.

      * *

      The Service class is an important part of an - * application's overall lifecycle.

      + * application's overall lifecycle.

      * *

      Topics covered here: *

        @@ -79,7 +79,7 @@ import java.io.PrintWriter; * to the service. The service will remain running as long as the connection * is established (whether or not the client retains a reference on the * service's IBinder). Usually the IBinder returned is for a complex - * interface that has been written + * interface that has been written * in aidl. * *

        A service can be both started and have connections bound to it. In such @@ -106,7 +106,7 @@ import java.io.PrintWriter; * {@link #checkCallingPermission} * method before executing the implementation of that call. * - *

        See the Security Model + *

        See the Security and Permissions * document for more information on permissions and security in general. * * @@ -201,14 +201,14 @@ public abstract class Service extends ContextWrapper implements ComponentCallbac * Return the communication channel to the service. May return null if * clients can not bind to the service. The returned * {@link android.os.IBinder} is usually for a complex interface - * that has been described using + * that has been described using * aidl. * *

        Note that unlike other application components, calls on to the * IBinder interface returned here may not happen on the main thread * of the process. More information about this can be found - * in the Threading section - * of the Application Model overview.

        + * in Application Fundamentals: + * Processes and Threads.

        * * @param intent The Intent that was used to bind to this service, * as given to {@link android.content.Context#bindService @@ -327,11 +327,15 @@ public abstract class Service extends ContextWrapper implements ComponentCallbac } /** - * Print the Service's state into the given stream. + * Print the Service's state into the given stream. This gets invoked if + * you run "adb shell dumpsys activity service ". + * This is distinct from "dumpsys ", which only works for + * named system services and which invokes the {@link IBinder#dump} method + * on the {@link IBinder} interface registered with ServiceManager. * * @param fd The raw file descriptor that the dump is being sent to. * @param writer The PrintWriter to which you should dump your state. This will be - * closed for you after you return. + * closed for you after you return. * @param args additional arguments to the dump request. */ protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { diff --git a/core/java/android/appwidget/AppWidgetHost.java b/core/java/android/appwidget/AppWidgetHost.java new file mode 100644 index 0000000000000000000000000000000000000000..10c2b02d4c3529004a6b147564cfb0f822f185b3 --- /dev/null +++ b/core/java/android/appwidget/AppWidgetHost.java @@ -0,0 +1,248 @@ +/* + * + * 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. + */ + +package android.appwidget; + +import android.content.Context; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import android.os.Message; +import android.os.RemoteException; +import android.os.ServiceManager; +import android.widget.RemoteViews; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import com.android.internal.appwidget.IAppWidgetHost; +import com.android.internal.appwidget.IAppWidgetService; + +/** + * AppWidgetHost provides the interaction with the AppWidget service for apps, + * like the home screen, that want to embed AppWidgets in their UI. + */ +public class AppWidgetHost { + + static final int HANDLE_UPDATE = 1; + static final int HANDLE_PROVIDER_CHANGED = 2; + + static Object sServiceLock = new Object(); + static IAppWidgetService sService; + + Context mContext; + String mPackageName; + + class Callbacks extends IAppWidgetHost.Stub { + public void updateAppWidget(int appWidgetId, RemoteViews views) { + Message msg = mHandler.obtainMessage(HANDLE_UPDATE); + msg.arg1 = appWidgetId; + msg.obj = views; + msg.sendToTarget(); + } + + public void providerChanged(int appWidgetId, AppWidgetProviderInfo info) { + Message msg = mHandler.obtainMessage(HANDLE_PROVIDER_CHANGED); + msg.arg1 = appWidgetId; + msg.obj = info; + msg.sendToTarget(); + } + } + + class UpdateHandler extends Handler { + public UpdateHandler(Looper looper) { + super(looper); + } + + public void handleMessage(Message msg) { + switch (msg.what) { + case HANDLE_UPDATE: { + updateAppWidgetView(msg.arg1, (RemoteViews)msg.obj); + break; + } + case HANDLE_PROVIDER_CHANGED: { + onProviderChanged(msg.arg1, (AppWidgetProviderInfo)msg.obj); + break; + } + } + } + } + + Handler mHandler; + + int mHostId; + Callbacks mCallbacks = new Callbacks(); + HashMap mViews = new HashMap(); + + public AppWidgetHost(Context context, int hostId) { + mContext = context; + mHostId = hostId; + mHandler = new UpdateHandler(context.getMainLooper()); + synchronized (sServiceLock) { + if (sService == null) { + IBinder b = ServiceManager.getService(Context.APPWIDGET_SERVICE); + sService = IAppWidgetService.Stub.asInterface(b); + } + } + } + + /** + * Start receiving onAppWidgetChanged calls for your AppWidgets. Call this when your activity + * becomes visible, i.e. from onStart() in your Activity. + */ + public void startListening() { + int[] updatedIds = null; + ArrayList updatedViews = new ArrayList(); + + try { + if (mPackageName == null) { + mPackageName = mContext.getPackageName(); + } + updatedIds = sService.startListening(mCallbacks, mPackageName, mHostId, updatedViews); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + + final int N = updatedIds.length; + for (int i=0; i + *
      1. Call this when initializing your database, as it might be because of a data wipe.
      2. + *
      3. Call this to have the AppWidget manager release all resources associated with your + * host. Any future calls about this host will cause the records to be re-allocated.
      4. + *
    + */ + public void deleteHost() { + try { + sService.deleteHost(mHostId); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + + /** + * Remove all records about all hosts for your package. + *
      + *
    • Call this when initializing your database, as it might be because of a data wipe.
    • + *
    • Call this to have the AppWidget manager release all resources associated with your + * host. Any future calls about this host will cause the records to be re-allocated.
    • + *
    + */ + public static void deleteAllHosts() { + try { + sService.deleteAllHosts(); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + + public final AppWidgetHostView createView(Context context, int appWidgetId, + AppWidgetProviderInfo appWidget) { + AppWidgetHostView view = onCreateView(context, appWidgetId, appWidget); + view.setAppWidget(appWidgetId, appWidget); + synchronized (mViews) { + mViews.put(appWidgetId, view); + } + RemoteViews views = null; + try { + views = sService.getAppWidgetViews(appWidgetId); + } catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + view.updateAppWidget(views); + return view; + } + + /** + * Called to create the AppWidgetHostView. Override to return a custom subclass if you + * need it. {@more} + */ + protected AppWidgetHostView onCreateView(Context context, int appWidgetId, + AppWidgetProviderInfo appWidget) { + return new AppWidgetHostView(context); + } + + /** + * Called when the AppWidget provider for a AppWidget has been upgraded to a new apk. + */ + protected void onProviderChanged(int appWidgetId, AppWidgetProviderInfo appWidget) { + } + + void updateAppWidgetView(int appWidgetId, RemoteViews views) { + AppWidgetHostView v; + synchronized (mViews) { + v = mViews.get(appWidgetId); + } + if (v != null) { + v.updateAppWidget(views); + } + } +} + + diff --git a/core/java/android/appwidget/AppWidgetHostView.java b/core/java/android/appwidget/AppWidgetHostView.java new file mode 100644 index 0000000000000000000000000000000000000000..be0f96e8ab6a6d6cef4dcdf4ba305c9604589fa5 --- /dev/null +++ b/core/java/android/appwidget/AppWidgetHostView.java @@ -0,0 +1,312 @@ +/* + * 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. + */ + +package android.appwidget; + +import android.content.Context; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.os.Handler; +import android.os.Message; +import android.os.SystemClock; +import android.util.Config; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.animation.Animation; +import android.widget.FrameLayout; +import android.widget.RemoteViews; +import android.widget.TextView; + +/** + * Provides the glue to show AppWidget views. This class offers automatic animation + * between updates, and will try recycling old views for each incoming + * {@link RemoteViews}. + */ +public class AppWidgetHostView extends FrameLayout { + static final String TAG = "AppWidgetHostView"; + static final boolean LOGD = false; + static final boolean CROSSFADE = false; + + static final int VIEW_MODE_NOINIT = 0; + static final int VIEW_MODE_CONTENT = 1; + static final int VIEW_MODE_ERROR = 2; + static final int VIEW_MODE_DEFAULT = 3; + + static final int FADE_DURATION = 1000; + + // When we're inflating the initialLayout for a AppWidget, we only allow + // views that are allowed in RemoteViews. + static final LayoutInflater.Filter sInflaterFilter = new LayoutInflater.Filter() { + public boolean onLoadClass(Class clazz) { + return clazz.isAnnotationPresent(RemoteViews.RemoteView.class); + } + }; + + Context mContext; + + int mAppWidgetId; + AppWidgetProviderInfo mInfo; + View mView; + int mViewMode = VIEW_MODE_NOINIT; + int mLayoutId = -1; + long mFadeStartTime = -1; + Bitmap mOld; + Paint mOldPaint = new Paint(); + + /** + * Create a host view. Uses default fade animations. + */ + public AppWidgetHostView(Context context) { + this(context, android.R.anim.fade_in, android.R.anim.fade_out); + } + + /** + * Create a host view. Uses specified animations when pushing + * {@link #updateAppWidget(RemoteViews)}. + * + * @param animationIn Resource ID of in animation to use + * @param animationOut Resource ID of out animation to use + */ + public AppWidgetHostView(Context context, int animationIn, int animationOut) { + super(context); + mContext = context; + } + + /** + * Set the AppWidget that will be displayed by this view. + */ + public void setAppWidget(int appWidgetId, AppWidgetProviderInfo info) { + mAppWidgetId = appWidgetId; + mInfo = info; + } + + public int getAppWidgetId() { + return mAppWidgetId; + } + + public AppWidgetProviderInfo getAppWidgetInfo() { + return mInfo; + } + + /** + * Process a set of {@link RemoteViews} coming in as an update from the + * AppWidget provider. Will animate into these new views as needed. + */ + public void updateAppWidget(RemoteViews remoteViews) { + if (LOGD) Log.d(TAG, "updateAppWidget called mOld=" + mOld); + + boolean recycled = false; + View content = null; + Exception exception = null; + + // Capture the old view into a bitmap so we can do the crossfade. + if (CROSSFADE) { + if (mFadeStartTime < 0) { + if (mView != null) { + final int width = mView.getWidth(); + final int height = mView.getHeight(); + try { + mOld = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + } catch (OutOfMemoryError e) { + // we just won't do the fade + mOld = null; + } + if (mOld != null) { + //mView.drawIntoBitmap(mOld); + } + } + } + } + + if (remoteViews == null) { + if (mViewMode == VIEW_MODE_DEFAULT) { + // We've already done this -- nothing to do. + return; + } + content = getDefaultView(); + mLayoutId = -1; + mViewMode = VIEW_MODE_DEFAULT; + } else { + int layoutId = remoteViews.getLayoutId(); + + // If our stale view has been prepared to match active, and the new + // layout matches, try recycling it + if (content == null && layoutId == mLayoutId) { + try { + remoteViews.reapply(mContext, mView); + content = mView; + recycled = true; + if (LOGD) Log.d(TAG, "was able to recycled existing layout"); + } catch (RuntimeException e) { + exception = e; + } + } + + // Try normal RemoteView inflation + if (content == null) { + try { + content = remoteViews.apply(mContext, this); + if (LOGD) Log.d(TAG, "had to inflate new layout"); + } catch (RuntimeException e) { + exception = e; + } + } + + mLayoutId = layoutId; + mViewMode = VIEW_MODE_CONTENT; + } + + if (content == null) { + if (mViewMode == VIEW_MODE_ERROR) { + // We've already done this -- nothing to do. + return ; + } + Log.w(TAG, "updateAppWidget couldn't find any view, using error view", exception); + content = getErrorView(); + mViewMode = VIEW_MODE_ERROR; + } + + if (!recycled) { + prepareView(content); + addView(content); + } + + if (mView != content) { + removeView(mView); + mView = content; + } + + if (CROSSFADE) { + if (mFadeStartTime < 0) { + // if there is already an animation in progress, don't do anything -- + // the new view will pop in on top of the old one during the cross fade, + // and that looks okay. + mFadeStartTime = SystemClock.uptimeMillis(); + invalidate(); + } + } + } + + protected boolean drawChild(Canvas canvas, View child, long drawingTime) { + if (CROSSFADE) { + int alpha; + int l = child.getLeft(); + int t = child.getTop(); + if (mFadeStartTime > 0) { + alpha = (int)(((drawingTime-mFadeStartTime)*255)/FADE_DURATION); + if (alpha > 255) { + alpha = 255; + } + Log.d(TAG, "drawChild alpha=" + alpha + " l=" + l + " t=" + t + + " w=" + child.getWidth()); + if (alpha != 255 && mOld != null) { + mOldPaint.setAlpha(255-alpha); + //canvas.drawBitmap(mOld, l, t, mOldPaint); + } + } else { + alpha = 255; + } + int restoreTo = canvas.saveLayerAlpha(l, t, child.getWidth(), child.getHeight(), alpha, + Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); + boolean rv = super.drawChild(canvas, child, drawingTime); + canvas.restoreToCount(restoreTo); + if (alpha < 255) { + invalidate(); + } else { + mFadeStartTime = -1; + if (mOld != null) { + mOld.recycle(); + mOld = null; + } + } + return rv; + } else { + return super.drawChild(canvas, child, drawingTime); + } + } + + /** + * Prepare the given view to be shown. This might include adjusting + * {@link FrameLayout.LayoutParams} before inserting. + */ + protected void prepareView(View view) { + // Take requested dimensions from parent, but apply default gravity. + ViewGroup.LayoutParams requested = view.getLayoutParams(); + if (requested == null) { + requested = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, + LayoutParams.FILL_PARENT); + } + + FrameLayout.LayoutParams params = + new FrameLayout.LayoutParams(requested.width, requested.height); + params.gravity = Gravity.CENTER; + view.setLayoutParams(params); + } + + /** + * Inflate and return the default layout requested by AppWidget provider. + */ + protected View getDefaultView() { + View defaultView = null; + Exception exception = null; + + try { + if (mInfo != null) { + Context theirContext = mContext.createPackageContext( + mInfo.provider.getPackageName(), 0 /* no flags */); + LayoutInflater inflater = (LayoutInflater) + theirContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + inflater = inflater.cloneInContext(theirContext); + inflater.setFilter(sInflaterFilter); + defaultView = inflater.inflate(mInfo.initialLayout, this, false); + } else { + Log.w(TAG, "can't inflate defaultView because mInfo is missing"); + } + } catch (PackageManager.NameNotFoundException e) { + exception = e; + } catch (RuntimeException e) { + exception = e; + } + + if (exception != null && LOGD) { + Log.w(TAG, "Error inflating AppWidget " + mInfo, exception); + } + + if (defaultView == null) { + if (LOGD) Log.d(TAG, "getDefaultView couldn't find any view, so inflating error"); + defaultView = getErrorView(); + } + + return defaultView; + } + + /** + * Inflate and return a view that represents an error state. + */ + protected View getErrorView() { + TextView tv = new TextView(mContext); + tv.setText(com.android.internal.R.string.gadget_host_error_inflating); + // TODO: get this color from somewhere. + tv.setBackgroundColor(Color.argb(127, 0, 0, 0)); + return tv; + } +} diff --git a/core/java/android/appwidget/AppWidgetManager.java b/core/java/android/appwidget/AppWidgetManager.java new file mode 100644 index 0000000000000000000000000000000000000000..3b10ed282d1c7a59647cad5b7c706d2636ae7a44 --- /dev/null +++ b/core/java/android/appwidget/AppWidgetManager.java @@ -0,0 +1,320 @@ +/* + * 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. + */ + +package android.appwidget; + +import android.content.ComponentName; +import android.content.Context; +import android.os.IBinder; +import android.os.RemoteException; +import android.os.ServiceManager; +import android.util.Log; +import android.widget.RemoteViews; + +import com.android.internal.appwidget.IAppWidgetService; + +import java.lang.ref.WeakReference; +import java.util.List; +import java.util.WeakHashMap; + +/** + * Updates AppWidget state; gets information about installed AppWidget providers and other + * AppWidget related state. + */ +public class AppWidgetManager { + static final String TAG = "AppWidgetManager"; + + /** + * Send this from your {@link AppWidgetHost} activity when you want to pick an AppWidget to display. + * The AppWidget picker activity will be launched. + *

    + * You must supply the following extras: + * + * + * + * + * + *
    {@link #EXTRA_APPWIDGET_ID}A newly allocated appWidgetId, which will be bound to the AppWidget provider + * once the user has selected one.
    + * + *

    + * The system will respond with an onActivityResult call with the following extras in + * the intent: + * + * + * + * + * + *
    {@link #EXTRA_APPWIDGET_ID}The appWidgetId that you supplied in the original intent.
    + *

    + * When you receive the result from the AppWidget pick activity, if the resultCode is + * {@link android.app.Activity#RESULT_OK}, an AppWidget has been selected. You should then + * check the AppWidgetProviderInfo for the returned AppWidget, and if it has one, launch its configuration + * activity. If {@link android.app.Activity#RESULT_CANCELED} is returned, you should delete + * the appWidgetId. + * + * @see #ACTION_APPWIDGET_CONFIGURE + */ + public static final String ACTION_APPWIDGET_PICK = "android.appwidget.action.APPWIDGET_PICK"; + + /** + * Sent when it is time to configure your AppWidget while it is being added to a host. + * This action is not sent as a broadcast to the AppWidget provider, but as a startActivity + * to the activity specified in the {@link AppWidgetProviderInfo AppWidgetProviderInfo meta-data}. + * + *

    + * The intent will contain the following extras: + * + * + * + * + * + *
    {@link #EXTRA_APPWIDGET_ID}The appWidgetId to configure.
    + * + *

    If you return {@link android.app.Activity#RESULT_OK} using + * {@link android.app.Activity#setResult Activity.setResult()}, the AppWidget will be added, + * and you will receive an {@link #ACTION_APPWIDGET_UPDATE} broadcast for this AppWidget. + * If you return {@link android.app.Activity#RESULT_CANCELED}, the host will cancel the add + * and not display this AppWidget, and you will receive a {@link #ACTION_APPWIDGET_DELETED} broadcast. + */ + public static final String ACTION_APPWIDGET_CONFIGURE = "android.appwidget.action.APPWIDGET_CONFIGURE"; + + /** + * An intent extra that contains one appWidgetId. + *

    + * The value will be an int that can be retrieved like this: + * {@sample frameworks/base/tests/appwidgets/AppWidgetHostTest/src/com/android/tests/appwidgethost/AppWidgetHostActivity.java getExtra_EXTRA_APPWIDGET_ID} + */ + public static final String EXTRA_APPWIDGET_ID = "appWidgetId"; + + /** + * An intent extra that contains multiple appWidgetIds. + *

    + * The value will be an int array that can be retrieved like this: + * {@sample frameworks/base/tests/appwidgets/AppWidgetHostTest/src/com/android/tests/appwidgethost/TestAppWidgetProvider.java getExtra_EXTRA_APPWIDGET_IDS} + */ + public static final String EXTRA_APPWIDGET_IDS = "appWidgetIds"; + + /** + * A sentiel value that the AppWidget manager will never return as a appWidgetId. + */ + public static final int INVALID_APPWIDGET_ID = 0; + + /** + * Sent when it is time to update your AppWidget. + * + *

    This may be sent in response to a new instance for this AppWidget provider having + * been instantiated, the requested {@link AppWidgetProviderInfo#updatePeriodMillis update interval} + * having lapsed, or the system booting. + * + *

    + * The intent will contain the following extras: + * + * + * + * + * + *
    {@link #EXTRA_APPWIDGET_IDS}The appWidgetIds to update. This may be all of the AppWidgets created for this + * provider, or just a subset. The system tries to send updates for as few AppWidget + * instances as possible.
    + * + * @see AppWidgetProvider#onUpdate AppWidgetProvider.onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) + */ + public static final String ACTION_APPWIDGET_UPDATE = "android.appwidget.action.APPWIDGET_UPDATE"; + + /** + * Sent when an instance of an AppWidget is deleted from its host. + * + * @see AppWidgetProvider#onDeleted AppWidgetProvider.onDeleted(Context context, int[] appWidgetIds) + */ + public static final String ACTION_APPWIDGET_DELETED = "android.appwidget.action.APPWIDGET_DELETED"; + + /** + * Sent when an instance of an AppWidget is removed from the last host. + * + * @see AppWidgetProvider#onEnabled AppWidgetProvider.onEnabled(Context context) + */ + public static final String ACTION_APPWIDGET_DISABLED = "android.appwidget.action.APPWIDGET_DISABLED"; + + /** + * Sent when an instance of an AppWidget is added to a host for the first time. + * This broadcast is sent at boot time if there is a AppWidgetHost installed with + * an instance for this provider. + * + * @see AppWidgetProvider#onEnabled AppWidgetProvider.onEnabled(Context context) + */ + public static final String ACTION_APPWIDGET_ENABLED = "android.appwidget.action.APPWIDGET_ENABLED"; + + /** + * Field for the manifest meta-data tag. + * + * @see AppWidgetProviderInfo + */ + public static final String META_DATA_APPWIDGET_PROVIDER = "android.appwidget.provider"; + + static WeakHashMap> sManagerCache = new WeakHashMap(); + static IAppWidgetService sService; + + Context mContext; + + /** + * Get the AppWidgetManager instance to use for the supplied {@link android.content.Context + * Context} object. + */ + public static AppWidgetManager getInstance(Context context) { + synchronized (sManagerCache) { + if (sService == null) { + IBinder b = ServiceManager.getService(Context.APPWIDGET_SERVICE); + sService = IAppWidgetService.Stub.asInterface(b); + } + + WeakReference ref = sManagerCache.get(context); + AppWidgetManager result = null; + if (ref != null) { + result = ref.get(); + } + if (result == null) { + result = new AppWidgetManager(context); + sManagerCache.put(context, new WeakReference(result)); + } + return result; + } + } + + private AppWidgetManager(Context context) { + mContext = context; + } + + /** + * Set the RemoteViews to use for the specified appWidgetIds. + * + *

    + * It is okay to call this method both inside an {@link #ACTION_APPWIDGET_UPDATE} broadcast, + * and outside of the handler. + * This method will only work when called from the uid that owns the AppWidget provider. + * + * @param appWidgetIds The AppWidget instances for which to set the RemoteViews. + * @param views The RemoteViews object to show. + */ + public void updateAppWidget(int[] appWidgetIds, RemoteViews views) { + try { + sService.updateAppWidgetIds(appWidgetIds, views); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + + /** + * Set the RemoteViews to use for the specified appWidgetId. + * + *

    + * It is okay to call this method both inside an {@link #ACTION_APPWIDGET_UPDATE} broadcast, + * and outside of the handler. + * This method will only work when called from the uid that owns the AppWidget provider. + * + * @param appWidgetId The AppWidget instance for which to set the RemoteViews. + * @param views The RemoteViews object to show. + */ + public void updateAppWidget(int appWidgetId, RemoteViews views) { + updateAppWidget(new int[] { appWidgetId }, views); + } + + /** + * Set the RemoteViews to use for all AppWidget instances for the supplied AppWidget provider. + * + *

    + * It is okay to call this method both inside an {@link #ACTION_APPWIDGET_UPDATE} broadcast, + * and outside of the handler. + * This method will only work when called from the uid that owns the AppWidget provider. + * + * @param provider The {@link ComponentName} for the {@link + * android.content.BroadcastReceiver BroadcastReceiver} provider + * for your AppWidget. + * @param views The RemoteViews object to show. + */ + public void updateAppWidget(ComponentName provider, RemoteViews views) { + try { + sService.updateAppWidgetProvider(provider, views); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + + /** + * Return a list of the AppWidget providers that are currently installed. + */ + public List getInstalledProviders() { + try { + return sService.getInstalledProviders(); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + + /** + * Get the available info about the AppWidget. + * + * @return A appWidgetId. If the appWidgetId has not been bound to a provider yet, or + * you don't have access to that appWidgetId, null is returned. + */ + public AppWidgetProviderInfo getAppWidgetInfo(int appWidgetId) { + try { + return sService.getAppWidgetInfo(appWidgetId); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + + /** + * Set the component for a given appWidgetId. + * + *

    You need the APPWIDGET_LIST permission. This method is to be used by the + * AppWidget picker. + * + * @param appWidgetId The AppWidget instance for which to set the RemoteViews. + * @param provider The {@link android.content.BroadcastReceiver} that will be the AppWidget + * provider for this AppWidget. + */ + public void bindAppWidgetId(int appWidgetId, ComponentName provider) { + try { + sService.bindAppWidgetId(appWidgetId, provider); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + + /** + * Get the list of appWidgetIds that have been bound to the given AppWidget + * provider. + * + * @param provider The {@link android.content.BroadcastReceiver} that is the + * AppWidget provider to find appWidgetIds for. + */ + public int[] getAppWidgetIds(ComponentName provider) { + try { + return sService.getAppWidgetIds(provider); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } +} + diff --git a/core/java/android/appwidget/AppWidgetProvider.java b/core/java/android/appwidget/AppWidgetProvider.java new file mode 100755 index 0000000000000000000000000000000000000000..f70de9cde67e09bdf339327008168381ecd8296f --- /dev/null +++ b/core/java/android/appwidget/AppWidgetProvider.java @@ -0,0 +1,154 @@ +/* + * 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. + */ + +package android.appwidget; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; + +/** + * A conveience class to aid in implementing an AppWidget provider. + * Everything you can do with AppWidgetProvider, you can do with a regular {@link BroadcastReceiver}. + * AppWidgetProvider merely parses the relevant fields out of the Intent that is received in + * {@link #onReceive(Context,Intent) onReceive(Context,Intent)}, and calls hook methods + * with the received extras. + * + *

    Extend this class and override one or more of the {@link #onUpdate}, {@link #onDeleted}, + * {@link #onEnabled} or {@link #onDisabled} methods to implement your own AppWidget functionality. + * + *

    Sample Code

    + * For an example of how to write a AppWidget provider, see the + * android.appwidget + * package overview. + */ +public class AppWidgetProvider extends BroadcastReceiver { + /** + * Constructor to initialize AppWidgetProvider. + */ + public AppWidgetProvider() { + } + + /** + * Implements {@link BroadcastReceiver#onReceive} to dispatch calls to the various + * other methods on AppWidgetProvider. + * + * @param context The Context in which the receiver is running. + * @param intent The Intent being received. + */ + // BEGIN_INCLUDE(onReceive) + public void onReceive(Context context, Intent intent) { + // Protect against rogue update broadcasts (not really a security issue, + // just filter bad broacasts out so subclasses are less likely to crash). + String action = intent.getAction(); + if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { + Bundle extras = intent.getExtras(); + if (extras != null) { + int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS); + if (appWidgetIds != null && appWidgetIds.length > 0) { + this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds); + } + } + } + else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { + Bundle extras = intent.getExtras(); + if (extras != null) { + int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS); + if (appWidgetIds != null && appWidgetIds.length > 0) { + this.onDeleted(context, appWidgetIds); + } + } + } + else if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action)) { + this.onEnabled(context); + } + else if (AppWidgetManager.ACTION_APPWIDGET_DISABLED.equals(action)) { + this.onDisabled(context); + } + } + // END_INCLUDE(onReceive) + + /** + * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_UPDATE} broadcast when + * this AppWidget provider is being asked to provide {@link android.widget.RemoteViews RemoteViews} + * for a set of AppWidgets. Override this method to implement your own AppWidget functionality. + * + * {@more} + * + * @param context The {@link android.content.Context Context} in which this receiver is + * running. + * @param appWidgetManager A {@link AppWidgetManager} object you can call {@link + * AppWidgetManager#updateAppWidget} on. + * @param appWidgetIds The appWidgetIds for which an update is needed. Note that this + * may be all of the AppWidget instances for this provider, or just + * a subset of them. + * + * @see AppWidgetManager#ACTION_APPWIDGET_UPDATE + */ + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + } + + /** + * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_DELETED} broadcast when + * one or more AppWidget instances have been deleted. Override this method to implement + * your own AppWidget functionality. + * + * {@more} + * + * @param context The {@link android.content.Context Context} in which this receiver is + * running. + * @param appWidgetIds The appWidgetIds that have been deleted from their host. + * + * @see AppWidgetManager#ACTION_APPWIDGET_DELETED + */ + public void onDeleted(Context context, int[] appWidgetIds) { + } + + /** + * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_ENABLED} broadcast when + * the a AppWidget for this provider is instantiated. Override this method to implement your + * own AppWidget functionality. + * + * {@more} + * When the last AppWidget for this provider is deleted, + * {@link AppWidgetManager#ACTION_APPWIDGET_DISABLED} is sent by the AppWidget manager, and + * {@link #onDisabled} is called. If after that, an AppWidget for this provider is created + * again, onEnabled() will be called again. + * + * @param context The {@link android.content.Context Context} in which this receiver is + * running. + * + * @see AppWidgetManager#ACTION_APPWIDGET_ENABLED + */ + public void onEnabled(Context context) { + } + + /** + * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_DISABLED} broadcast, which + * is sent when the last AppWidget instance for this provider is deleted. Override this method + * to implement your own AppWidget functionality. + * + * {@more} + * + * @param context The {@link android.content.Context Context} in which this receiver is + * running. + * + * @see AppWidgetManager#ACTION_APPWIDGET_DISABLED + */ + public void onDisabled(Context context) { + } +} diff --git a/core/java/android/os/HandlerInterface.java b/core/java/android/appwidget/AppWidgetProviderInfo.aidl similarity index 57% rename from core/java/android/os/HandlerInterface.java rename to core/java/android/appwidget/AppWidgetProviderInfo.aidl index 62dc273e32c2e47fe225485ab1c3fcee26129f4b..82b3adac9e775c3cf66a005c60c0b21bf27e76b0 100644 --- a/core/java/android/os/HandlerInterface.java +++ b/core/java/android/appwidget/AppWidgetProviderInfo.aidl @@ -1,27 +1,19 @@ /* - * Copyright (C) 2006 The Android Open Source Project + * 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 + * 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 + * 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 + * 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. */ -package android.os; - -/** - * @hide - * @deprecated - */ -public interface HandlerInterface -{ - void handleMessage(Message msg); -} +package android.appwidget; +parcelable AppWidgetProviderInfo; diff --git a/core/java/android/appwidget/AppWidgetProviderInfo.java b/core/java/android/appwidget/AppWidgetProviderInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..8530c355b93512042f4a93a448f40433c7b7647f --- /dev/null +++ b/core/java/android/appwidget/AppWidgetProviderInfo.java @@ -0,0 +1,168 @@ +/* + * 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. + */ + +package android.appwidget; + +import android.os.Parcel; +import android.os.Parcelable; +import android.content.ComponentName; + +/** + * Describes the meta data for an installed AppWidget provider. The fields in this class + * correspond to the fields in the <appwidget-provider> xml tag. + */ +public class AppWidgetProviderInfo implements Parcelable { + /** + * Identity of this AppWidget component. This component should be a {@link + * android.content.BroadcastReceiver}, and it will be sent the AppWidget intents + * {@link android.appwidget as described in the AppWidget package documentation}. + * + *

    This field corresponds to the android:name attribute in + * the <receiver> element in the AndroidManifest.xml file. + */ + public ComponentName provider; + + /** + * Minimum width of the AppWidget, in dp. + * + *

    This field corresponds to the android:minWidth attribute in + * the AppWidget meta-data file. + */ + public int minWidth; + + /** + * Minimum height of the AppWidget, in dp. + * + *

    This field corresponds to the android:minHeight attribute in + * the AppWidget meta-data file. + */ + public int minHeight; + + /** + * How often, in milliseconds, that this AppWidget wants to be updated. + * The AppWidget manager may place a limit on how often a AppWidget is updated. + * + *

    This field corresponds to the android:updatePeriodMillis attribute in + * the AppWidget meta-data file. + */ + public int updatePeriodMillis; + + /** + * The resource id of the initial layout for this AppWidget. This should be + * displayed until the RemoteViews for the AppWidget is available. + * + *

    This field corresponds to the android:initialLayout attribute in + * the AppWidget meta-data file. + */ + public int initialLayout; + + /** + * The activity to launch that will configure the AppWidget. + * + *

    This class name of field corresponds to the android:configure attribute in + * the AppWidget meta-data file. The package name always corresponds to the package containing + * the AppWidget provider. + */ + public ComponentName configure; + + /** + * The label to display to the user in the AppWidget picker. If not supplied in the + * xml, the application label will be used. + * + *

    This field corresponds to the android:label attribute in + * the <receiver> element in the AndroidManifest.xml file. + */ + public String label; + + /** + * The icon to display for this AppWidget in the AppWidget picker. If not supplied in the + * xml, the application icon will be used. + * + *

    This field corresponds to the android:icon attribute in + * the <receiver> element in the AndroidManifest.xml file. + */ + public int icon; + + public AppWidgetProviderInfo() { + } + + /** + * Unflatten the AppWidgetProviderInfo from a parcel. + */ + public AppWidgetProviderInfo(Parcel in) { + if (0 != in.readInt()) { + this.provider = new ComponentName(in); + } + this.minWidth = in.readInt(); + this.minHeight = in.readInt(); + this.updatePeriodMillis = in.readInt(); + this.initialLayout = in.readInt(); + if (0 != in.readInt()) { + this.configure = new ComponentName(in); + } + this.label = in.readString(); + this.icon = in.readInt(); + } + + + public void writeToParcel(android.os.Parcel out, int flags) { + if (this.provider != null) { + out.writeInt(1); + this.provider.writeToParcel(out, flags); + } else { + out.writeInt(0); + } + out.writeInt(this.minWidth); + out.writeInt(this.minHeight); + out.writeInt(this.updatePeriodMillis); + out.writeInt(this.initialLayout); + if (this.configure != null) { + out.writeInt(1); + this.configure.writeToParcel(out, flags); + } else { + out.writeInt(0); + } + out.writeString(this.label); + out.writeInt(this.icon); + } + + public int describeContents() { + return 0; + } + + /** + * Parcelable.Creator that instantiates AppWidgetProviderInfo objects + */ + public static final Parcelable.Creator CREATOR + = new Parcelable.Creator() + { + public AppWidgetProviderInfo createFromParcel(Parcel parcel) + { + return new AppWidgetProviderInfo(parcel); + } + + public AppWidgetProviderInfo[] newArray(int size) + { + return new AppWidgetProviderInfo[size]; + } + }; + + public String toString() { + return "AppWidgetProviderInfo(provider=" + this.provider + ")"; + } +} + + diff --git a/core/java/android/appwidget/package.html b/core/java/android/appwidget/package.html new file mode 100644 index 0000000000000000000000000000000000000000..b6cd9c74d02ef04c51cc744b943344b9bab09b59 --- /dev/null +++ b/core/java/android/appwidget/package.html @@ -0,0 +1,136 @@ + +

    Android allows applications to publish views to be embedded in other applications. These +views are called widgets, and are published by "AppWidget providers." The component that can +contain widgets is called a "AppWidget host." +

    +

    AppWidget Providers

    + +

    AppWidget Hosts

    + + +{@more} + + +

    AppWidget Providers

    +

    +Any application can publish widgets. All an application needs to do to publish a widget is +to have a {@link android.content.BroadcastReceiver} that receives the {@link +android.appwidget.AppWidgetManager#ACTION_APPWIDGET_UPDATE AppWidgetManager.ACTION_APPWIDGET_UPDATE} intent, +and provide some meta-data about the widget. Android provides the +{@link android.appwidget.AppWidgetProvider} class, which extends BroadcastReceiver, as a convenience +class to aid in handling the broadcasts. + +

    Declaring a widget in the AndroidManifest

    + +

    +First, declare the {@link android.content.BroadcastReceiver} in your application's +AndroidManifest.xml file. + +{@sample frameworks/base/tests/appwidgets/AppWidgetHostTest/AndroidManifest.xml AppWidgetProvider} + +

    +The <receiver> element has the following attributes: +

      +
    • android:name - which specifies the + {@link android.content.BroadcastReceiver} or {@link android.appwidget.AppWidgetProvider} + class.
    • +
    • android:label - which specifies the string resource that + will be shown by the widget picker as the label.
    • +
    • android:icon - which specifies the drawable resource that + will be shown by the widget picker as the icon.
    • +
    + +

    +The <intent-filter> element tells the {@link android.content.pm.PackageManager} +that this {@link android.content.BroadcastReceiver} receives the {@link +android.appwidget.AppWidgetManager#ACTION_APPWIDGET_UPDATE AppWidgetManager.ACTION_APPWIDGET_UPDATE} broadcast. +The widget manager will send other broadcasts directly to your widget provider as required. +It is only necessary to explicitly declare that you accept the {@link +android.appwidget.AppWidgetManager#ACTION_APPWIDGET_UPDATE AppWidgetManager.ACTION_APPWIDGET_UPDATE} broadcast. + +

    +The <meta-data> element tells the widget manager which xml resource to +read to find the {@link android.appwidget.AppWidgetProviderInfo} for your widget provider. It has the following +attributes: +

      +
    • android:name="android.appwidget.provider" - identifies this meta-data + as the {@link android.appwidget.AppWidgetProviderInfo} descriptor.
    • +
    • android:resource - is the xml resource to use as that descriptor.
    • +
    + + +

    Adding the {@link android.appwidget.AppWidgetProviderInfo AppWidgetProviderInfo} meta-data

    + +

    +For a widget, the values in the {@link android.appwidget.AppWidgetProviderInfo} structure are supplied +in an XML resource. In the example above, the xml resource is referenced with +android:resource="@xml/appwidget_info". That XML file would go in your application's +directory at res/xml/appwidget_info.xml. Here is a simple example. + +{@sample frameworks/base/tests/appwidgets/AppWidgetHostTest/res/xml/appwidget_info.xml AppWidgetProviderInfo} + +

    +The attributes are as documented in the {@link android.appwidget.AppWidgetProviderInfo GagetInfo} class. (86400000 milliseconds means once per day) + + +

    Using the {@link android.appwidget.AppWidgetProvider AppWidgetProvider} class

    + +

    The AppWidgetProvider class is the easiest way to handle the widget provider intent broadcasts. +See the src/com/example/android/apis/appwidget/ExampleAppWidgetProvider.java +sample class in ApiDemos for an example. + +

    Keep in mind that since the the AppWidgetProvider is a BroadcastReceiver, +your process is not guaranteed to keep running after the callback methods return. See +Application Fundamentals > +Broadcast Receiver Lifecycle for more information. + + + +

    AppWidget Configuration UI

    + +

    +Widget hosts have the ability to start a configuration activity when a widget is instantiated. +The activity should be declared as normal in AndroidManifest.xml, and it should be listed in +the AppWidgetProviderInfo XML file in the android:configure attribute. + +

    The activity you specified will be launched with the {@link +android.appwidget.AppWidgetManager#ACTION_APPWIDGET_CONFIGURE} action. See the documentation for that +action for more info. + +

    See the src/com/example/android/apis/appwidget/ExampleAppWidgetConfigure.java +sample class in ApiDemos for an example. + + + +

    AppWidget Broadcast Intents

    + +

    {@link android.appwidget.AppWidgetProvider} is just a convenience class. If you would like +to receive the widget broadcasts directly, you can. The four intents you need to care about are: +

      +
    • {@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_UPDATE}
    • +
    • {@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_DELETED}
    • +
    • {@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_ENABLED}
    • +
    • {@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_DISABLED}
    • +
    + +

    By way of example, the implementation of +{@link android.appwidget.AppWidgetProvider#onReceive} is quite simple:

    + +{@sample frameworks/base/core/java/android/appwidget/AppWidgetProvider.java onReceive} + + +

    AppWidget Hosts

    +

    Widget hosts are the containers in which widgets can be placed. Most of the look and feel +details are left up to the widget hosts. For example, the home screen has one way of viewing +widgets, but the lock screen could also contain widgets, and it would have a different way of +adding, removing and otherwise managing widgets.

    +

    For more information on implementing your own widget host, see the +{@link android.appwidget.AppWidgetHost AppWidgetHost} class.

    + + diff --git a/core/java/android/bluetooth/BluetoothA2dp.java b/core/java/android/bluetooth/BluetoothA2dp.java index b0b0154abc90670e9b7d258eceae527f1cb077ac..2ea45d567f6add5cb7d037756ebf8dc4d31d00eb 100644 --- a/core/java/android/bluetooth/BluetoothA2dp.java +++ b/core/java/android/bluetooth/BluetoothA2dp.java @@ -49,6 +49,7 @@ import java.util.List; */ public class BluetoothA2dp { private static final String TAG = "BluetoothA2dp"; + private static final boolean DBG = false; /** int extra for SINK_STATE_CHANGED_ACTION */ public static final String SINK_STATE = @@ -103,6 +104,7 @@ public class BluetoothA2dp { * @hide */ public int connectSink(String address) { + if (DBG) log("connectSink(" + address + ")"); try { return mService.connectSink(address); } catch (RemoteException e) { @@ -119,6 +121,7 @@ public class BluetoothA2dp { * @hide */ public int disconnectSink(String address) { + if (DBG) log("disconnectSink(" + address + ")"); try { return mService.disconnectSink(address); } catch (RemoteException e) { @@ -133,6 +136,7 @@ public class BluetoothA2dp { * @hide */ public boolean isSinkConnected(String address) { + if (DBG) log("isSinkConnected(" + address + ")"); int state = getSinkState(address); return state == STATE_CONNECTED || state == STATE_PLAYING; } @@ -142,6 +146,7 @@ public class BluetoothA2dp { * @hide */ public List listConnectedSinks() { + if (DBG) log("listConnectedSinks()"); try { return mService.listConnectedSinks(); } catch (RemoteException e) { @@ -156,6 +161,7 @@ public class BluetoothA2dp { * @hide */ public int getSinkState(String address) { + if (DBG) log("getSinkState(" + address + ")"); try { return mService.getSinkState(address); } catch (RemoteException e) { @@ -177,6 +183,7 @@ public class BluetoothA2dp { * @return Result code, negative indicates an error */ public int setSinkPriority(String address, int priority) { + if (DBG) log("setSinkPriority(" + address + ", " + priority + ")"); try { return mService.setSinkPriority(address, priority); } catch (RemoteException e) { @@ -191,6 +198,7 @@ public class BluetoothA2dp { * @return non-negative priority, or negative error code on error. */ public int getSinkPriority(String address) { + if (DBG) log("getSinkPriority(" + address + ")"); try { return mService.getSinkPriority(address); } catch (RemoteException e) { @@ -244,4 +252,8 @@ public class BluetoothA2dp { return ""; } } + + private static void log(String msg) { + Log.d(TAG, msg); + } } diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java index d613e1cfba27e3d444aa9b8eaf0fc2a177027203..1ba1c1e86f7b968934198b08ef61fbaf81d5c622 100644 --- a/core/java/android/bluetooth/BluetoothDevice.java +++ b/core/java/android/bluetooth/BluetoothDevice.java @@ -31,10 +31,15 @@ import java.io.UnsupportedEncodingException; * @hide */ public class BluetoothDevice { - public static final int MODE_UNKNOWN = -1; - public static final int MODE_OFF = 0; - public static final int MODE_CONNECTABLE = 1; - public static final int MODE_DISCOVERABLE = 2; + /** Inquiry scan and page scan are both off. + * Device is neither discoverable nor connectable */ + public static final int SCAN_MODE_NONE = 0; + /** Page scan is on, inquiry scan is off. + * Device is connectable, but not discoverable */ + public static final int SCAN_MODE_CONNECTABLE = 1; + /** Page scan and inquiry scan are on. + * Device is connectable and discoverable */ + public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 3; public static final int RESULT_FAILURE = -1; public static final int RESULT_SUCCESS = 0; @@ -54,12 +59,14 @@ public class BluetoothDevice { /** A bond attempt failed because the other side explicilty rejected * bonding */ public static final int UNBOND_REASON_AUTH_REJECTED = 2; - /** A bond attempt failed because we cancelled the bonding process */ - public static final int UNBOND_REASON_CANCELLED = 3; + /** A bond attempt failed because we canceled the bonding process */ + public static final int UNBOND_REASON_AUTH_CANCELED = 3; /** A bond attempt failed because we could not contact the remote device */ - public static final int UNBOND_REASON_AUTH_REMOTE_DEVICE_DOWN = 4; + public static final int UNBOND_REASON_REMOTE_DEVICE_DOWN = 4; + /** A bond attempt failed because a discovery is in progress */ + public static final int UNBOND_REASON_DISCOVERY_IN_PROGRESS = 5; /** An existing bond was explicitly revoked */ - public static final int UNBOND_REASON_REMOVED = 5; + public static final int UNBOND_REASON_REMOVED = 6; private static final String TAG = "BluetoothDevice"; @@ -174,18 +181,6 @@ public class BluetoothDevice { return false; } - public String getMajorClass() { - try { - return mService.getMajorClass(); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } - public String getMinorClass() { - try { - return mService.getMinorClass(); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } public String getVersion() { try { return mService.getVersion(); @@ -211,15 +206,26 @@ public class BluetoothDevice { return null; } - public int getMode() { + /** + * Get the current scan mode. + * Used to determine if the local device is connectable and/or discoverable + * @return Scan mode, one of SCAN_MODE_* or an error code + */ + public int getScanMode() { try { - return mService.getMode(); + return mService.getScanMode(); } catch (RemoteException e) {Log.e(TAG, "", e);} - return MODE_UNKNOWN; + return BluetoothError.ERROR_IPC; } - public void setMode(int mode) { + + /** + * Set the current scan mode. + * Used to make the local device connectable and/or discoverable + * @param scanMode One of SCAN_MODE_* + */ + public void setScanMode(int scanMode) { try { - mService.setMode(mode); + mService.setScanMode(scanMode); } catch (RemoteException e) {Log.e(TAG, "", e);} } @@ -435,24 +441,6 @@ public class BluetoothDevice { return null; } - public String getRemoteAlias(String address) { - try { - return mService.getRemoteAlias(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } - public boolean setRemoteAlias(String address, String alias) { - try { - return mService.setRemoteAlias(address, alias); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return false; - } - public boolean clearRemoteAlias(String address) { - try { - return mService.clearRemoteAlias(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return false; - } public String getRemoteVersion(String address) { try { return mService.getRemoteVersion(address); @@ -477,24 +465,6 @@ public class BluetoothDevice { } catch (RemoteException e) {Log.e(TAG, "", e);} return null; } - public String getRemoteMajorClass(String address) { - try { - return mService.getRemoteMajorClass(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } - public String getRemoteMinorClass(String address) { - try { - return mService.getRemoteMinorClass(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } - public String[] getRemoteServiceClasses(String address) { - try { - return mService.getRemoteServiceClasses(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } /** * Returns the RFCOMM channel associated with the 16-byte UUID on @@ -512,12 +482,19 @@ public class BluetoothDevice { return false; } + /** + * Get the major, minor and servics classes of a remote device. + * These classes are encoded as a 32-bit integer. See BluetoothClass. + * @param address remote device + * @return 32-bit class suitable for use with BluetoothClass. + */ public int getRemoteClass(String address) { try { return mService.getRemoteClass(address); } catch (RemoteException e) {Log.e(TAG, "", e);} return BluetoothClass.ERROR; } + public byte[] getRemoteFeatures(String address) { try { return mService.getRemoteFeatures(address); @@ -576,8 +553,8 @@ public class BluetoothDevice { } - /* Sanity check a bluetooth address, such as "00:43:A8:23:10:F0" */ private static final int ADDRESS_LENGTH = 17; + /** Sanity check a bluetooth address, such as "00:43:A8:23:10:F0" */ public static boolean checkBluetoothAddress(String address) { if (address == null || address.length() != ADDRESS_LENGTH) { return false; diff --git a/core/java/android/bluetooth/BluetoothHeadset.java b/core/java/android/bluetooth/BluetoothHeadset.java index c3152719bbb61499843548769a859a65530b2908..1dbe0cccda51e122388aed7865abbc2377fd14c9 100644 --- a/core/java/android/bluetooth/BluetoothHeadset.java +++ b/core/java/android/bluetooth/BluetoothHeadset.java @@ -67,10 +67,15 @@ public class BluetoothHeadset { /** A headset is currently connected */ public static final int STATE_CONNECTED = 2; + /** A SCO audio channel is not established */ + public static final int AUDIO_STATE_DISCONNECTED = 0; + /** A SCO audio channel is established */ + public static final int AUDIO_STATE_CONNECTED = 1; + public static final int RESULT_FAILURE = 0; public static final int RESULT_SUCCESS = 1; - /** Connection cancelled before completetion. */ - public static final int RESULT_CANCELLED = 2; + /** Connection canceled before completetion. */ + public static final int RESULT_CANCELED = 2; /** Default priority for headsets that should be auto-connected */ public static final int PRIORITY_AUTO = 100; @@ -126,6 +131,7 @@ public class BluetoothHeadset { * are ok. */ public synchronized void close() { + if (DBG) log("close()"); if (mConnection != null) { mContext.unbindService(mConnection); mConnection = null; @@ -138,6 +144,7 @@ public class BluetoothHeadset { * object is currently not connected to the Headset service. */ public int getState() { + if (DBG) log("getState()"); if (mService != null) { try { return mService.getState(); @@ -156,6 +163,7 @@ public class BluetoothHeadset { * service. */ public String getHeadsetAddress() { + if (DBG) log("getHeadsetAddress()"); if (mService != null) { try { return mService.getHeadsetAddress(); @@ -180,6 +188,7 @@ public class BluetoothHeadset { * will be expected. */ public boolean connectHeadset(String address) { + if (DBG) log("connectHeadset(" + address + ")"); if (mService != null) { try { if (mService.connectHeadset(address)) { @@ -199,6 +208,7 @@ public class BluetoothHeadset { * if not currently connected to the headset service. */ public boolean isConnected(String address) { + if (DBG) log("isConnected(" + address + ")"); if (mService != null) { try { return mService.isConnected(address); @@ -216,6 +226,7 @@ public class BluetoothHeadset { * not currently connected to the Headset service. */ public boolean disconnectHeadset() { + if (DBG) log("disconnectHeadset()"); if (mService != null) { try { mService.disconnectHeadset(); @@ -235,6 +246,7 @@ public class BluetoothHeadset { * error. */ public boolean startVoiceRecognition() { + if (DBG) log("startVoiceRecognition()"); if (mService != null) { try { return mService.startVoiceRecognition(); @@ -252,6 +264,7 @@ public class BluetoothHeadset { * headset is not in voice recognition mode, or on error. */ public boolean stopVoiceRecognition() { + if (DBG) log("stopVoiceRecognition()"); if (mService != null) { try { return mService.stopVoiceRecognition(); @@ -282,6 +295,7 @@ public class BluetoothHeadset { * @return True if successful, false if there was some error. */ public boolean setPriority(String address, int priority) { + if (DBG) log("setPriority(" + address + ", " + priority + ")"); if (mService != null) { try { return mService.setPriority(address, priority); @@ -299,6 +313,7 @@ public class BluetoothHeadset { * @return non-negative priority, or negative error code on error. */ public int getPriority(String address) { + if (DBG) log("getPriority(" + address + ")"); if (mService != null) { try { return mService.getPriority(address); @@ -318,6 +333,12 @@ public class BluetoothHeadset { * @return True if this device might support HSP or HFP. */ public static boolean doesClassMatch(int btClass) { + // The render service class is required by the spec for HFP, so is a + // pretty good signal + if (BluetoothClass.Service.hasService(btClass, BluetoothClass.Service.RENDER)) { + return true; + } + // Just in case they forgot the render service class switch (BluetoothClass.Device.getDevice(btClass)) { case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE: case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET: @@ -344,4 +365,8 @@ public class BluetoothHeadset { } } }; + + private static void log(String msg) { + Log.d(TAG, msg); + } } diff --git a/core/java/android/bluetooth/BluetoothIntent.java b/core/java/android/bluetooth/BluetoothIntent.java index 57c46f98c299915adf2ad059ca2009be4174d0f5..9273d0defaeb094415391cf9ca7caa6e0eb37f5d 100644 --- a/core/java/android/bluetooth/BluetoothIntent.java +++ b/core/java/android/bluetooth/BluetoothIntent.java @@ -29,8 +29,8 @@ import android.annotation.SdkConstant.SdkConstantType; * @hide */ public interface BluetoothIntent { - public static final String MODE = - "android.bluetooth.intent.MODE"; + public static final String SCAN_MODE = + "android.bluetooth.intent.SCAN_MODE"; public static final String ADDRESS = "android.bluetooth.intent.ADDRESS"; public static final String NAME = @@ -45,6 +45,8 @@ public interface BluetoothIntent { "android.bluetooth.intent.HEADSET_STATE"; public static final String HEADSET_PREVIOUS_STATE = "android.bluetooth.intent.HEADSET_PREVIOUS_STATE"; + public static final String HEADSET_AUDIO_STATE = + "android.bluetooth.intent.HEADSET_AUDIO_STATE"; public static final String BOND_STATE = "android.bluetooth.intent.BOND_STATE"; public static final String BOND_PREVIOUS_STATE = @@ -62,9 +64,14 @@ public interface BluetoothIntent { @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String NAME_CHANGED_ACTION = "android.bluetooth.intent.action.NAME_CHANGED"; + + /** + * Broadcast when the scan mode changes. Always contains an int extra + * named SCAN_MODE that contains the new scan mode. + */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) - public static final String MODE_CHANGED_ACTION = - "android.bluetooth.intent.action.MODE_CHANGED"; + public static final String SCAN_MODE_CHANGED_ACTION = + "android.bluetooth.intent.action.SCAN_MODE_CHANGED"; @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String DISCOVERY_STARTED_ACTION = @@ -104,12 +111,6 @@ public interface BluetoothIntent { @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String REMOTE_NAME_FAILED_ACTION = "android.bluetooth.intent.action.REMOTE_NAME_FAILED"; - @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) - public static final String REMOTE_ALIAS_CHANGED_ACTION = - "android.bluetooth.intent.action.REMOTE_ALIAS_CHANGED"; - @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) - public static final String REMOTE_ALIAS_CLEARED_ACTION = - "android.bluetooth.intent.action.REMOTE_ALIAS_CLEARED"; /** * Broadcast when the bond state of a remote device changes. @@ -123,7 +124,18 @@ public interface BluetoothIntent { public static final String BOND_STATE_CHANGED_ACTION = "android.bluetooth.intent.action.BOND_STATE_CHANGED_ACTION"; + /** + * TODO(API release): Move into BluetoothHeadset + */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String HEADSET_STATE_CHANGED_ACTION = "android.bluetooth.intent.action.HEADSET_STATE_CHANGED"; + + /** + * TODO(API release): Consider incorporating as new state in + * HEADSET_STATE_CHANGED + */ + @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String HEADSET_AUDIO_STATE_CHANGED_ACTION = + "android.bluetooth.intent.action.HEADSET_ADUIO_STATE_CHANGED"; } diff --git a/core/java/android/bluetooth/HeadsetBase.java b/core/java/android/bluetooth/HeadsetBase.java index bce3388b6e9c6a04243625565ab2b6d768f2ad73..fd2d2ab88481ba18bb633eb45a126612aa22da29 100644 --- a/core/java/android/bluetooth/HeadsetBase.java +++ b/core/java/android/bluetooth/HeadsetBase.java @@ -21,13 +21,10 @@ import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; -import java.io.IOException; -import java.lang.Thread; - /** * The Android Bluetooth API is not finalized, and *will* change. Use at your * own risk. - * + * * The base RFCOMM (service) connection for a headset or handsfree device. * * In the future this class will be removed. @@ -90,7 +87,7 @@ public class HeadsetBase { /* Create from an already exisiting rfcomm connection */ public HeadsetBase(PowerManager pm, BluetoothDevice bluetooth, String address, int socketFd, - int rfcommChannel, Handler handler) { + int rfcommChannel, Handler handler) { mDirection = DIRECTION_INCOMING; mConnectTimestamp = System.currentTimeMillis(); mBluetooth = bluetooth; @@ -132,30 +129,8 @@ public class HeadsetBase { */ protected void initializeAtParser() { mAtParser = new AtParser(); - - // Microphone Gain - mAtParser.register("+VGM", new AtCommandHandler() { - @Override - public AtCommandResult handleSetCommand(Object[] args) { - // AT+VGM= in range [0,15] - // Headset/Handsfree is reporting its current gain setting - //TODO: sync to android UI - //TODO: Send unsolicited +VGM when volume changed on AG - return new AtCommandResult(AtCommandResult.OK); - } - }); - - // Speaker Gain - mAtParser.register("+VGS", new AtCommandHandler() { - @Override - public AtCommandResult handleSetCommand(Object[] args) { - // AT+VGS= in range [0,15] - // Headset/Handsfree is reporting its current gain to Android - //TODO: sync to AG UI - //TODO: Send unsolicited +VGS when volume changed on AG - return new AtCommandResult(AtCommandResult.OK); - } - }); + //TODO(): Get rid of this as there are no parsers registered. But because of dependencies, + //it needs to be done as part of refactoring HeadsetBase and BluetoothHandsfree } public AtParser getAtParser() { diff --git a/core/java/android/bluetooth/IBluetoothDevice.aidl b/core/java/android/bluetooth/IBluetoothDevice.aidl index 59f679f3cd6a463c76bb94c1341cb843906c88b7..4351d2ebc3863f26d4cdafe6ae8cc193d0ae3a54 100644 --- a/core/java/android/bluetooth/IBluetoothDevice.aidl +++ b/core/java/android/bluetooth/IBluetoothDevice.aidl @@ -32,15 +32,13 @@ interface IBluetoothDevice String getAddress(); String getName(); boolean setName(in String name); - String getMajorClass(); - String getMinorClass(); String getVersion(); String getRevision(); String getManufacturer(); String getCompany(); - int getMode(); - boolean setMode(int mode); + int getScanMode(); + boolean setScanMode(int mode); int getDiscoverableTimeout(); boolean setDiscoverableTimeout(int timeout); @@ -64,17 +62,11 @@ interface IBluetoothDevice int getBondState(in String address); String getRemoteName(in String address); - String getRemoteAlias(in String address); - boolean setRemoteAlias(in String address, in String alias); - boolean clearRemoteAlias(in String address); String getRemoteVersion(in String address); String getRemoteRevision(in String address); int getRemoteClass(in String address); String getRemoteManufacturer(in String address); String getRemoteCompany(in String address); - String getRemoteMajorClass(in String address); - String getRemoteMinorClass(in String address); - String[] getRemoteServiceClasses(in String address); boolean getRemoteServiceChannel(in String address, int uuid16, in IBluetoothDeviceCallback callback); byte[] getRemoteFeatures(in String adddress); String lastSeen(in String address); diff --git a/core/java/android/bluetooth/ScoSocket.java b/core/java/android/bluetooth/ScoSocket.java index 75b33296dd18e99e718eca2c8862f42ad57803f4..a43a08be1056750e2342f34e8eee30c27760e6da 100644 --- a/core/java/android/bluetooth/ScoSocket.java +++ b/core/java/android/bluetooth/ScoSocket.java @@ -16,17 +16,12 @@ package android.bluetooth; -import android.content.Context; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; -import java.io.IOException; -import java.lang.Thread; - - /** * The Android Bluetooth API is not finalized, and *will* change. Use at your * own risk. @@ -56,7 +51,7 @@ public class ScoSocket { private int mConnectedCode; private int mClosedCode; - private WakeLock mWakeLock; // held while STATE_CONNECTING or STATE_CONNECTED + private WakeLock mWakeLock; // held while in STATE_CONNECTING static { classInitNative(); @@ -130,6 +125,7 @@ public class ScoSocket { public synchronized void close() { if (DBG) log(this + " SCO OBJECT close() mState = " + mState); + acquireWakeLock(); mState = STATE_CLOSED; closeNative(); releaseWakeLock(); @@ -152,19 +148,16 @@ public class ScoSocket { mState = STATE_CLOSED; } mHandler.obtainMessage(mConnectedCode, mState, -1, this).sendToTarget(); - if (result < 0) { - releaseWakeLock(); - } + releaseWakeLock(); } private synchronized void onAccepted(int result) { if (VDBG) log("onAccepted() " + this); if (mState != STATE_ACCEPT) { - if (DBG) log("Strange state" + this); + if (DBG) log("Strange state " + this); return; } if (result >= 0) { - acquireWakeLock(); mState = STATE_CONNECTED; } else { mState = STATE_CLOSED; @@ -184,13 +177,13 @@ public class ScoSocket { private void acquireWakeLock() { if (!mWakeLock.isHeld()) { mWakeLock.acquire(); - if (VDBG) log("mWakeLock.acquire()" + this); + if (VDBG) log("mWakeLock.acquire() " + this); } } private void releaseWakeLock() { if (mWakeLock.isHeld()) { - if (VDBG) log("mWakeLock.release()" + this); + if (VDBG) log("mWakeLock.release() " + this); mWakeLock.release(); } } diff --git a/core/java/android/content/AsyncQueryHandler.java b/core/java/android/content/AsyncQueryHandler.java index 2d651a756111ca29bb11ec5fdd6961bc8f5311a2..ac851ccbcc211540b7c35b68dd201c0b988acf28 100644 --- a/core/java/android/content/AsyncQueryHandler.java +++ b/core/java/android/content/AsyncQueryHandler.java @@ -146,6 +146,20 @@ public abstract class AsyncQueryHandler extends Handler { * @param token A token passed into {@link #onQueryComplete} to identify * the query. * @param cookie An object that gets passed into {@link #onQueryComplete} + * @param uri The URI, using the content:// scheme, for the content to + * retrieve. + * @param projection A list of which columns to return. Passing null will + * return all columns, which is discouraged to prevent reading data + * from storage that isn't going to be used. + * @param selection A filter declaring which rows to return, formatted as an + * SQL WHERE clause (excluding the WHERE itself). Passing null will + * return all rows for the given URI. + * @param selectionArgs You may include ?s in selection, which will be + * replaced by the values from selectionArgs, in the order that they + * appear in the selection. The values will be bound as Strings. + * @param orderBy How to order the rows, formatted as an SQL ORDER BY + * clause (excluding the ORDER BY itself). Passing null will use the + * default sort order, which may be unordered. */ public void startQuery(int token, Object cookie, Uri uri, String[] projection, String selection, String[] selectionArgs, diff --git a/core/java/android/content/BroadcastReceiver.java b/core/java/android/content/BroadcastReceiver.java index cd92002b72ada65aa1183aa0e67cc94db3476405..08f6191ac71e7a9abfd04d072fa23163dba85b3c 100644 --- a/core/java/android/content/BroadcastReceiver.java +++ b/core/java/android/content/BroadcastReceiver.java @@ -16,7 +16,11 @@ package android.content; +import android.app.ActivityManagerNative; +import android.app.IActivityManager; import android.os.Bundle; +import android.os.IBinder; +import android.os.RemoteException; import android.util.Log; /** @@ -75,7 +79,7 @@ import android.util.Log; *

    The BroadcastReceiver class (when launched as a component through * a manifest's {@link android.R.styleable#AndroidManifestReceiver <receiver>} * tag) is an important part of an - * application's overall lifecycle.

    + * application's overall lifecycle.

    * *

    Topics covered here: *

      @@ -131,7 +135,7 @@ import android.util.Log; * tag in their AndroidManifest.xml) will be able to send an * Intent to the receiver. * - *

      See the Security Model + *

      See the Security and Permissions * document for more information on permissions and security in general. * * @@ -175,13 +179,35 @@ public abstract class BroadcastReceiver { * return a result to you asynchronously -- in particular, for interacting * with services, you should use * {@link Context#startService(Intent)} instead of - * {@link Context#bindService(Intent, ServiceConnection, int)}. + * {@link Context#bindService(Intent, ServiceConnection, int)}. If you wish + * to interact with a service that is already running, you can use + * {@link #peekService}. * * @param context The Context in which the receiver is running. * @param intent The Intent being received. */ public abstract void onReceive(Context context, Intent intent); + /** + * Provide a binder to an already-running service. This method is synchronous + * and will not start the target service if it is not present, so it is safe + * to call from {@link #onReceive}. + * + * @param myContext The Context that had been passed to {@link #onReceive(Context, Intent)} + * @param service The Intent indicating the service you wish to use. See {@link + * Context#startService(Intent)} for more information. + */ + public IBinder peekService(Context myContext, Intent service) { + IActivityManager am = ActivityManagerNative.getDefault(); + IBinder binder = null; + try { + binder = am.peekService(service, service.resolveTypeIfNeeded( + myContext.getContentResolver())); + } catch (RemoteException e) { + } + return binder; + } + /** * Change the current result code of this broadcast; only works with * broadcasts sent through diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java index 226c5ab77ebc5eff6602a15a67dfb6b194ad1384..25544deac10d1ee2eb2eacdf6dd371bbd3fe0cd6 100644 --- a/core/java/android/content/ContentProvider.java +++ b/core/java/android/content/ContentProvider.java @@ -18,6 +18,7 @@ package android.content; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; +import android.content.res.AssetFileDescriptor; import android.content.res.Configuration; import android.database.Cursor; import android.database.CursorToBulkCursorAdaptor; @@ -41,8 +42,8 @@ import java.io.FileNotFoundException; * multiple applications you can use a database directly via * {@link android.database.sqlite.SQLiteDatabase}. * - *

      See this page for more information on - * content providers.

      + *

      For more information, read Content + * Providers.

      * *

      When a request is made via * a {@link ContentResolver} the system inspects the authority of the given URI and passes the @@ -162,6 +163,13 @@ public abstract class ContentProvider implements ComponentCallbacks { return ContentProvider.this.openFile(uri, mode); } + public AssetFileDescriptor openAssetFile(Uri uri, String mode) + throws FileNotFoundException { + if (mode != null && mode.startsWith("rw")) checkWritePermission(uri); + else checkReadPermission(uri); + return ContentProvider.this.openAssetFile(uri, mode); + } + public ISyncAdapter getSyncAdapter() { checkWritePermission(null); return ContentProvider.this.getSyncAdapter().getISyncAdapter(); @@ -226,9 +234,9 @@ public abstract class ContentProvider implements ComponentCallbacks { /** * Return the name of the permission required for read-only access to * this content provider. This method can be called from multiple - * threads, as described in the - * Threading section of - * the Application Model overview. + * threads, as described in + * Application Fundamentals: + * Processes and Threads. */ public final String getReadPermission() { return mReadPermission; @@ -248,9 +256,9 @@ public abstract class ContentProvider implements ComponentCallbacks { /** * Return the name of the permission required for read/write access to * this content provider. This method can be called from multiple - * threads, as described in the - * Threading section of - * the Application Model overview. + * threads, as described in + * Application Fundamentals: + * Processes and Threads. */ public final String getWritePermission() { return mWritePermission; @@ -273,9 +281,9 @@ public abstract class ContentProvider implements ComponentCallbacks { * Receives a query request from a client in a local process, and * returns a Cursor. This is called internally by the {@link ContentResolver}. * This method can be called from multiple - * threads, as described in the - * Threading section of - * the Application Model overview. + * threads, as described in + * Application Fundamentals: + * Processes and Threads. *

      * Example client call:

      *

      // Request a specific record.
      @@ -330,9 +338,9 @@ public abstract class ContentProvider implements ComponentCallbacks {
            * vnd.android.cursor.item for a single record,
            * or vnd.android.cursor.dir/ for multiple items.
            * This method can be called from multiple
      -     * threads, as described in the
      -     * Threading section of
      -     * the Application Model overview.
      +     * threads, as described in
      +     * Application Fundamentals:
      +     * Processes and Threads.
            *
            * @param uri the URI to query.
            * @return a MIME type string, or null if there is no type.
      @@ -344,9 +352,9 @@ public abstract class ContentProvider implements ComponentCallbacks {
            * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
            * after inserting.
            * This method can be called from multiple
      -     * threads, as described in the
      -     * Threading section of the
      -     * Application Model overview.
      +     * threads, as described in
      +     * Application Fundamentals:
      +     * Processes and Threads.
            * @param uri The content:// URI of the insertion request.
            * @param values A set of column_name/value pairs to add to the database.
            * @return The URI for the newly inserted item.
      @@ -359,9 +367,9 @@ public abstract class ContentProvider implements ComponentCallbacks {
            * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
            * after inserting.
            * This method can be called from multiple
      -     * threads, as described in the
      -     * Threading section of
      -     * the Application Model overview.
      +     * threads, as described in
      +     * Application Fundamentals:
      +     * Processes and Threads.
            *
            * @param uri The content:// URI of the insertion request.
            * @param values An array of sets of column_name/value pairs to add to the database.
      @@ -382,9 +390,9 @@ public abstract class ContentProvider implements ComponentCallbacks {
            * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
            * after deleting.
            * This method can be called from multiple
      -     * threads, as described in the
      -     * Threading section of the
      -     * Application Model overview.
      +     * threads, as described in
      +     * Application Fundamentals:
      +     * Processes and Threads.
            *
            * 

      The implementation is responsible for parsing out a row ID at the end * of the URI, if a specific row is being deleted. That is, the client would @@ -405,9 +413,9 @@ public abstract class ContentProvider implements ComponentCallbacks { * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()} * after updating. * This method can be called from multiple - * threads, as described in the - * Threading section of the - * Application Model overview. + * threads, as described in + * Application Fundamentals: + * Processes and Threads. * * @param uri The URI to query. This can potentially have a record ID if this * is an update request for a specific record. @@ -422,9 +430,9 @@ public abstract class ContentProvider implements ComponentCallbacks { /** * Open a file blob associated with a content URI. * This method can be called from multiple - * threads, as described in the - * Threading section of the - * Application Model overview. + * threads, as described in + * Application Fundamentals: + * Processes and Threads. * *

      Returns a * ParcelFileDescriptor, from which you can obtain a @@ -438,8 +446,9 @@ public abstract class ContentProvider implements ComponentCallbacks { * of this method should create a new ParcelFileDescriptor for each call. * * @param uri The URI whose file is to be opened. - * @param mode Access mode for the file. May be "r" for read-only access - * or "rw" for read and write access. + * @param mode Access mode for the file. May be "r" for read-only access, + * "rw" for read and write access, or "rwt" for read and write access + * that truncates any existing file. * * @return Returns a new ParcelFileDescriptor which you can use to access * the file. @@ -448,19 +457,66 @@ public abstract class ContentProvider implements ComponentCallbacks { * no file associated with the given URI or the mode is invalid. * @throws SecurityException Throws SecurityException if the caller does * not have permission to access the file. - */ + * + * @see #openAssetFile(Uri, String) + * @see #openFileHelper(Uri, String) + */ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { throw new FileNotFoundException("No files supported by provider at " + uri); } + + /** + * This is like {@link #openFile}, but can be implemented by providers + * that need to be able to return sub-sections of files, often assets + * inside of their .apk. Note that when implementing this your clients + * must be able to deal with such files, either directly with + * {@link ContentResolver#openAssetFileDescriptor + * ContentResolver.openAssetFileDescriptor}, or by using the higher-level + * {@link ContentResolver#openInputStream ContentResolver.openInputStream} + * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream} + * methods. + * + *

      Note: if you are implementing this to return a full file, you + * should create the AssetFileDescriptor with + * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with + * applications that can not handle sub-sections of files.

      + * + * @param uri The URI whose file is to be opened. + * @param mode Access mode for the file. May be "r" for read-only access, + * "w" for write-only access (erasing whatever data is currently in + * the file), "wa" for write-only access to append to any existing data, + * "rw" for read and write access on any existing data, and "rwt" for read + * and write access that truncates any existing file. + * + * @return Returns a new AssetFileDescriptor which you can use to access + * the file. + * + * @throws FileNotFoundException Throws FileNotFoundException if there is + * no file associated with the given URI or the mode is invalid. + * @throws SecurityException Throws SecurityException if the caller does + * not have permission to access the file. + * + * @see #openFile(Uri, String) + * @see #openFileHelper(Uri, String) + */ + public AssetFileDescriptor openAssetFile(Uri uri, String mode) + throws FileNotFoundException { + ParcelFileDescriptor fd = openFile(uri, mode); + return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null; + } /** * Convenience for subclasses that wish to implement {@link #openFile} * by looking up a column named "_data" at the given URI. * * @param uri The URI to be opened. - * @param mode The file mode. + * @param mode The file mode. May be "r" for read-only access, + * "w" for write-only access (erasing whatever data is currently in + * the file), "wa" for write-only access to append to any existing data, + * "rw" for read and write access on any existing data, and "rwt" for read + * and write access that truncates any existing file. * * @return Returns a new ParcelFileDescriptor that can be used by the * client to access the file. @@ -489,16 +545,7 @@ public abstract class ContentProvider implements ComponentCallbacks { throw new FileNotFoundException("Column _data not found."); } - int modeBits; - if ("r".equals(mode)) { - modeBits = ParcelFileDescriptor.MODE_READ_ONLY; - } else if ("rw".equals(mode)) { - modeBits = ParcelFileDescriptor.MODE_READ_WRITE - | ParcelFileDescriptor.MODE_CREATE; - } else { - throw new FileNotFoundException("Bad mode for " + uri + ": " - + mode); - } + int modeBits = ContentResolver.modeToMode(uri, mode); return ParcelFileDescriptor.open(new File(path), modeBits); } @@ -507,9 +554,9 @@ public abstract class ContentProvider implements ComponentCallbacks { * This is intended for use by the sync system. If null then this * content provider is considered not syncable. * This method can be called from multiple - * threads, as described in the - * Threading section of - * the Application Model overview. + * threads, as described in + * Application Fundamentals: + * Processes and Threads. * * @return the SyncAdapter that is to be used by this ContentProvider, or null * if this ContentProvider is not syncable diff --git a/core/java/android/content/ContentProviderNative.java b/core/java/android/content/ContentProviderNative.java index ede2c9bee6e99852e138e49c0a821ee1fa0b3a4b..e5e3f749a8d750d3699c5d4c3a0191395586b61e 100644 --- a/core/java/android/content/ContentProviderNative.java +++ b/core/java/android/content/ContentProviderNative.java @@ -16,6 +16,7 @@ package android.content; +import android.content.res.AssetFileDescriptor; import android.database.BulkCursorNative; import android.database.BulkCursorToCursorAdaptor; import android.database.Cursor; @@ -187,6 +188,25 @@ abstract public class ContentProviderNative extends Binder implements IContentPr return true; } + case OPEN_ASSET_FILE_TRANSACTION: + { + data.enforceInterface(IContentProvider.descriptor); + Uri url = Uri.CREATOR.createFromParcel(data); + String mode = data.readString(); + + AssetFileDescriptor fd; + fd = openAssetFile(url, mode); + reply.writeNoException(); + if (fd != null) { + reply.writeInt(1); + fd.writeToParcel(reply, + Parcelable.PARCELABLE_WRITE_RETURN_VALUE); + } else { + reply.writeInt(0); + } + return true; + } + case GET_SYNC_ADAPTER_TRANSACTION: { data.enforceInterface(IContentProvider.descriptor); @@ -413,6 +433,29 @@ final class ContentProviderProxy implements IContentProvider return fd; } + public AssetFileDescriptor openAssetFile(Uri url, String mode) + throws RemoteException, FileNotFoundException { + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + + data.writeInterfaceToken(IContentProvider.descriptor); + + url.writeToParcel(data, 0); + data.writeString(mode); + + mRemote.transact(IContentProvider.OPEN_ASSET_FILE_TRANSACTION, data, reply, 0); + + DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(reply); + int has = reply.readInt(); + AssetFileDescriptor fd = has != 0 + ? AssetFileDescriptor.CREATOR.createFromParcel(reply) : null; + + data.recycle(); + reply.recycle(); + + return fd; + } + public ISyncAdapter getSyncAdapter() throws RemoteException { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java index 52f55b633727e56aef023ceb5a8300e09e5a304b..0d886ee23e8d1117296a8c38661ae4dcbfc5d255 100644 --- a/core/java/android/content/ContentResolver.java +++ b/core/java/android/content/ContentResolver.java @@ -17,6 +17,7 @@ package android.content; import android.content.pm.PackageManager.NameNotFoundException; +import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; @@ -28,6 +29,7 @@ import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.text.TextUtils; +import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -170,84 +172,52 @@ public abstract class ContentResolver { *
    1. android.resource ({@link #SCHEME_ANDROID_RESOURCE})
    2. *
    3. file ({@link #SCHEME_FILE})
    4. * - *
      The android.resource ({@link #SCHEME_ANDROID_RESOURCE}) Scheme
      - *

      - * A Uri object can be used to reference a resource in an APK file. The - * Uri should be one of the following formats: - *

        - *
      • android.resource://package_name/id_number
        - * package_name is your package name as listed in your AndroidManifest.xml. - * For example com.example.myapp
        - * id_number is the int form of the ID.
        - * The easiest way to construct this form is - *
        Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.my_resource");
        - *
      • - *
      • android.resource://package_name/type/name
        - * package_name is your package name as listed in your AndroidManifest.xml. - * For example com.example.myapp
        - * type is the string form of the resource type. For example, raw - * or drawable. - * name is the string form of the resource name. That is, whatever the file - * name was in your res directory, without the type extension. - * The easiest way to construct this form is - *
        Uri uri = Uri.parse("android.resource://com.example.myapp/raw/my_resource");
        - *
      • - *
      - * @param uri The desired "content:" URI. + * + *

      See {@link #openAssetFileDescriptor(Uri, String)} for more information + * on these schemes. + * + * @param uri The desired URI. * @return InputStream * @throws FileNotFoundException if the provided URI could not be opened. + * @see #openAssetFileDescriptor(Uri, String) */ public final InputStream openInputStream(Uri uri) throws FileNotFoundException { String scheme = uri.getScheme(); - if (SCHEME_CONTENT.equals(scheme)) { - ParcelFileDescriptor fd = openFileDescriptor(uri, "r"); - return fd != null ? new ParcelFileDescriptor.AutoCloseInputStream(fd) : null; - } else if (SCHEME_ANDROID_RESOURCE.equals(scheme)) { - String authority = uri.getAuthority(); - Resources r; - if (TextUtils.isEmpty(authority)) { - throw new FileNotFoundException("No authority: " + uri); - } else { - try { - r = mContext.getPackageManager().getResourcesForApplication(authority); - } catch (NameNotFoundException ex) { - throw new FileNotFoundException("No package found for authority: " + uri); - } - } - List path = uri.getPathSegments(); - if (path == null) { - throw new FileNotFoundException("No path: " + uri); - } - int len = path.size(); - int id; - if (len == 1) { - try { - id = Integer.parseInt(path.get(0)); - } catch (NumberFormatException e) { - throw new FileNotFoundException("Single path segment is not a resource ID: " + uri); - } - } else if (len == 2) { - id = r.getIdentifier(path.get(1), path.get(0), authority); - } else { - throw new FileNotFoundException("More than two path segments: " + uri); - } - if (id == 0) { - throw new FileNotFoundException("No resource found for: " + uri); - } + if (SCHEME_ANDROID_RESOURCE.equals(scheme)) { + // Note: left here to avoid breaking compatibility. May be removed + // with sufficient testing. + OpenResourceIdResult r = getResourceId(uri); try { - InputStream stream = r.openRawResource(id); + InputStream stream = r.r.openRawResource(r.id); return stream; } catch (Resources.NotFoundException ex) { - throw new FileNotFoundException("Resource ID does not exist: " + uri); + throw new FileNotFoundException("Resource does not exist: " + uri); } } else if (SCHEME_FILE.equals(scheme)) { + // Note: left here to avoid breaking compatibility. May be removed + // with sufficient testing. return new FileInputStream(uri.getPath()); } else { - throw new FileNotFoundException("Unknown scheme: " + uri); + AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r"); + try { + return fd != null ? fd.createInputStream() : null; + } catch (IOException e) { + throw new FileNotFoundException("Unable to create stream"); + } } } + /** + * Synonym for {@link #openOutputStream(Uri, String) + * openOutputStream(uri, "w")}. + * @throws FileNotFoundException if the provided URI could not be opened. + */ + public final OutputStream openOutputStream(Uri uri) + throws FileNotFoundException { + return openOutputStream(uri, "w"); + } + /** * Open a stream on to the content associated with a content URI. If there * is no data associated with the URI, FileNotFoundException is thrown. @@ -255,34 +225,47 @@ public abstract class ContentResolver { *

      Accepts the following URI schemes:
      *
        *
      • content ({@link #SCHEME_CONTENT})
      • + *
      • file ({@link #SCHEME_FILE})
      • *
      * - * @param uri The desired "content:" URI. + *

      See {@link #openAssetFileDescriptor(Uri, String)} for more information + * on these schemes. + * + * @param uri The desired URI. + * @param mode May be "w", "wa", "rw", or "rwt". * @return OutputStream + * @throws FileNotFoundException if the provided URI could not be opened. + * @see #openAssetFileDescriptor(Uri, String) */ - public final OutputStream openOutputStream(Uri uri) + public final OutputStream openOutputStream(Uri uri, String mode) throws FileNotFoundException { - String scheme = uri.getScheme(); - if (SCHEME_CONTENT.equals(scheme)) { - ParcelFileDescriptor fd = openFileDescriptor(uri, "rw"); - return fd != null - ? new ParcelFileDescriptor.AutoCloseOutputStream(fd) : null; - } else { - throw new FileNotFoundException("Unknown scheme: " + uri); + AssetFileDescriptor fd = openAssetFileDescriptor(uri, mode); + try { + return fd != null ? fd.createOutputStream() : null; + } catch (IOException e) { + throw new FileNotFoundException("Unable to create stream"); } } /** * Open a raw file descriptor to access data under a "content:" URI. This - * interacts with the underlying {@link ContentProvider#openFile} - * ContentProvider.openFile()} method of the provider associated with the - * given URI, to retrieve any file stored there. + * is like {@link #openAssetFileDescriptor(Uri, String)}, but uses the + * underlying {@link ContentProvider#openFile} + * ContentProvider.openFile()} method, so will not work with + * providers that return sub-sections of files. If at all possible, + * you should use {@link #openAssetFileDescriptor(Uri, String)}. You + * will receive a FileNotFoundException exception if the provider returns a + * sub-section of a file. * *

      Accepts the following URI schemes:
      *
        *
      • content ({@link #SCHEME_CONTENT})
      • + *
      • file ({@link #SCHEME_FILE})
      • *
      * + *

      See {@link #openAssetFileDescriptor(Uri, String)} for more information + * on these schemes. + * * @param uri The desired URI to open. * @param mode The file mode to use, as per {@link ContentProvider#openFile * ContentProvider.openFile}. @@ -290,32 +273,189 @@ public abstract class ContentResolver { * own this descriptor and are responsible for closing it when done. * @throws FileNotFoundException Throws FileNotFoundException of no * file exists under the URI or the mode is invalid. + * @see #openAssetFileDescriptor(Uri, String) */ public final ParcelFileDescriptor openFileDescriptor(Uri uri, String mode) throws FileNotFoundException { - IContentProvider provider = acquireProvider(uri); - if (provider == null) { - throw new FileNotFoundException("No content provider: " + uri); + AssetFileDescriptor afd = openAssetFileDescriptor(uri, mode); + if (afd == null) { + return null; + } + + if (afd.getDeclaredLength() < 0) { + // This is a full file! + return afd.getParcelFileDescriptor(); } + + // Client can't handle a sub-section of a file, so close what + // we got and bail with an exception. try { - ParcelFileDescriptor fd = provider.openFile(uri, mode); - if(fd == null) { + afd.close(); + } catch (IOException e) { + } + + throw new FileNotFoundException("Not a whole file"); + } + + /** + * Open a raw file descriptor to access data under a "content:" URI. This + * interacts with the underlying {@link ContentProvider#openAssetFile} + * ContentProvider.openAssetFile()} method of the provider associated with the + * given URI, to retrieve any file stored there. + * + *

      Accepts the following URI schemes:
      + *
        + *
      • content ({@link #SCHEME_CONTENT})
      • + *
      • android.resource ({@link #SCHEME_ANDROID_RESOURCE})
      • + *
      • file ({@link #SCHEME_FILE})
      • + *
      + *
      The android.resource ({@link #SCHEME_ANDROID_RESOURCE}) Scheme
      + *

      + * A Uri object can be used to reference a resource in an APK file. The + * Uri should be one of the following formats: + *

        + *
      • android.resource://package_name/id_number
        + * package_name is your package name as listed in your AndroidManifest.xml. + * For example com.example.myapp
        + * id_number is the int form of the ID.
        + * The easiest way to construct this form is + *
        Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.my_resource");
        + *
      • + *
      • android.resource://package_name/type/name
        + * package_name is your package name as listed in your AndroidManifest.xml. + * For example com.example.myapp
        + * type is the string form of the resource type. For example, raw + * or drawable. + * name is the string form of the resource name. That is, whatever the file + * name was in your res directory, without the type extension. + * The easiest way to construct this form is + *
        Uri uri = Uri.parse("android.resource://com.example.myapp/raw/my_resource");
        + *
      • + *
      + * + * @param uri The desired URI to open. + * @param mode The file mode to use, as per {@link ContentProvider#openAssetFile + * ContentProvider.openAssetFile}. + * @return Returns a new ParcelFileDescriptor pointing to the file. You + * own this descriptor and are responsible for closing it when done. + * @throws FileNotFoundException Throws FileNotFoundException of no + * file exists under the URI or the mode is invalid. + */ + public final AssetFileDescriptor openAssetFileDescriptor(Uri uri, + String mode) throws FileNotFoundException { + String scheme = uri.getScheme(); + if (SCHEME_ANDROID_RESOURCE.equals(scheme)) { + if (!"r".equals(mode)) { + throw new FileNotFoundException("Can't write resources: " + uri); + } + OpenResourceIdResult r = getResourceId(uri); + try { + return r.r.openRawResourceFd(r.id); + } catch (Resources.NotFoundException ex) { + throw new FileNotFoundException("Resource does not exist: " + uri); + } + } else if (SCHEME_FILE.equals(scheme)) { + ParcelFileDescriptor pfd = ParcelFileDescriptor.open( + new File(uri.getPath()), modeToMode(uri, mode)); + return new AssetFileDescriptor(pfd, 0, -1); + } else { + IContentProvider provider = acquireProvider(uri); + if (provider == null) { + throw new FileNotFoundException("No content provider: " + uri); + } + try { + AssetFileDescriptor fd = provider.openAssetFile(uri, mode); + if(fd == null) { + releaseProvider(provider); + return null; + } + ParcelFileDescriptor pfd = new ParcelFileDescriptorInner( + fd.getParcelFileDescriptor(), provider); + return new AssetFileDescriptor(pfd, fd.getStartOffset(), + fd.getDeclaredLength()); + } catch (RemoteException e) { releaseProvider(provider); - return null; + throw new FileNotFoundException("Dead content provider: " + uri); + } catch (FileNotFoundException e) { + releaseProvider(provider); + throw e; + } catch (RuntimeException e) { + releaseProvider(provider); + throw e; } - return new ParcelFileDescriptorInner(fd, provider); - } catch (RemoteException e) { - releaseProvider(provider); - throw new FileNotFoundException("Dead content provider: " + uri); - } catch (FileNotFoundException e) { - releaseProvider(provider); - throw e; - } catch (RuntimeException e) { - releaseProvider(provider); - throw e; } } + class OpenResourceIdResult { + Resources r; + int id; + } + + OpenResourceIdResult getResourceId(Uri uri) throws FileNotFoundException { + String authority = uri.getAuthority(); + Resources r; + if (TextUtils.isEmpty(authority)) { + throw new FileNotFoundException("No authority: " + uri); + } else { + try { + r = mContext.getPackageManager().getResourcesForApplication(authority); + } catch (NameNotFoundException ex) { + throw new FileNotFoundException("No package found for authority: " + uri); + } + } + List path = uri.getPathSegments(); + if (path == null) { + throw new FileNotFoundException("No path: " + uri); + } + int len = path.size(); + int id; + if (len == 1) { + try { + id = Integer.parseInt(path.get(0)); + } catch (NumberFormatException e) { + throw new FileNotFoundException("Single path segment is not a resource ID: " + uri); + } + } else if (len == 2) { + id = r.getIdentifier(path.get(1), path.get(0), authority); + } else { + throw new FileNotFoundException("More than two path segments: " + uri); + } + if (id == 0) { + throw new FileNotFoundException("No resource found for: " + uri); + } + OpenResourceIdResult res = new OpenResourceIdResult(); + res.r = r; + res.id = id; + return res; + } + + /** @hide */ + static public int modeToMode(Uri uri, String mode) throws FileNotFoundException { + int modeBits; + if ("r".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_READ_ONLY; + } else if ("w".equals(mode) || "wt".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY + | ParcelFileDescriptor.MODE_CREATE + | ParcelFileDescriptor.MODE_TRUNCATE; + } else if ("wa".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY + | ParcelFileDescriptor.MODE_CREATE + | ParcelFileDescriptor.MODE_APPEND; + } else if ("rw".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_READ_WRITE + | ParcelFileDescriptor.MODE_CREATE; + } else if ("rwt".equals(mode)) { + modeBits = ParcelFileDescriptor.MODE_READ_WRITE + | ParcelFileDescriptor.MODE_CREATE + | ParcelFileDescriptor.MODE_TRUNCATE; + } else { + throw new FileNotFoundException("Bad mode for " + uri + ": " + + mode); + } + return modeBits; + } + /** * Inserts a row into a table at the given URL. * diff --git a/core/java/android/content/ContentServiceNative.java b/core/java/android/content/ContentServiceNative.java index f05050190d670f47f063b54816930b1e848c3160..364f9ee8a29d41845d9b5c80e03d09ed2bb816fe 100644 --- a/core/java/android/content/ContentServiceNative.java +++ b/core/java/android/content/ContentServiceNative.java @@ -75,6 +75,13 @@ abstract class ContentServiceNative extends Binder implements IContentService { try { switch (code) { + case 5038: { + data.readString(); // ignore the interface token that service generated + Uri uri = Uri.parse(data.readString()); + notifyChange(uri, null, false, false); + return true; + } + case REGISTER_CONTENT_OBSERVER_TRANSACTION: { Uri uri = Uri.CREATOR.createFromParcel(data); boolean notifyForDescendents = data.readInt() != 0; diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java index 3908aa1bf80fce3b38e817fde7630ddcc12759fd..9a0dc9f189bb19fec37f24a68075e88ded89f8f0 100644 --- a/core/java/android/content/Context.java +++ b/core/java/android/content/Context.java @@ -127,7 +127,7 @@ public abstract class Context { * current process. */ public abstract Context getApplicationContext(); - + /** * Return a localized, styled CharSequence from the application's package's * default string table. @@ -428,7 +428,7 @@ public abstract class Context { * cursor when query is called. * * @return The contents of a newly created database with the given name. - * @throws SQLiteException if the database file could not be opened. + * @throws android.database.sqlite.SQLiteException if the database file could not be opened. * * @see #MODE_PRIVATE * @see #MODE_WORLD_READABLE @@ -1064,7 +1064,7 @@ public abstract class Context { * @see #AUDIO_SERVICE * @see android.media.AudioManager * @see #TELEPHONY_SERVICE - * @see android.internal.TelephonyManager + * @see android.telephony.TelephonyManager * @see #INPUT_METHOD_SERVICE * @see android.view.inputmethod.InputMethodManager */ @@ -1250,12 +1250,12 @@ public abstract class Context { /** * Use with {@link #getSystemService} to retrieve a - * {@blink android.gadget.GadgetManager} for accessing wallpapers. + * {@blink android.appwidget.AppWidgetManager} for accessing AppWidgets. * * @hide * @see #getSystemService */ - public static final String GADGET_SERVICE = "gadget"; + public static final String APPWIDGET_SERVICE = "appwidget"; /** * Determine whether the given permission is allowed for a particular diff --git a/core/java/android/content/IContentProvider.java b/core/java/android/content/IContentProvider.java index a6ef46f420512c9ebb76ce26a63cbae2dd33cc26..06069569db974db104ca3ea49c689e34f4dfc377 100644 --- a/core/java/android/content/IContentProvider.java +++ b/core/java/android/content/IContentProvider.java @@ -16,6 +16,7 @@ package android.content; +import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.database.CursorWindow; import android.database.IBulkCursor; @@ -52,6 +53,8 @@ public interface IContentProvider extends IInterface { String[] selectionArgs) throws RemoteException; public ParcelFileDescriptor openFile(Uri url, String mode) throws RemoteException, FileNotFoundException; + public AssetFileDescriptor openAssetFile(Uri url, String mode) + throws RemoteException, FileNotFoundException; public ISyncAdapter getSyncAdapter() throws RemoteException; /* IPC constants */ @@ -65,4 +68,5 @@ public interface IContentProvider extends IInterface { static final int GET_SYNC_ADAPTER_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 10; static final int BULK_INSERT_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 12; static final int OPEN_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 13; + static final int OPEN_ASSET_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 14; } diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java index 23fd17187927db51681762471812b5b6a5547237..c47b72fffc2f5928e3f0cee7d8ef4f72d43eac30 100644 --- a/core/java/android/content/Intent.java +++ b/core/java/android/content/Intent.java @@ -504,6 +504,8 @@ import java.util.Set; *
    5. {@link #ACTION_PACKAGE_ADDED} *
    6. {@link #ACTION_PACKAGE_CHANGED} *
    7. {@link #ACTION_PACKAGE_REMOVED} + *
    8. {@link #ACTION_PACKAGE_RESTARTED} + *
    9. {@link #ACTION_PACKAGE_DATA_CLEARED} *
    10. {@link #ACTION_UID_REMOVED} *
    11. {@link #ACTION_BATTERY_CHANGED} *
    12. {@link #ACTION_POWER_CONNECTED} @@ -522,9 +524,9 @@ import java.util.Set; *
    13. {@link #CATEGORY_ALTERNATIVE} *
    14. {@link #CATEGORY_SELECTED_ALTERNATIVE} *
    15. {@link #CATEGORY_LAUNCHER} + *
    16. {@link #CATEGORY_INFO} *
    17. {@link #CATEGORY_HOME} *
    18. {@link #CATEGORY_PREFERENCE} - *
    19. {@link #CATEGORY_GADGET} *
    20. {@link #CATEGORY_TEST} * * @@ -1026,6 +1028,15 @@ public class Intent implements Parcelable { */ @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) public static final String ACTION_VOICE_COMMAND = "android.intent.action.VOICE_COMMAND"; + + /** + * Activity Action: Start action associated with long pressing on the + * search key. + *

      Input: Nothing. + *

      Output: Nothing. + */ + @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) + public static final String ACTION_SEARCH_LONG_PRESS = "android.intent.action.SEARCH_LONG_PRESS"; // --------------------------------------------------------------------- // --------------------------------------------------------------------- @@ -1041,6 +1052,14 @@ public class Intent implements Parcelable { */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_SCREEN_ON = "android.intent.action.SCREEN_ON"; + + /** + * Broadcast Action: Sent when the user is present after device wakes up (e.g when the + * keyguard is gone). + */ + @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String ACTION_USER_PRESENT= "android.intent.action.USER_PRESENT"; + /** * Broadcast Action: The current time has changed. Sent every * minute. You can not receive this through components declared @@ -1109,6 +1128,12 @@ public class Intent implements Parcelable { /** * Broadcast Action: A new application package has been installed on the * device. The data contains the name of the package. + *

      My include the following extras: + *

        + *
      • {@link #EXTRA_UID} containing the integer uid assigned to the new package. + *
      • {@link #EXTRA_REPLACING} is set to true if this is following + * an {@link #ACTION_PACKAGE_REMOVED} broadcast for the same package. + *
      */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_PACKAGE_ADDED = "android.intent.action.PACKAGE_ADDED"; @@ -1116,22 +1141,48 @@ public class Intent implements Parcelable { * Broadcast Action: An existing application package has been removed from * the device. The data contains the name of the package. The package * that is being installed does not receive this Intent. + *
        + *
      • {@link #EXTRA_UID} containing the integer uid previously assigned + * to the package. + *
      • {@link #EXTRA_DATA_REMOVED} is set to true if the entire + * application -- data and code -- is being removed. + *
      • {@link #EXTRA_REPLACING} is set to true if this will be followed + * by an {@link #ACTION_PACKAGE_ADDED} broadcast for the same package. + *
      */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_PACKAGE_REMOVED = "android.intent.action.PACKAGE_REMOVED"; /** * Broadcast Action: An existing application package has been changed (e.g. a component has been * enabled or disabled. The data contains the name of the package. + *
        + *
      • {@link #EXTRA_UID} containing the integer uid assigned to the package. + *
      */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_PACKAGE_CHANGED = "android.intent.action.PACKAGE_CHANGED"; /** - * Broadcast Action: The user has restarted a package, all runtime state + * Broadcast Action: The user has restarted a package, and all of its + * processes have been killed. All runtime state * associated with it (processes, alarms, notifications, etc) should - * be remove. The data contains the name of the package. + * be removed. The data contains the name of the package. + *
        + *
      • {@link #EXTRA_UID} containing the integer uid assigned to the package. + *
      */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_PACKAGE_RESTARTED = "android.intent.action.PACKAGE_RESTARTED"; + /** + * Broadcast Action: The user has cleared the data of a package. This should + * be preceded by {@link #ACTION_PACKAGE_RESTARTED}, after which all of + * its persistent data is erased and this broadcast sent. The data contains + * the name of the package. + *
        + *
      • {@link #EXTRA_UID} containing the integer uid assigned to the package. + *
      + */ + @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String ACTION_PACKAGE_DATA_CLEARED = "android.intent.action.PACKAGE_DATA_CLEARED"; /** * Broadcast Action: A user ID has been removed from the system. The user * ID number is stored in the extra data under {@link #EXTRA_UID}. @@ -1248,7 +1299,6 @@ public class Intent implements Parcelable { /** * Broadcast Action: External media is present, and being disk-checked * The path to the mount point for the checking media is contained in the Intent.mData field. - * @hide */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_MEDIA_CHECKING = "android.intent.action.MEDIA_CHECKING"; @@ -1256,7 +1306,6 @@ public class Intent implements Parcelable { /** * Broadcast Action: External media is present, but is using an incompatible fs (or is blank) * The path to the mount point for the checking media is contained in the Intent.mData field. - * @hide */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_MEDIA_NOFS = "android.intent.action.MEDIA_NOFS"; @@ -1524,16 +1573,17 @@ public class Intent implements Parcelable { @SdkConstant(SdkConstantType.INTENT_CATEGORY) public static final String CATEGORY_TAB = "android.intent.category.TAB"; /** - * This activity can be embedded inside of another activity that is hosting - * gadgets. + * Should be displayed in the top-level launcher. */ @SdkConstant(SdkConstantType.INTENT_CATEGORY) - public static final String CATEGORY_GADGET = "android.intent.category.GADGET"; + public static final String CATEGORY_LAUNCHER = "android.intent.category.LAUNCHER"; /** - * Should be displayed in the top-level launcher. + * Provides information about the package it is in; typically used if + * a package does not contain a {@link #CATEGORY_LAUNCHER} to provide + * a front-door to the user without having to be shown in the all apps list. */ @SdkConstant(SdkConstantType.INTENT_CATEGORY) - public static final String CATEGORY_LAUNCHER = "android.intent.category.LAUNCHER"; + public static final String CATEGORY_INFO = "android.intent.category.INFO"; /** * This is the home activity, that is the first activity that is displayed * when the device boots. @@ -1552,9 +1602,6 @@ public class Intent implements Parcelable { public static final String CATEGORY_DEVELOPMENT_PREFERENCE = "android.intent.category.DEVELOPMENT_PREFERENCE"; /** * Capable of running inside a parent activity container. - * - *

      Note: being removed in favor of more explicit categories such as - * CATEGORY_GADGET */ @SdkConstant(SdkConstantType.INTENT_CATEGORY) public static final String CATEGORY_EMBED = "android.intent.category.EMBED"; @@ -1676,6 +1723,22 @@ public class Intent implements Parcelable { */ public static final String EXTRA_UID = "android.intent.extra.UID"; + /** + * Used as a boolean extra field in {@link android.content.Intent#ACTION_PACKAGE_REMOVED} + * intents to indicate whether this represents a full uninstall (removing + * both the code and its data) or a partial uninstall (leaving its data, + * implying that this is an update). + */ + public static final String EXTRA_DATA_REMOVED = "android.intent.extra.DATA_REMOVED"; + + /** + * Used as a boolean extra field in {@link android.content.Intent#ACTION_PACKAGE_REMOVED} + * intents to indicate that this is a replacement of the package, so this + * broadcast will immediately be followed by an add broadcast for a + * different version of the same package. + */ + public static final String EXTRA_REPLACING = "android.intent.extra.REPLACING"; + /** * Used as an int extra field in {@link android.app.AlarmManager} intents * to tell the application being invoked how many pending alarms are being @@ -1739,9 +1802,9 @@ public class Intent implements Parcelable { * next task activity) defines an atomic group of activities that the * user can move to. Tasks can be moved to the foreground and background; * all of the activities inside of a particular task always remain in - * the same order. See the - * Application Model - * documentation for more details on tasks. + * the same order. See + * Application Fundamentals: + * Activities and Tasks for more details on tasks. * *

      This flag is generally used by activities that want * to present a "launcher" style behavior: they give the user a list of @@ -1774,9 +1837,8 @@ public class Intent implements Parcelable { *

      This flag is ignored if * {@link #FLAG_ACTIVITY_NEW_TASK} is not set. * - *

      See the - * Application Model - * documentation for more details on tasks. + *

      See Application Fundamentals: + * Activities and Tasks for more details on tasks. */ public static final int FLAG_ACTIVITY_MULTIPLE_TASK = 0x08000000; /** @@ -1791,8 +1853,8 @@ public class Intent implements Parcelable { * Intent, resulting in the stack now being: A, B. * *

      The currently running instance of task B in the above example will - * either receiving the new intent you are starting here in its - * onNewIntent() method, or be itself finished and restarting with the + * either receive the new intent you are starting here in its + * onNewIntent() method, or be itself finished and restarted with the * new intent. If it has declared its launch mode to be "multiple" (the * default) it will be finished and re-created; for all other launch modes * it will receive the Intent in the current instance. @@ -1804,9 +1866,8 @@ public class Intent implements Parcelable { * especially useful, for example, when launching an activity from the * notification manager. * - *

      See the - * Application Model - * documentation for more details on tasks. + *

      See Application Fundamentals: + * Activities and Tasks for more details on tasks. */ public static final int FLAG_ACTIVITY_CLEAR_TOP = 0x04000000; /** @@ -1876,7 +1937,7 @@ public class Intent implements Parcelable { */ public static final int FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET = 0x00080000; /** - * If set, this flag will prevent the normal {@link android.app.Activity#onUserLeaving} + * If set, this flag will prevent the normal {@link android.app.Activity#onUserLeaveHint} * callback from occurring on the current frontmost activity before it is * paused as the newly-started activity is brought to the front. * @@ -1892,12 +1953,39 @@ public class Intent implements Parcelable { * activity does not think the user has acknowledged its notification. */ public static final int FLAG_ACTIVITY_NO_USER_ACTION = 0x00040000; - + /** + * If set in an Intent passed to {@link Context#startActivity Context.startActivity()}, + * this flag will cause the launched activity to be brought to the front of its + * task's history stack if it is already running. + * + *

      For example, consider a task consisting of four activities: A, B, C, D. + * If D calls startActivity() with an Intent that resolves to the component + * of activity B, then B will be brought to the front of the history stack, + * with this resulting order: A, C, D, B. + * + * This flag will be ignored if {@link #FLAG_ACTIVITY_CLEAR_TOP} is also + * specified. + */ + public static final int FLAG_ACTIVITY_REORDER_TO_FRONT = 0X00020000; /** * If set, when sending a broadcast only registered receivers will be * called -- no BroadcastReceiver components will be launched. */ public static final int FLAG_RECEIVER_REGISTERED_ONLY = 0x40000000; + /** + * If set, when sending a broadcast before boot has completed only + * registered receivers will be called -- no BroadcastReceiver components + * will be launched. Sticky intent state will be recorded properly even + * if no receivers wind up being called. If {@link #FLAG_RECEIVER_REGISTERED_ONLY} + * is specified in the broadcast intent, this flag is unnecessary. + * + *

      This flag is only for use by system sevices as a convenience to + * avoid having to implement a more complex mechanism around detection + * of boot completion. + * + * @hide + */ + public static final int FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT = 0x20000000; // --------------------------------------------------------------------- @@ -3865,8 +3953,8 @@ public class Intent implements Parcelable { * FLAG_RECEIVER_* flags are all for use with * {@link Context#sendBroadcast(Intent) Context.sendBroadcast()}. * - *

      See the Application Model - * documentation for important information on how some of these options impact + *

      See the Application Fundamentals: + * Activities and Tasks documentation for important information on how some of these options impact * the behavior of your application. * * @param flags The desired flags. @@ -4141,14 +4229,11 @@ public class Intent implements Parcelable { @Override public boolean equals(Object obj) { - Intent other; - try { - other = ((FilterComparison)obj).mIntent; - } catch (ClassCastException e) { - return false; + if (obj instanceof FilterComparison) { + Intent other = ((FilterComparison)obj).mIntent; + return mIntent.filterEquals(other); } - - return mIntent.filterEquals(other); + return false; } @Override diff --git a/core/java/android/content/SyncManager.java b/core/java/android/content/SyncManager.java index 6bc3774859b0db9d31e9c6ba8f3e6c248d1edde6..96470c3c5756c941e3d5941e5f73d6780e565985 100644 --- a/core/java/android/content/SyncManager.java +++ b/core/java/android/content/SyncManager.java @@ -123,7 +123,7 @@ class SyncManager { private static final String SYNC_WAKE_LOCK = "SyncManagerSyncWakeLock"; private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarmWakeLock"; - + private Context mContext; private ContentResolver mContentResolver; @@ -249,7 +249,7 @@ class SyncManager { mSyncQueue = new SyncQueue(mSyncStorageEngine); mContext = context; - + mSyncThread = new HandlerThread("SyncHandlerThread", Process.THREAD_PRIORITY_BACKGROUND); mSyncThread.start(); mSyncHandler = new SyncHandler(mSyncThread.getLooper()); @@ -489,7 +489,7 @@ class SyncManager { // Require the precise value "yes" to discourage accidental activation. return "yes".equals(SystemProperties.get("ro.config.sync")); } - + /** * Initiate a sync. This can start a sync for all providers * (pass null to url, set onlyTicklable to false), only those @@ -515,7 +515,7 @@ class SyncManager { * syncs of a specific provider. Can be null. Is ignored * if the url is null. * @param delay how many milliseconds in the future to wait before performing this - * sync. -1 means to make this the next sync to perform. + * sync. -1 means to make this the next sync to perform. */ public void scheduleSync(Uri url, Bundle extras, long delay) { boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE); @@ -694,7 +694,7 @@ class SyncManager { class SyncHandlerMessagePayload { public final ActiveSyncContext activeSyncContext; public final SyncResult syncResult; - + SyncHandlerMessagePayload(ActiveSyncContext syncContext, SyncResult syncResult) { this.activeSyncContext = syncContext; this.syncResult = syncResult; @@ -740,7 +740,7 @@ class SyncManager { if (newDelayInMs > maxSyncRetryTimeInSeconds * 1000) { newDelayInMs = maxSyncRetryTimeInSeconds * 1000; } - + SyncOperation rescheduledSyncOperation = new SyncOperation(syncOperation); rescheduledSyncOperation.setDelay(newDelayInMs); scheduleSyncOperation(rescheduledSyncOperation); @@ -786,7 +786,7 @@ class SyncManager { // key than the one we are scheduling. if (!activeIsExpedited && !hasSameKey) { rescheduleImmediately(activeSyncContext.mSyncOperation); - sendSyncFinishedOrCanceledMessage(activeSyncContext, + sendSyncFinishedOrCanceledMessage(activeSyncContext, null /* no result since this is a cancel */); } } @@ -1323,7 +1323,7 @@ class SyncManager { public SyncHandler(Looper looper) { super(looper); } - + public void handleMessage(Message msg) { handleSyncHandlerMessage(msg); } @@ -1462,6 +1462,9 @@ class SyncManager { // start it, otherwise just get out. SyncOperation syncOperation; final Sync.Settings.QueryMap syncSettings = getSyncSettings(); + final ConnectivityManager connManager = (ConnectivityManager) + mContext.getSystemService(Context.CONNECTIVITY_SERVICE); + final boolean backgroundDataSetting = connManager.getBackgroundDataSetting(); synchronized (mSyncQueue) { while (true) { syncOperation = mSyncQueue.head(); @@ -1484,10 +1487,10 @@ class SyncManager { // skip the sync if it isn't a force and the settings are off for this provider final boolean force = syncOperation.extras.getBoolean( ContentResolver.SYNC_EXTRAS_FORCE, false); - if (!force && (!syncSettings.getBackgroundData() + if (!force && (!backgroundDataSetting || !syncSettings.getListenForNetworkTickles() || !syncSettings.getSyncProviderAutomatically( - syncOperation.authority))) { + syncOperation.authority))) { if (isLoggable) { Log.v(TAG, "runStateIdle: sync off, dropping " + syncOperation); } @@ -1669,7 +1672,7 @@ class SyncManager { * @param syncResult the SyncResult from which to read * @return the most "serious" error set in the SyncResult * @throws IllegalStateException if the SyncResult does not indicate any errors. - * If SyncResult.error() is true then it is safe to call this. + * If SyncResult.error() is true then it is safe to call this. */ private int syncResultToErrorNumber(SyncResult syncResult) { if (syncResult.syncAlreadyInProgress) return History.ERROR_SYNC_ALREADY_IN_PROGRESS; @@ -1679,7 +1682,8 @@ class SyncManager { if (syncResult.stats.numConflictDetectedExceptions > 0) return History.ERROR_CONFLICT; if (syncResult.tooManyDeletions) return History.ERROR_TOO_MANY_DELETIONS; if (syncResult.tooManyRetries) return History.ERROR_TOO_MANY_RETRIES; - throw new IllegalStateException("we are not in an error state, " + toString()); + if (syncResult.databaseError) return History.ERROR_INTERNAL; + throw new IllegalStateException("we are not in an error state, " + syncResult); } private void manageSyncNotification() { @@ -1717,7 +1721,7 @@ class SyncManager { if (mSyncNotificationInfo.isActive) { shouldInstall = shouldCancel; } else { - final boolean timeToShowNotification = + final boolean timeToShowNotification = now > mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY; final boolean syncIsForced = syncOperation.extras .getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false); @@ -1769,7 +1773,7 @@ class SyncManager { if (!mDataConnectionIsConnected) return; if (mAccounts == null) return; if (mStorageIsLow) return; - + // Compute the alarm fire time: // - not syncing: time of the next sync operation // - syncing, no notification: time from sync start to notification create time @@ -1850,12 +1854,12 @@ class SyncManager { clickIntent.putExtra("account", account); clickIntent.putExtra("provider", authority); clickIntent.putExtra("numDeletes", numDeletes); - + if (!isActivityAvailable(clickIntent)) { Log.w(TAG, "No activity found to handle too many deletes."); return; } - + final PendingIntent pendingIntent = PendingIntent .getActivity(mContext, 0, clickIntent, PendingIntent.FLAG_CANCEL_CURRENT); @@ -1877,7 +1881,7 @@ class SyncManager { /** * Checks whether an activity exists on the system image for the given intent. - * + * * @param intent The intent for an activity. * @return Whether or not an activity exists. */ @@ -1892,10 +1896,10 @@ class SyncManager { return true; } } - + return false; } - + public long insertStartSyncEvent(SyncOperation syncOperation) { final int source = syncOperation.syncSource; final long now = System.currentTimeMillis(); diff --git a/core/java/android/content/TempProviderSyncAdapter.java b/core/java/android/content/TempProviderSyncAdapter.java index 78510aad987a0ac4420443ad7d307f8438ecadc3..eb3a5da4a5b12e4c300fb6abc38dd39d44c14855 100644 --- a/core/java/android/content/TempProviderSyncAdapter.java +++ b/core/java/android/content/TempProviderSyncAdapter.java @@ -1,11 +1,11 @@ package android.content; -import com.google.android.net.NetStats; - import android.database.SQLException; import android.os.Bundle; import android.os.Debug; +import android.os.NetStat; import android.os.Parcelable; +import android.os.Process; import android.os.SystemProperties; import android.text.TextUtils; import android.util.Config; @@ -177,7 +177,8 @@ public abstract class TempProviderSyncAdapter extends SyncAdapter { private final Bundle mExtras; private final SyncContext mSyncContext; private volatile boolean mIsCanceled = false; - private long[] mNetStats; + private long mInitialTxBytes; + private long mInitialRxBytes; private final SyncResult mResult; SyncThread(SyncContext syncContext, String account, Bundle extras) { @@ -193,15 +194,18 @@ public abstract class TempProviderSyncAdapter extends SyncAdapter { if (mAdapterSyncStarted) onSyncCanceled(); if (mProviderSyncStarted) mProvider.onSyncCanceled(); // We may lose the last few sync events when canceling. Oh well. - long[] newNetStats = NetStats.getStats(); - logSyncDetails(newNetStats[0] - mNetStats[0], newNetStats[1] - mNetStats[1], mResult); + int uid = Process.myUid(); + logSyncDetails(NetStat.getUidTxBytes(uid) - mInitialTxBytes, + NetStat.getUidRxBytes(uid) - mInitialRxBytes, mResult); } @Override public void run() { - android.os.Process.setThreadPriority(android.os.Process.myTid(), - android.os.Process.THREAD_PRIORITY_BACKGROUND); - mNetStats = NetStats.getStats(); + Process.setThreadPriority(Process.myTid(), + Process.THREAD_PRIORITY_BACKGROUND); + int uid = Process.myUid(); + mInitialTxBytes = NetStat.getUidTxBytes(uid); + mInitialRxBytes = NetStat.getUidRxBytes(uid); try { sync(mSyncContext, mAccount, mExtras); } catch (SQLException e) { @@ -210,8 +214,8 @@ public abstract class TempProviderSyncAdapter extends SyncAdapter { } finally { mSyncThread = null; if (!mIsCanceled) { - long[] newNetStats = NetStats.getStats(); - logSyncDetails(newNetStats[0] - mNetStats[0], newNetStats[1] - mNetStats[1], mResult); + logSyncDetails(NetStat.getUidTxBytes(uid) - mInitialTxBytes, + NetStat.getUidRxBytes(uid) - mInitialRxBytes, mResult); mSyncContext.onFinished(mResult); } } diff --git a/core/java/android/content/package.html b/core/java/android/content/package.html index 7b3e8cfae7b1eadc5a0a8057753001b3c58c0f80..dd5360f651b4631ab6d071852dd2bac0f9d711e6 100644 --- a/core/java/android/content/package.html +++ b/core/java/android/content/package.html @@ -50,9 +50,9 @@ an application's resources and transfer data between applications.

      This topic includes a terminology list associated with resources, and a series of examples of using resources in code. For a complete guide on creating and - using resources, see the document on Resources + using resources, see the document on Resources and Internationalization. For a reference on the supported Android resource types, - see Available Resource Types.

      + see Available Resource Types.

      The Android resource system keeps track of all non-code assets associated with an application. You use the {@link android.content.res.Resources Resources} class to access your @@ -175,7 +175,8 @@ download files with new appearances.

      This section gives a few quick examples you can use to make your own resources. For more details on how to define and use resources, see Resources.

      + href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources and + Internationalization.

      Using System Resources

      diff --git a/core/java/android/content/pm/ConfigurationInfo.java b/core/java/android/content/pm/ConfigurationInfo.java index 9115225c4415ea41ffbc21643d1b17ba7f712008..dcc746331b0b89a7ea4aba3882c66ef929c455c5 100755 --- a/core/java/android/content/pm/ConfigurationInfo.java +++ b/core/java/android/content/pm/ConfigurationInfo.java @@ -16,7 +16,6 @@ package android.content.pm; -import android.content.res.Configuration; import android.os.Parcel; import android.os.Parcelable; @@ -60,12 +59,12 @@ public class ConfigurationInfo implements Parcelable { /** * Value for {@link #reqInputFeatures}: if set, indicates that the application - * requires a hard keyboard + * requires a five way navigation device */ public static final int INPUT_FEATURE_FIVE_WAY_NAV = 0x00000002; /** - * Flags associated with the application. Any combination of + * Flags associated with the input features. Any combination of * {@link #INPUT_FEATURE_HARD_KEYBOARD}, * {@link #INPUT_FEATURE_FIVE_WAY_NAV} */ diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl index ea86188d2bf9b021dec895f06ea59822124af8a0..d3f6f3c564c89e68ef0d194c62e7f479565540f6 100644 --- a/core/java/android/content/pm/IPackageManager.aidl +++ b/core/java/android/content/pm/IPackageManager.aidl @@ -255,8 +255,15 @@ interface IPackageManager { * retrieval of information is complete. */ void getPackageSizeInfo(in String packageName, IPackageStatsObserver observer); + + /** + * Get a list of shared libraries that are available on the + * system. + */ + String[] getSystemSharedLibraryNames(); void enterSafeMode(); + boolean isSafeMode(); void systemReady(); boolean hasSystemUidErrors(); } diff --git a/core/java/android/content/pm/PackageInfo.java b/core/java/android/content/pm/PackageInfo.java index 994afc8381ff1effccadaf2f57c251a05152ca56..d9326f211b5ba39d3a454d96f8c401bae07280df 100644 --- a/core/java/android/content/pm/PackageInfo.java +++ b/core/java/android/content/pm/PackageInfo.java @@ -28,6 +28,20 @@ public class PackageInfo implements Parcelable { */ public String versionName; + /** + * The shared user ID name of this package, as specified by the <manifest> + * tag's {@link android.R.styleable#AndroidManifest_sharedUserId sharedUserId} + * attribute. + */ + public String sharedUserId; + + /** + * The shared user ID label of this package, as specified by the <manifest> + * tag's {@link android.R.styleable#AndroidManifest_sharedUserLabel sharedUserLabel} + * attribute. + */ + public int sharedUserLabel; + /** * Information collected from the <application> tag, or null if * there was none. @@ -130,6 +144,8 @@ public class PackageInfo implements Parcelable { dest.writeString(packageName); dest.writeInt(versionCode); dest.writeString(versionName); + dest.writeString(sharedUserId); + dest.writeInt(sharedUserLabel); if (applicationInfo != null) { dest.writeInt(1); applicationInfo.writeToParcel(dest, parcelableFlags); @@ -163,6 +179,8 @@ public class PackageInfo implements Parcelable { packageName = source.readString(); versionCode = source.readInt(); versionName = source.readString(); + sharedUserId = source.readString(); + sharedUserLabel = source.readInt(); int hasApp = source.readInt(); if (hasApp != 0) { applicationInfo = ApplicationInfo.CREATOR.createFromParcel(source); diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java index 4b902e9fe944f121c84e905125c84d64bf06c41c..7287d9cd58e9306732c74de2bebfa01f7540de97 100644 --- a/core/java/android/content/pm/PackageManager.java +++ b/core/java/android/content/pm/PackageManager.java @@ -479,6 +479,26 @@ public abstract class PackageManager { public abstract PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException; + /** + * Return a "good" intent to launch a front-door activity in a package, + * for use for example to implement an "open" button when browsing through + * packages. The current implementation will look first for a main + * activity in the category {@link Intent#CATEGORY_INFO}, next for a + * main activity in the category {@link Intent#CATEGORY_LAUNCHER}, or return + * null if neither are found. + * + *

      Throws {@link NameNotFoundException} if a package with the given + * name can not be found on the system. + * + * @param packageName The name of the package to inspect. + * + * @return Returns either a fully-qualified Intent that can be used to + * launch the main activity in the package, or null if the package does + * not contain such an activity. + */ + public abstract Intent getLaunchIntentForPackage(String packageName) + throws NameNotFoundException; + /** * Return an array of all of the secondary group-ids that have been * assigned to a package. @@ -851,6 +871,16 @@ public abstract class PackageManager { * @see #GET_UNINSTALLED_PACKAGES */ public abstract List getInstalledApplications(int flags); + + /** + * Get a list of shared libraries that are available on the + * system. + * + * @return An array of shared library names that are + * available on the system, or null if none are installed. + * + */ + public abstract String[] getSystemSharedLibraryNames(); /** * Determine the best action to perform for a given Intent. This is how @@ -1608,4 +1638,9 @@ public abstract class PackageManager { * the manifest as found in {@link ComponentInfo}. */ public abstract int getApplicationEnabledSetting(String packageName); + + /** + * Return whether the device has been booted into safe mode. + */ + public abstract boolean isSafeMode(); } diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java index e08f1d154dc2e42507c1037748e4ccc3f9b6dd68..2dcb4830bf48474301b78e3ce20ac10a38ea86e8 100644 --- a/core/java/android/content/pm/PackageParser.java +++ b/core/java/android/content/pm/PackageParser.java @@ -101,6 +101,8 @@ public class PackageParser { pi.packageName = p.packageName; pi.versionCode = p.mVersionCode; pi.versionName = p.mVersionName; + pi.sharedUserId = p.mSharedUserId; + pi.sharedUserLabel = p.mSharedUserLabel; pi.applicationInfo = p.applicationInfo; if ((flags&PackageManager.GET_GIDS) != 0) { pi.gids = gids; @@ -258,8 +260,9 @@ public class PackageParser { boolean assetError = true; try { assmgr = new AssetManager(); - if(assmgr.addAssetPath(mArchiveSourcePath) != 0) { - parser = assmgr.openXmlResourceParser("AndroidManifest.xml"); + int cookie = assmgr.addAssetPath(mArchiveSourcePath); + if(cookie != 0) { + parser = assmgr.openXmlResourceParser(cookie, "AndroidManifest.xml"); assetError = false; } else { Log.w(TAG, "Failed adding asset path:"+mArchiveSourcePath); @@ -585,6 +588,8 @@ public class PackageParser { return null; } pkg.mSharedUserId = str.intern(); + pkg.mSharedUserLabel = sa.getResourceId( + com.android.internal.R.styleable.AndroidManifest_sharedUserLabel, 0); } sa.recycle(); @@ -2045,6 +2050,9 @@ public class PackageParser { // The shared user id that this package wants to use. public String mSharedUserId; + // The shared user label that this package wants to use. + public int mSharedUserLabel; + // Signatures that were read from the package. public Signature mSignatures[]; diff --git a/core/java/android/content/res/AssetFileDescriptor.java b/core/java/android/content/res/AssetFileDescriptor.java index 4a073f75664214a0a3987ed4a95520a5d26e3695..231e3e24a27c8036c736b29fe48ad040f9aadce7 100644 --- a/core/java/android/content/res/AssetFileDescriptor.java +++ b/core/java/android/content/res/AssetFileDescriptor.java @@ -16,9 +16,13 @@ package android.content.res; +import android.os.Parcel; import android.os.ParcelFileDescriptor; +import android.os.Parcelable; import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; /** @@ -26,16 +30,32 @@ import java.io.IOException; * opened FileDescriptor that can be used to read the data, as well as the * offset and length of that entry's data in the file. */ -public class AssetFileDescriptor { +public class AssetFileDescriptor implements Parcelable { + /** + * Length used with {@link #AssetFileDescriptor(ParcelFileDescriptor, long, long)} + * and {@link #getDeclaredLength} when a length has not been declared. This means + * the data extends to the end of the file. + */ + public static final long UNKNOWN_LENGTH = -1; + private final ParcelFileDescriptor mFd; private final long mStartOffset; private final long mLength; /** * Create a new AssetFileDescriptor from the given values. + * @param fd The underlying file descriptor. + * @param startOffset The location within the file that the asset starts. + * This must be 0 if length is UNKNOWN_LENGTH. + * @param length The number of bytes of the asset, or + * {@link #UNKNOWN_LENGTH if it extends to the end of the file. */ public AssetFileDescriptor(ParcelFileDescriptor fd, long startOffset, long length) { + if (length < 0 && startOffset != 0) { + throw new IllegalArgumentException( + "startOffset must be 0 when using UNKNOWN_LENGTH"); + } mFd = fd; mStartOffset = startOffset; mLength = length; @@ -66,9 +86,33 @@ public class AssetFileDescriptor { } /** - * Returns the total number of bytes of this asset entry's data. + * Returns the total number of bytes of this asset entry's data. May be + * {@link #UNKNOWN_LENGTH} if the asset extends to the end of the file. + * If the AssetFileDescriptor was constructed with {@link #UNKNOWN_LENGTH}, + * this will use {@link ParcelFileDescriptor#getStatSize() + * ParcelFileDescriptor.getStatSize()} to find the total size of the file, + * returning that number if found or {@link #UNKNOWN_LENGTH} if it could + * not be determined. + * + * @see #getDeclaredLength() */ public long getLength() { + if (mLength >= 0) { + return mLength; + } + long len = mFd.getStatSize(); + return len >= 0 ? len : UNKNOWN_LENGTH; + } + + /** + * Return the actual number of bytes that were declared when the + * AssetFileDescriptor was constructed. Will be + * {@link #UNKNOWN_LENGTH} if the length was not declared, meaning data + * should be read to the end of the file. + * + * @see #getDeclaredLength() + */ + public long getDeclaredLength() { return mLength; } @@ -78,4 +122,227 @@ public class AssetFileDescriptor { public void close() throws IOException { mFd.close(); } + + /** + * Create and return a new auto-close input stream for this asset. This + * will either return a full asset {@link AutoCloseInputStream}, or + * an underlying {@link ParcelFileDescriptor.AutoCloseInputStream + * ParcelFileDescriptor.AutoCloseInputStream} depending on whether the + * the object represents a complete file or sub-section of a file. You + * should only call this once for a particular asset. + */ + public FileInputStream createInputStream() throws IOException { + if (mLength < 0) { + return new ParcelFileDescriptor.AutoCloseInputStream(mFd); + } + return new AutoCloseInputStream(this); + } + + /** + * Create and return a new auto-close output stream for this asset. This + * will either return a full asset {@link AutoCloseOutputStream}, or + * an underlying {@link ParcelFileDescriptor.AutoCloseOutputStream + * ParcelFileDescriptor.AutoCloseOutputStream} depending on whether the + * the object represents a complete file or sub-section of a file. You + * should only call this once for a particular asset. + */ + public FileOutputStream createOutputStream() throws IOException { + if (mLength < 0) { + return new ParcelFileDescriptor.AutoCloseOutputStream(mFd); + } + return new AutoCloseOutputStream(this); + } + + @Override + public String toString() { + return "{AssetFileDescriptor: " + mFd + + " start=" + mStartOffset + " len=" + mLength + "}"; + } + + /** + * An InputStream you can create on a ParcelFileDescriptor, which will + * take care of calling {@link ParcelFileDescriptor#close + * ParcelFileDescritor.close()} for you when the stream is closed. + */ + public static class AutoCloseInputStream + extends ParcelFileDescriptor.AutoCloseInputStream { + private long mRemaining; + + public AutoCloseInputStream(AssetFileDescriptor fd) throws IOException { + super(fd.getParcelFileDescriptor()); + super.skip(fd.getStartOffset()); + mRemaining = (int)fd.getLength(); + } + + @Override + public int available() throws IOException { + return mRemaining >= 0 + ? (mRemaining < 0x7fffffff ? (int)mRemaining : 0x7fffffff) + : super.available(); + } + + @Override + public int read() throws IOException { + if (mRemaining >= 0) { + if (mRemaining == 0) return -1; + int res = super.read(); + if (res >= 0) mRemaining--; + return res; + } + + return super.read(); + } + + @Override + public int read(byte[] buffer, int offset, int count) throws IOException { + if (mRemaining >= 0) { + if (mRemaining == 0) return -1; + if (count > mRemaining) count = (int)mRemaining; + int res = super.read(buffer, offset, count); + if (res >= 0) mRemaining -= res; + return res; + } + + return super.read(buffer, offset, count); + } + + @Override + public int read(byte[] buffer) throws IOException { + if (mRemaining >= 0) { + if (mRemaining == 0) return -1; + int count = buffer.length; + if (count > mRemaining) count = (int)mRemaining; + int res = super.read(buffer, 0, count); + if (res >= 0) mRemaining -= res; + return res; + } + + return super.read(buffer); + } + + @Override + public long skip(long count) throws IOException { + if (mRemaining >= 0) { + if (mRemaining == 0) return -1; + if (count > mRemaining) count = mRemaining; + long res = super.skip(count); + if (res >= 0) mRemaining -= res; + return res; + } + + // TODO Auto-generated method stub + return super.skip(count); + } + + @Override + public void mark(int readlimit) { + if (mRemaining >= 0) { + // Not supported. + return; + } + super.mark(readlimit); + } + + @Override + public boolean markSupported() { + if (mRemaining >= 0) { + return false; + } + return super.markSupported(); + } + + @Override + public synchronized void reset() throws IOException { + if (mRemaining >= 0) { + // Not supported. + return; + } + super.reset(); + } + } + + /** + * An OutputStream you can create on a ParcelFileDescriptor, which will + * take care of calling {@link ParcelFileDescriptor#close + * ParcelFileDescritor.close()} for you when the stream is closed. + */ + public static class AutoCloseOutputStream + extends ParcelFileDescriptor.AutoCloseOutputStream { + private long mRemaining; + + public AutoCloseOutputStream(AssetFileDescriptor fd) throws IOException { + super(fd.getParcelFileDescriptor()); + if (fd.getParcelFileDescriptor().seekTo(fd.getStartOffset()) < 0) { + throw new IOException("Unable to seek"); + } + mRemaining = (int)fd.getLength(); + } + + @Override + public void write(byte[] buffer, int offset, int count) throws IOException { + if (mRemaining >= 0) { + if (mRemaining == 0) return; + if (count > mRemaining) count = (int)mRemaining; + super.write(buffer, offset, count); + mRemaining -= count; + return; + } + + super.write(buffer, offset, count); + } + + @Override + public void write(byte[] buffer) throws IOException { + if (mRemaining >= 0) { + if (mRemaining == 0) return; + int count = buffer.length; + if (count > mRemaining) count = (int)mRemaining; + super.write(buffer); + mRemaining -= count; + return; + } + + super.write(buffer); + } + + @Override + public void write(int oneByte) throws IOException { + if (mRemaining >= 0) { + if (mRemaining == 0) return; + super.write(oneByte); + mRemaining--; + return; + } + + super.write(oneByte); + } + } + + + /* Parcelable interface */ + public int describeContents() { + return mFd.describeContents(); + } + + public void writeToParcel(Parcel out, int flags) { + mFd.writeToParcel(out, flags); + out.writeLong(mStartOffset); + out.writeLong(mLength); + } + + AssetFileDescriptor(Parcel src) { + mFd = ParcelFileDescriptor.CREATOR.createFromParcel(src); + mStartOffset = src.readLong(); + mLength = src.readLong(); + } + + public static final Parcelable.Creator CREATOR + = new Parcelable.Creator() { + public AssetFileDescriptor createFromParcel(Parcel in) { + return new AssetFileDescriptor(in); + } + public AssetFileDescriptor[] newArray(int size) { + return new AssetFileDescriptor[size]; + } + }; } diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java index fadcb352261ff40185277d4793086aa9309773a5..1c9173694d2bccb668b99d96e89df9ad2d6422c2 100644 --- a/core/java/android/content/res/AssetManager.java +++ b/core/java/android/content/res/AssetManager.java @@ -567,8 +567,8 @@ public final class AssetManager { /** * Add an additional set of assets to the asset manager. This can be - * either a directory or ZIP file. Not for use by applications. A - * zero return value indicates failure. + * either a directory or ZIP file. Not for use by applications. Returns + * the cookie of the added asset, or 0 on failure. * {@hide} */ public native final int addAssetPath(String path); diff --git a/core/java/android/content/res/ColorStateList.java b/core/java/android/content/res/ColorStateList.java index 4b1e67843608c0d9246a662d61c825e3f4fd763a..453a83d30412d263d05c56ce449764bcea9d0f0c 100644 --- a/core/java/android/content/res/ColorStateList.java +++ b/core/java/android/content/res/ColorStateList.java @@ -16,8 +16,6 @@ package android.content.res; -import com.google.android.collect.Lists; - import com.android.internal.util.ArrayUtils; import org.xmlpull.v1.XmlPullParser; @@ -113,7 +111,8 @@ public class ColorStateList implements Parcelable { * Create a ColorStateList from an XML document, given a set of {@link Resources}. */ public static ColorStateList createFromXml(Resources r, XmlPullParser parser) - throws XmlPullParserException, IOException { + throws XmlPullParserException, IOException { + AttributeSet attrs = Xml.asAttributeSet(parser); int type; @@ -125,19 +124,16 @@ public class ColorStateList implements Parcelable { throw new XmlPullParserException("No start tag found"); } - final ColorStateList colorStateList = createFromXmlInner(r, parser, attrs); - - return colorStateList; + return createFromXmlInner(r, parser, attrs); } /* Create from inside an XML document. Called on a parser positioned at * a tag in an XML document, tries to create a ColorStateList from that tag. * Returns null if the tag is not a valid ColorStateList. */ - private static ColorStateList createFromXmlInner(Resources r, - XmlPullParser parser, - AttributeSet attrs) - throws XmlPullParserException, IOException { + private static ColorStateList createFromXmlInner(Resources r, XmlPullParser parser, + AttributeSet attrs) throws XmlPullParserException, IOException { + ColorStateList colorStateList; final String name = parser.getName(); @@ -146,8 +142,7 @@ public class ColorStateList implements Parcelable { colorStateList = new ColorStateList(); } else { throw new XmlPullParserException( - parser.getPositionDescription() + ": invalid drawable tag " - + name); + parser.getPositionDescription() + ": invalid drawable tag " + name); } colorStateList.inflate(r, parser, attrs); @@ -304,7 +299,11 @@ public class ColorStateList implements Parcelable { } public void writeToParcel(Parcel dest, int flags) { - dest.writeArray(mStateSpecs); + final int N = mStateSpecs.length; + dest.writeInt(N); + for (int i=0; i mPreloadedDrawables = new SparseArray(); + private static final SparseArray mPreloadedColorStateLists + = new SparseArray(); private static boolean mPreloaded; /*package*/ final TypedValue mTmpValue = new TypedValue(); @@ -79,7 +81,7 @@ public class Resources { private final Configuration mConfiguration = new Configuration(); /*package*/ final DisplayMetrics mMetrics = new DisplayMetrics(); PluralRules mPluralRule; - + /** * This exception is thrown by the resource APIs when a requested resource * can not be found. @@ -91,7 +93,7 @@ public class Resources { public NotFoundException(String name) { super(name); } - }; + } /** * Create a new Resources object on top of an existing set of assets in an @@ -399,7 +401,6 @@ public class Resources { * * @throws NotFoundException Throws NotFoundException if the given ID does not exist. * - * @return CharSequence The string data associated with the resource, plus * @see #getDimensionPixelOffset * @see #getDimensionPixelSize */ @@ -432,7 +433,6 @@ public class Resources { * * @throws NotFoundException Throws NotFoundException if the given ID does not exist. * - * @return CharSequence The string data associated with the resource, plus * @see #getDimension * @see #getDimensionPixelSize */ @@ -467,7 +467,6 @@ public class Resources { * * @throws NotFoundException Throws NotFoundException if the given ID does not exist. * - * @return CharSequence The string data associated with the resource, plus * @see #getDimension * @see #getDimensionPixelOffset */ @@ -485,6 +484,36 @@ public class Resources { } } + /** + * Retrieve a fractional unit for a particular resource ID. + * + * @param id The desired resource identifier, as generated by the aapt + * tool. This integer encodes the package, type, and resource + * entry. The value 0 is an invalid identifier. + * @param base The base value of this fraction. In other words, a + * standard fraction is multiplied by this value. + * @param pbase The parent base value of this fraction. In other + * words, a parent fraction (nn%p) is multiplied by this + * value. + * + * @return Attribute fractional value multiplied by the appropriate + * base value. + * + * @throws NotFoundException Throws NotFoundException if the given ID does not exist. + */ + public float getFraction(int id, int base, int pbase) { + synchronized (mTmpValue) { + TypedValue value = mTmpValue; + getValue(id, value, true); + if (value.type == TypedValue.TYPE_FRACTION) { + return TypedValue.complexToFraction(value.data, base, pbase); + } + throw new NotFoundException( + "Resource ID #0x" + Integer.toHexString(id) + " type #0x" + + Integer.toHexString(value.type) + " is not valid"); + } + } + /** * Return a drawable object associated with a particular resource ID. * Various types of objects will be returned depending on the underlying @@ -721,22 +750,36 @@ public class Resources { */ public InputStream openRawResource(int id) throws NotFoundException { synchronized (mTmpValue) { - TypedValue value = mTmpValue; - getValue(id, value, true); + return openRawResource(id, mTmpValue); + } + } - try { - return mAssets.openNonAsset( - value.assetCookie, value.string.toString(), - AssetManager.ACCESS_STREAMING); - } catch (Exception e) { - NotFoundException rnf = new NotFoundException( - "File " + value.string.toString() - + " from drawable resource ID #0x" - + Integer.toHexString(id)); - rnf.initCause(e); - throw rnf; - } + /** + * Open a data stream for reading a raw resource. This can only be used + * with resources whose value is the name of an asset files -- that is, it can be + * used to open drawable, sound, and raw resources; it will fail on string + * and color resources. + * + * @param id The resource identifier to open, as generated by the appt tool. + * @param value The TypedValue object to hold the resource information. + * + * @return InputStream Access to the resource data. + * + * @throws NotFoundException Throws NotFoundException if the given ID does not exist. + * + * @hide Pending API council approval + */ + public InputStream openRawResource(int id, TypedValue value) throws NotFoundException { + getValue(id, value, true); + try { + return mAssets.openNonAsset(value.assetCookie, value.string.toString(), + AssetManager.ACCESS_STREAMING); + } catch (Exception e) { + NotFoundException rnf = new NotFoundException("File " + value.string.toString() + + " from drawable resource ID #0x" + Integer.toHexString(id)); + rnf.initCause(e); + throw rnf; } } @@ -1189,7 +1232,9 @@ public class Resources { width = mMetrics.widthPixels; height = mMetrics.heightPixels; } else { + //noinspection SuspiciousNameCombination width = mMetrics.heightPixels; + //noinspection SuspiciousNameCombination height = mMetrics.widthPixels; } int keyboardHidden = mConfiguration.keyboardHidden; @@ -1302,6 +1347,7 @@ public class Resources { try { return Integer.parseInt(name); } catch (Exception e) { + // Ignore } return mAssets.getResourceIdentifier(name, defType, defPackage); } @@ -1535,21 +1581,18 @@ public class Resources { /*package*/ Drawable loadDrawable(TypedValue value, int id) throws NotFoundException { - if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT - && value.type <= TypedValue.TYPE_LAST_COLOR_INT) { - // Should we be caching these? If we use constant colors much - // at all, most likely... - //System.out.println("Creating drawable for color: #" + - // Integer.toHexString(value.data)); - Drawable dr = new ColorDrawable(value.data); - dr.setChangingConfigurations(value.changingConfigurations); - return dr; + + if (TRACE_FOR_PRELOAD) { + // Log only framework resources + if ((id >>> 24) == 0x1) { + final String name = getResourceName(id); + if (name != null) android.util.Log.d("PreloadDrawable", name); + } } - final int key = (value.assetCookie<<24)|value.data; + final int key = (value.assetCookie << 24) | value.data; Drawable dr = getCachedDrawable(key); - //System.out.println("Cached drawable @ #" + - // Integer.toHexString(key.intValue()) + ": " + dr); + if (dr != null) { return dr; } @@ -1557,46 +1600,52 @@ public class Resources { Drawable.ConstantState cs = mPreloadedDrawables.get(key); if (cs != null) { dr = cs.newDrawable(); - } else { - if (value.string == null) { - throw new NotFoundException( - "Resource is not a Drawable (color or path): " + value); + if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && + value.type <= TypedValue.TYPE_LAST_COLOR_INT) { + dr = new ColorDrawable(value.data); } - - String file = value.string.toString(); - - if (DEBUG_LOAD) Log.v(TAG, "Loading drawable for cookie " - + value.assetCookie + ": " + file); - - if (file.endsWith(".xml")) { - try { - XmlResourceParser rp = loadXmlResourceParser( - file, id, value.assetCookie, "drawable"); - dr = Drawable.createFromXml(this, rp); - rp.close(); - } catch (Exception e) { - NotFoundException rnf = new NotFoundException( - "File " + file + " from drawable resource ID #0x" - + Integer.toHexString(id)); - rnf.initCause(e); - throw rnf; + + if (dr == null) { + if (value.string == null) { + throw new NotFoundException( + "Resource is not a Drawable (color or path): " + value); } - - } else { - try { - InputStream is = mAssets.openNonAsset( - value.assetCookie, file, AssetManager.ACCESS_BUFFER); - // System.out.println("Opened file " + file + ": " + is); - dr = Drawable.createFromStream(is, file); - is.close(); - // System.out.println("Created stream: " + dr); - } catch (Exception e) { - NotFoundException rnf = new NotFoundException( - "File " + file + " from drawable resource ID #0x" - + Integer.toHexString(id)); - rnf.initCause(e); - throw rnf; + + String file = value.string.toString(); + + if (DEBUG_LOAD) Log.v(TAG, "Loading drawable for cookie " + + value.assetCookie + ": " + file); + + if (file.endsWith(".xml")) { + try { + XmlResourceParser rp = loadXmlResourceParser( + file, id, value.assetCookie, "drawable"); + dr = Drawable.createFromXml(this, rp); + rp.close(); + } catch (Exception e) { + NotFoundException rnf = new NotFoundException( + "File " + file + " from drawable resource ID #0x" + + Integer.toHexString(id)); + rnf.initCause(e); + throw rnf; + } + + } else { + try { + InputStream is = mAssets.openNonAsset( + value.assetCookie, file, AssetManager.ACCESS_BUFFER); + // System.out.println("Opened file " + file + ": " + is); + dr = Drawable.createFromResourceStream(this, value, is, file); + is.close(); + // System.out.println("Created stream: " + dr); + } catch (Exception e) { + NotFoundException rnf = new NotFoundException( + "File " + file + " from drawable resource ID #0x" + + Integer.toHexString(id)); + rnf.initCause(e); + throw rnf; + } } } } @@ -1607,13 +1656,13 @@ public class Resources { if (cs != null) { if (mPreloading) { mPreloadedDrawables.put(key, cs); - } - synchronized (mTmpValue) { - //Log.i(TAG, "Saving cached drawable @ #" + - // Integer.toHexString(key.intValue()) - // + " in " + this + ": " + cs); - mDrawableCache.put( - key, new WeakReference(cs)); + } else { + synchronized (mTmpValue) { + //Log.i(TAG, "Saving cached drawable @ #" + + // Integer.toHexString(key.intValue()) + // + " in " + this + ": " + cs); + mDrawableCache.put(key, new WeakReference(cs)); + } } } } @@ -1621,7 +1670,7 @@ public class Resources { return dr; } - private final Drawable getCachedDrawable(int key) { + private Drawable getCachedDrawable(int key) { synchronized (mTmpValue) { WeakReference wr = mDrawableCache.get(key); if (wr != null) { // we have the key @@ -1642,13 +1691,40 @@ public class Resources { /*package*/ ColorStateList loadColorStateList(TypedValue value, int id) throws NotFoundException { - if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT - && value.type <= TypedValue.TYPE_LAST_COLOR_INT) { - return ColorStateList.valueOf(value.data); + if (TRACE_FOR_PRELOAD) { + // Log only framework resources + if ((id >>> 24) == 0x1) { + final String name = getResourceName(id); + if (name != null) android.util.Log.d("PreloadColorStateList", name); + } } - final int key = (value.assetCookie<<24)|value.data; - ColorStateList csl = getCachedColorStateList(key); + final int key = (value.assetCookie << 24) | value.data; + + ColorStateList csl; + + if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && + value.type <= TypedValue.TYPE_LAST_COLOR_INT) { + + csl = mPreloadedColorStateLists.get(key); + if (csl != null) { + return csl; + } + + csl = ColorStateList.valueOf(value.data); + if (mPreloading) { + mPreloadedColorStateLists.put(key, csl); + } + + return csl; + } + + csl = getCachedColorStateList(key); + if (csl != null) { + return csl; + } + + csl = mPreloadedColorStateLists.get(key); if (csl != null) { return csl; } @@ -1680,12 +1756,16 @@ public class Resources { } if (csl != null) { - synchronized (mTmpValue) { - //Log.i(TAG, "Saving cached color state list @ #" + - // Integer.toHexString(key.intValue()) - // + " in " + this + ": " + csl); - mColorStateListCache.put( - key, new WeakReference(csl)); + if (mPreloading) { + mPreloadedColorStateLists.put(key, csl); + } else { + synchronized (mTmpValue) { + //Log.i(TAG, "Saving cached color state list @ #" + + // Integer.toHexString(key.intValue()) + // + " in " + this + ": " + csl); + mColorStateListCache.put( + key, new WeakReference(csl)); + } } } diff --git a/core/java/android/content/res/StringBlock.java b/core/java/android/content/res/StringBlock.java index 3df770889d66fbd94022bd3980b3daebc0669422..e684cb8018df9bc1df77d741394496c388e8c539 100644 --- a/core/java/android/content/res/StringBlock.java +++ b/core/java/android/content/res/StringBlock.java @@ -141,6 +141,8 @@ final class StringBlock { int type = style[i]; if (localLOGV) Log.v(TAG, "Applying style span id=" + type + ", start=" + style[i+1] + ", end=" + style[i+2]); + + if (type == ids.boldId) { buffer.setSpan(new StyleSpan(Typeface.BOLD), style[i+1], style[i+2]+1, @@ -178,9 +180,8 @@ final class StringBlock { style[i+1], style[i+2]+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (type == ids.listItemId) { - buffer.setSpan(new BulletSpan(10), - style[i+1], style[i+2]+1, - Spannable.SPAN_PARAGRAPH); + addParagraphSpan(buffer, new BulletSpan(10), + style[i+1], style[i+2]+1); } else if (type == ids.marqueeId) { buffer.setSpan(TextUtils.TruncateAt.MARQUEE, style[i+1], style[i+2]+1, @@ -194,9 +195,8 @@ final class StringBlock { sub = subtag(tag, ";height="); if (sub != null) { int size = Integer.parseInt(sub); - buffer.setSpan(new Height(size), - style[i+1], style[i+2]+1, - Spannable.SPAN_PARAGRAPH); + addParagraphSpan(buffer, new Height(size), + style[i+1], style[i+2]+1); } sub = subtag(tag, ";size="); @@ -231,6 +231,28 @@ final class StringBlock { style[i+1], style[i+2]+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } + } else if (tag.startsWith("annotation;")) { + int len = tag.length(); + int next; + + for (int t = tag.indexOf(';'); t < len; t = next) { + int eq = tag.indexOf('=', t); + if (eq < 0) { + break; + } + + next = tag.indexOf(';', eq); + if (next < 0) { + next = len; + } + + String key = tag.substring(t + 1, eq); + String value = tag.substring(eq + 1, next); + + buffer.setSpan(new Annotation(key, value), + style[i+1], style[i+2]+1, + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } } } @@ -239,6 +261,34 @@ final class StringBlock { return new SpannedString(buffer); } + /** + * If a translator has messed up the edges of paragraph-level markup, + * fix it to actually cover the entire paragraph that it is attached to + * instead of just whatever range they put it on. + */ + private static void addParagraphSpan(Spannable buffer, Object what, + int start, int end) { + int len = buffer.length(); + + if (start != 0 && start != len && buffer.charAt(start - 1) != '\n') { + for (start--; start > 0; start--) { + if (buffer.charAt(start - 1) == '\n') { + break; + } + } + } + + if (end != 0 && end != len && buffer.charAt(end - 1) != '\n') { + for (end++; end < len; end++) { + if (buffer.charAt(end - 1) == '\n') { + break; + } + } + } + + buffer.setSpan(what, start, end, Spannable.SPAN_PARAGRAPH); + } + private static String subtag(String full, String attribute) { int start = full.indexOf(attribute); if (start < 0) { diff --git a/core/java/android/content/res/TypedArray.java b/core/java/android/content/res/TypedArray.java index 82a57dd1b0adfd3eff7643a32f45945776960276..3a32c0312202532c32bb79c0801121c4fc09b70c 100644 --- a/core/java/android/content/res/TypedArray.java +++ b/core/java/android/content/res/TypedArray.java @@ -438,6 +438,34 @@ public class TypedArray { throw new RuntimeException(getPositionDescription() + ": You must supply a " + name + " attribute."); } + + /** + * Special version of {@link #getDimensionPixelSize} for retrieving + * {@link android.view.ViewGroup}'s layout_width and layout_height + * attributes. This is only here for performance reasons; applications + * should use {@link #getDimensionPixelSize}. + * + * @param index Index of the attribute to retrieve. + * @param defValue The default value to return if this attribute is not + * default or contains the wrong type of data. + * + * @return Attribute dimension value multiplied by the appropriate + * metric and truncated to integer pixels. + */ + public int getLayoutDimension(int index, int defValue) { + index *= AssetManager.STYLE_NUM_ENTRIES; + final int[] data = mData; + final int type = data[index+AssetManager.STYLE_TYPE]; + if (type >= TypedValue.TYPE_FIRST_INT + && type <= TypedValue.TYPE_LAST_INT) { + return data[index+AssetManager.STYLE_DATA]; + } else if (type == TypedValue.TYPE_DIMENSION) { + return TypedValue.complexToDimensionPixelSize( + data[index+AssetManager.STYLE_DATA], mResources.mMetrics); + } + + return defValue; + } /** * Retrieve a fractional unit attribute at index. diff --git a/core/java/android/database/DatabaseUtils.java b/core/java/android/database/DatabaseUtils.java index 2ff72947879f8af9c6d2fcfbda5393095958f26f..10f3806d0ec9ddf81d62ecd7444102915ff0afbc 100644 --- a/core/java/android/database/DatabaseUtils.java +++ b/core/java/android/database/DatabaseUtils.java @@ -84,6 +84,7 @@ public class DatabaseUtils { code = 9; } else { reply.writeException(e); + Log.e(TAG, "Writing exception to parcel", e); return; } reply.writeInt(code); diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java index fa062c86e00e319bbce70a5a71047cbdd9901623..2af080ae19bad84a0d930cd4c987d6c59e529db2 100644 --- a/core/java/android/database/sqlite/SQLiteDatabase.java +++ b/core/java/android/database/sqlite/SQLiteDatabase.java @@ -25,6 +25,7 @@ import android.os.SystemClock; import android.text.TextUtils; import android.util.Config; import android.util.Log; +import android.util.EventLog; import java.io.File; import java.util.HashMap; @@ -51,7 +52,8 @@ import java.util.concurrent.locks.ReentrantLock; * is the Unicode Collation Algorithm and not tailored to the current locale. */ public class SQLiteDatabase extends SQLiteClosable { - private final static String TAG = "Database"; + private static final String TAG = "Database"; + private static final int DB_OPERATION_EVENT = 52000; /** * Algorithms used in ON CONFLICT clause @@ -207,6 +209,11 @@ public class SQLiteDatabase extends SQLiteClosable { private WeakHashMap mPrograms; private final RuntimeException mLeakedException; + + // package visible, since callers will access directly to minimize overhead in the case + // that logging is not enabled. + /* package */ final boolean mLogStats; + /** * @param closable */ @@ -436,7 +443,14 @@ public class SQLiteDatabase extends SQLiteClosable { if (mTransactionIsSuccessful) { execSQL("COMMIT;"); } else { - execSQL("ROLLBACK;"); + try { + execSQL("ROLLBACK;"); + } catch (SQLException e) { + if (Config.LOGD) { + Log.d(TAG, "exception during rollback, maybe the DB previously " + + "performed an auto-rollback"); + } + } } } finally { unlockForced(); @@ -764,9 +778,9 @@ public class SQLiteDatabase extends SQLiteClosable { } /** - * Returns the maximum size the database may grow to. + * Returns the current database page size, in bytes. * - * @return the new maximum database size + * @return the database page size, in bytes */ public long getPageSize() { SQLiteStatement prog = null; @@ -1472,10 +1486,8 @@ public class SQLiteDatabase extends SQLiteClosable { * @throws SQLException If the SQL string is invalid for some reason */ public void execSQL(String sql) throws SQLException { - long timeStart = 0; - if (Config.LOGV) { - timeStart = System.currentTimeMillis(); - } + boolean logStats = mLogStats; + long timeStart = logStats ? SystemClock.elapsedRealtime() : 0; lock(); try { native_execSQL(sql); @@ -1485,9 +1497,8 @@ public class SQLiteDatabase extends SQLiteClosable { } finally { unlock(); } - if (Config.LOGV) { - long timeEnd = System.currentTimeMillis(); - Log.v(TAG, "Executed (" + (timeEnd - timeStart) + " ms):" + sql); + if (logStats) { + logTimeStat(false /* not a read */, timeStart, SystemClock.elapsedRealtime()); } } @@ -1504,10 +1515,9 @@ public class SQLiteDatabase extends SQLiteClosable { if (bindArgs == null) { throw new IllegalArgumentException("Empty bindArgs"); } - long timeStart = 0; - if (Config.LOGV) { - timeStart = System.currentTimeMillis(); - } + + boolean logStats = mLogStats; + long timeStart = logStats ? SystemClock.elapsedRealtime() : 0; lock(); SQLiteStatement statement = null; try { @@ -1528,9 +1538,8 @@ public class SQLiteDatabase extends SQLiteClosable { } unlock(); } - if (Config.LOGV) { - long timeEnd = System.currentTimeMillis(); - Log.v(TAG, "Executed (" + (timeEnd - timeStart) + " ms):" + sql); + if (logStats) { + logTimeStat(false /* not a read */, timeStart, SystemClock.elapsedRealtime()); } } @@ -1550,7 +1559,7 @@ public class SQLiteDatabase extends SQLiteClosable { } /** - * Private constructor. See {@link createDatabase} and {@link openDatabase}. + * Private constructor. See {@link #create} and {@link #openDatabase}. * * @param path The full path to the database * @param factory The factory to use when creating cursors, may be NULL. @@ -1563,6 +1572,8 @@ public class SQLiteDatabase extends SQLiteClosable { } mFlags = flags; mPath = path; + mLogStats = "1".equals(android.os.SystemProperties.get("db.logstats")); + mLeakedException = new IllegalStateException(path + " SQLiteDatabase created and never closed"); mFactory = factory; @@ -1605,6 +1616,10 @@ public class SQLiteDatabase extends SQLiteClosable { return mPath; } + /* package */ void logTimeStat(boolean read, long begin, long end) { + EventLog.writeEvent(DB_OPERATION_EVENT, mPath, read ? 0 : 1, end - begin); + } + /** * Sets the locale for this database. Does nothing if this database has * the NO_LOCALIZED_COLLATORS flag set or was opened read only. @@ -1629,7 +1644,7 @@ public class SQLiteDatabase extends SQLiteClosable { private native void dbopen(String path, int flags); /** - * Native call to execute a raw SQL statement. {@link mLock} must be held + * Native call to execute a raw SQL statement. {@link #lock} must be held * when calling this method. * * @param sql The raw SQL string @@ -1638,7 +1653,7 @@ public class SQLiteDatabase extends SQLiteClosable { /* package */ native void native_execSQL(String sql) throws SQLException; /** - * Native call to set the locale. {@link mLock} must be held when calling + * Native call to set the locale. {@link #lock} must be held when calling * this method. * @throws SQLException */ diff --git a/core/java/android/database/sqlite/SQLiteOpenHelper.java b/core/java/android/database/sqlite/SQLiteOpenHelper.java index 35bf6456ed97ccb06161a0e346d8382ca1fa3083..52aac3a822b3ff30de3d422ffdff0095a762ee30 100644 --- a/core/java/android/database/sqlite/SQLiteOpenHelper.java +++ b/core/java/android/database/sqlite/SQLiteOpenHelper.java @@ -26,6 +26,8 @@ import android.util.Log; * optionally {@link #onOpen}, and this class takes care of opening the database * if it exists, creating it if it does not, and upgrading it as necessary. * Transactions are used to make sure the database is always in a sensible state. + *

      For an example, see the NotePadProvider class in the NotePad sample application, + * in the samples/ directory of the SDK.

      */ public abstract class SQLiteOpenHelper { private static final String TAG = SQLiteOpenHelper.class.getSimpleName(); diff --git a/core/java/android/database/sqlite/SQLiteProgram.java b/core/java/android/database/sqlite/SQLiteProgram.java index f89c87d9baa1c3c787279cead9d3876d495dc0d4..9e8545267cbeaa008fb1b7b1756d80d90792e889 100644 --- a/core/java/android/database/sqlite/SQLiteProgram.java +++ b/core/java/android/database/sqlite/SQLiteProgram.java @@ -22,7 +22,7 @@ import android.util.Log; * A base class for compiled SQLite programs. */ public abstract class SQLiteProgram extends SQLiteClosable { - static final String TAG = "SQLiteProgram"; + private static final String TAG = "SQLiteProgram"; /** The database this program is compiled against. */ protected SQLiteDatabase mDatabase; diff --git a/core/java/android/database/sqlite/SQLiteQuery.java b/core/java/android/database/sqlite/SQLiteQuery.java index 22c53abca37e23eb20552f6ffd8afaf533832bd2..1386a0d15e126dc039b666713b60eed9c401a187 100644 --- a/core/java/android/database/sqlite/SQLiteQuery.java +++ b/core/java/android/database/sqlite/SQLiteQuery.java @@ -17,13 +17,15 @@ package android.database.sqlite; import android.database.CursorWindow; +import android.os.SystemClock; +import android.util.Log; /** * A SQLite program that represents a query that reads the resulting rows into a CursorWindow. * This class is used by SQLiteCursor and isn't useful itself. */ public class SQLiteQuery extends SQLiteProgram { - //private static final String TAG = "Cursor"; + private static final String TAG = "Cursor"; /** The index of the unbound OFFSET parameter */ private int mOffsetIndex; @@ -55,12 +57,14 @@ public class SQLiteQuery extends SQLiteProgram { * Reads rows into a buffer. This method acquires the database lock. * * @param window The window to fill into - * @param startPos The position to start reading rows from * @return number of total rows in the query */ /* package */ int fillWindow(CursorWindow window, int maxRead, int lastPos) { mDatabase.lock(); + + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; try { acquireReference(); try { @@ -68,8 +72,18 @@ public class SQLiteQuery extends SQLiteProgram { // if the start pos is not equal to 0, then most likely window is // too small for the data set, loading by another thread // is not safe in this situation. the native code will ignore maxRead - return native_fill_window(window, window.getStartPosition(), mOffsetIndex, + int numRows = native_fill_window(window, window.getStartPosition(), mOffsetIndex, maxRead, lastPos); + + // Logging + if (SQLiteDebug.DEBUG_SQL_STATEMENTS) { + Log.d(TAG, "fillWindow(): " + mQuery); + } + if (logStats) { + mDatabase.logTimeStat(true /* read */, startTime, + SystemClock.elapsedRealtime()); + } + return numRows; } catch (IllegalStateException e){ // simply ignore it return 0; diff --git a/core/java/android/database/sqlite/SQLiteStatement.java b/core/java/android/database/sqlite/SQLiteStatement.java index bf9361dccf8915e6ead43bfd9372d97ebad481ea..5889ad90aaad72240d238b6e2720c0dc1b9d8f84 100644 --- a/core/java/android/database/sqlite/SQLiteStatement.java +++ b/core/java/android/database/sqlite/SQLiteStatement.java @@ -16,6 +16,9 @@ package android.database.sqlite; +import android.os.SystemClock; +import android.util.Log; + /** * A pre-compiled statement against a {@link SQLiteDatabase} that can be reused. * The statement cannot return multiple rows, but 1x1 result sets are allowed. @@ -24,6 +27,10 @@ package android.database.sqlite; */ public class SQLiteStatement extends SQLiteProgram { + private static final String TAG = "SQLiteStatement"; + + private final String mSql; + /** * Don't use SQLiteStatement constructor directly, please use * {@link SQLiteDatabase#compileStatement(String)} @@ -32,6 +39,11 @@ public class SQLiteStatement extends SQLiteProgram */ /* package */ SQLiteStatement(SQLiteDatabase db, String sql) { super(db, sql); + if (SQLiteDebug.DEBUG_SQL_STATEMENTS) { + mSql = sql; + } else { + mSql = null; + } } /** @@ -43,10 +55,19 @@ public class SQLiteStatement extends SQLiteProgram */ public void execute() { mDatabase.lock(); + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; + acquireReference(); try { + if (SQLiteDebug.DEBUG_SQL_STATEMENTS) { + Log.v(TAG, "execute() for [" + mSql + "]"); + } native_execute(); - } finally { + if (logStats) { + mDatabase.logTimeStat(false /* write */, startTime, SystemClock.elapsedRealtime()); + } + } finally { releaseReference(); mDatabase.unlock(); } @@ -64,9 +85,18 @@ public class SQLiteStatement extends SQLiteProgram */ public long executeInsert() { mDatabase.lock(); + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; + acquireReference(); try { + if (SQLiteDebug.DEBUG_SQL_STATEMENTS) { + Log.v(TAG, "executeInsert() for [" + mSql + "]"); + } native_execute(); + if (logStats) { + mDatabase.logTimeStat(false /* write */, startTime, SystemClock.elapsedRealtime()); + } return mDatabase.lastInsertRow(); } finally { releaseReference(); @@ -84,9 +114,19 @@ public class SQLiteStatement extends SQLiteProgram */ public long simpleQueryForLong() { mDatabase.lock(); + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; + acquireReference(); try { - return native_1x1_long(); + if (SQLiteDebug.DEBUG_SQL_STATEMENTS) { + Log.v(TAG, "simpleQueryForLong() for [" + mSql + "]"); + } + long retValue = native_1x1_long(); + if (logStats) { + mDatabase.logTimeStat(false /* write */, startTime, SystemClock.elapsedRealtime()); + } + return retValue; } finally { releaseReference(); mDatabase.unlock(); @@ -103,9 +143,19 @@ public class SQLiteStatement extends SQLiteProgram */ public String simpleQueryForString() { mDatabase.lock(); + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; + acquireReference(); try { - return native_1x1_string(); + if (SQLiteDebug.DEBUG_SQL_STATEMENTS) { + Log.v(TAG, "simpleQueryForString() for [" + mSql + "]"); + } + String retValue = native_1x1_string(); + if (logStats) { + mDatabase.logTimeStat(false /* write */, startTime, SystemClock.elapsedRealtime()); + } + return retValue; } finally { releaseReference(); mDatabase.unlock(); diff --git a/core/java/android/database/sqlite/package.html b/core/java/android/database/sqlite/package.html index c03a8dc02830fdd1deece45fd2eeb53c046e0d07..ff0f9f58f35718a1ca0ea8535d0d19f4e11c3a5a 100644 --- a/core/java/android/database/sqlite/package.html +++ b/core/java/android/database/sqlite/package.html @@ -6,7 +6,7 @@ classes that an application would use to manage its own private database. Applications use these classes to maange private databases. If creating a content provider, you will probably have to use these classes to create and manage your own database to store content. See Storing, Retrieving and Exposing Data to learn +href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers to learn the conventions for implementing a content provider. See the NotePadProvider class in the NotePad sample application in the SDK for an example of a content provider. Android ships with SQLite version 3.4.0 diff --git a/core/java/android/emoji/EmojiFactory.java b/core/java/android/emoji/EmojiFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..389bd07d6b7355e8e853857cb8e589a00ee9b2b7 --- /dev/null +++ b/core/java/android/emoji/EmojiFactory.java @@ -0,0 +1,273 @@ +/* + * 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. + */ + +package android.emoji; + +import android.graphics.Bitmap; + +import java.lang.ref.WeakReference; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A class for the factories which produce Emoji (pictgram) images. + * This is intended to be used by IME, Email app, etc. + * There's no plan to make this public for now. + * @hide + */ +public final class EmojiFactory { + // private static final String LOG_TAG = "EmojiFactory"; + + private int sCacheSize = 100; + + // HashMap for caching Bitmap object. In order not to make an cache object + // blow up, we use LinkedHashMap with size limit. + private class CustomLinkedHashMap extends LinkedHashMap { + public CustomLinkedHashMap() { + // These magic numbers are gotten from the source code of + // LinkedHashMap.java and HashMap.java. + super(16, 0.75f, true); + } + + /* + * If size() becomes more than sCacheSize, least recently used cache + * is erased. + * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry) + */ + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > sCacheSize; + } + } + + // A pointer to native EmojiFactory object. + private int mNativeEmojiFactory; + private String mName; + // Cache. + private Map> mCache; + + /** + * @noinspection UnusedDeclaration + */ + /* + * Private constructor that must received an already allocated native + * EmojiFactory int (pointer). + * + * This can be called from JNI code. + */ + private EmojiFactory(int nativeEmojiFactory, String name) { + mNativeEmojiFactory = nativeEmojiFactory; + mName = name; + mCache = new CustomLinkedHashMap>(); + } + + @Override + protected void finalize() throws Throwable { + try { + nativeDestructor(mNativeEmojiFactory); + } finally { + super.finalize(); + } + } + + public String name() { + return mName; + } + + /** + * Returns Bitmap object corresponding to the AndroidPua. + * + * Note that each Bitmap is cached by this class, which means that, if you modify a + * Bitmap object (using setPos() method), all same emoji Bitmap will be modified. + * If it is unacceptable, please copy the object before modifying it. + * + * @param pua A unicode codepoint. + * @return Bitmap object when this factory knows the Bitmap relevant to the codepoint. + * Otherwise null is returned. + */ + public synchronized Bitmap getBitmapFromAndroidPua(int pua) { + WeakReference cache = mCache.get(pua); + if (cache == null) { + Bitmap ret = nativeGetBitmapFromAndroidPua(mNativeEmojiFactory, pua); + // There is no need to cache returned null, since in most cases it means there + // is no map from the AndroidPua to a specific image. In other words, it usually does + // not include the cost of creating Bitmap object. + if (ret != null) { + mCache.put(pua, new WeakReference(ret)); + } + return ret; + } else { + Bitmap tmp = cache.get(); + if (tmp == null) { + Bitmap ret = nativeGetBitmapFromAndroidPua(mNativeEmojiFactory, pua); + mCache.put(pua, new WeakReference(ret)); + return ret; + } else { + return tmp; + } + } + } + + /** + * Returns Bitmap object corresponding to the vendor specified sjis. + * + * See comments in getBitmapFromAndroidPua(). + * + * @param sjis sjis code specific to each career(vendor) + * @return Bitmap object when this factory knows the Bitmap relevant to the code. Otherwise + * null is returned. + */ + public synchronized Bitmap getBitmapFromVendorSpecificSjis(char sjis) { + return getBitmapFromAndroidPua(getAndroidPuaFromVendorSpecificSjis(sjis)); + } + + /** + * Returns Bitmap object corresponding to the vendor specific Unicode. + * + * See comments in getBitmapFromAndroidPua(). + * + * @param vsp vendor specific PUA. + * @return Bitmap object when this factory knows the Bitmap relevant to the code. Otherwise + * null is returned. + */ + public synchronized Bitmap getBitmapFromVendorSpecificPua(int vsp) { + return getBitmapFromAndroidPua(getAndroidPuaFromVendorSpecificPua(vsp)); + } + + /** + * Returns Unicode PUA for Android corresponding to the vendor specific sjis. + * + * @param sjis vendor specific sjis + * @return Unicode PUA for Android, or -1 if there's no map for the sjis. + */ + public int getAndroidPuaFromVendorSpecificSjis(char sjis) { + return nativeGetAndroidPuaFromVendorSpecificSjis(mNativeEmojiFactory, sjis); + } + + /** + * Returns vendor specific sjis corresponding to the Unicode AndroidPua. + * + * @param pua Unicode PUA for Android, + * @return vendor specific sjis, or -1 if there's no map for the AndroidPua. + */ + public int getVendorSpecificSjisFromAndroidPua(int pua) { + return nativeGetVendorSpecificSjisFromAndroidPua(mNativeEmojiFactory, pua); + } + + /** + * Returns Unicode PUA for Android corresponding to the vendor specific Unicode. + * + * @param vsp vendor specific PUA. + * @return Unicode PUA for Android, or -1 if there's no map for the + * Unicode. + */ + public int getAndroidPuaFromVendorSpecificPua(int vsp) { + return nativeGetAndroidPuaFromVendorSpecificPua(mNativeEmojiFactory, vsp); + } + + public String getAndroidPuaFromVendorSpecificPua(String vspString) { + if (vspString == null) { + return null; + } + int minVsp = nativeGetMinimumVendorSpecificPua(mNativeEmojiFactory); + int maxVsp = nativeGetMaximumVendorSpecificPua(mNativeEmojiFactory); + int len = vspString.length(); + int[] codePoints = new int[vspString.codePointCount(0, len)]; + + int new_len = 0; + for (int i = 0; i < len; i = vspString.offsetByCodePoints(i, 1), new_len++) { + int codePoint = vspString.codePointAt(i); + if (minVsp <= codePoint && codePoint <= maxVsp) { + int newCodePoint = getAndroidPuaFromVendorSpecificPua(codePoint); + if (newCodePoint > 0) { + codePoints[new_len] = newCodePoint; + continue; + } + } + codePoints[new_len] = codePoint; + } + return new String(codePoints, 0, new_len); + } + + /** + * Returns vendor specific Unicode corresponding to the Unicode AndroidPua. + * + * @param pua Unicode PUA for Android, + * @return vendor specific sjis, or -1 if there's no map for the AndroidPua. + */ + public int getVendorSpecificPuaFromAndroidPua(int pua) { + return nativeGetVendorSpecificPuaFromAndroidPua(mNativeEmojiFactory, pua); + } + + public String getVendorSpecificPuaFromAndroidPua(String puaString) { + if (puaString == null) { + return null; + } + int minVsp = nativeGetMinimumAndroidPua(mNativeEmojiFactory); + int maxVsp = nativeGetMaximumAndroidPua(mNativeEmojiFactory); + int len = puaString.length(); + int[] codePoints = new int[puaString.codePointCount(0, len)]; + + int new_len = 0; + for (int i = 0; i < len; i = puaString.offsetByCodePoints(i, 1), new_len++) { + int codePoint = puaString.codePointAt(i); + if (minVsp <= codePoint && codePoint <= maxVsp) { + int newCodePoint = getVendorSpecificPuaFromAndroidPua(codePoint); + if (newCodePoint > 0) { + codePoints[new_len] = newCodePoint; + continue; + } + } + codePoints[new_len] = codePoint; + } + return new String(codePoints, 0, new_len); + } + + /** + * Constructs an instance of EmojiFactory corresponding to the name. + * + * @param class_name Name of the factory. This must include complete package name. + * @return A concrete EmojiFactory instance corresponding to factory_name. + * If factory_name is invalid, null is returned. + */ + public static native EmojiFactory newInstance(String class_name); + + /** + * Constructs an instance of available EmojiFactory. + * + * @return A concrete EmojiFactory instance. If there are several available + * EmojiFactory class, preferred one is chosen by the system. If there isn't, null + * is returned. + */ + public static native EmojiFactory newAvailableInstance(); + + // native methods + + private native void nativeDestructor(int factory); + private native Bitmap nativeGetBitmapFromAndroidPua(int nativeEmojiFactory, int AndroidPua); + private native int nativeGetAndroidPuaFromVendorSpecificSjis(int nativeEmojiFactory, + char sjis); + private native int nativeGetVendorSpecificSjisFromAndroidPua(int nativeEmojiFactory, + int pua); + private native int nativeGetAndroidPuaFromVendorSpecificPua(int nativeEmojiFactory, + int vsp); + private native int nativeGetVendorSpecificPuaFromAndroidPua(int nativeEmojiFactory, + int pua); + private native int nativeGetMaximumVendorSpecificPua(int nativeEmojiFactory); + private native int nativeGetMinimumVendorSpecificPua(int nativeEmojiFactory); + private native int nativeGetMaximumAndroidPua(int nativeEmojiFactory); + private native int nativeGetMinimumAndroidPua(int nativeEmojiFactory); +} diff --git a/core/java/android/gadget/GadgetHost.java b/core/java/android/gadget/GadgetHost.java deleted file mode 100644 index 418f2aa17998b3d5b618ac04edcfc84d0bdcb603..0000000000000000000000000000000000000000 --- a/core/java/android/gadget/GadgetHost.java +++ /dev/null @@ -1,72 +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. - */ - -package android.gadget; - -import android.content.Context; -import android.widget.RemoteViews; - -/** - * GadgetHost provides the interaction with the Gadget Service for apps, - * like the home screen, that want to embed gadgets in their UI. - */ -public class GadgetHost { - public GadgetHost(Context context, int hostId) { - } - - /** - * Start receiving onGadgetChanged calls for your gadgets. Call this when your activity - * becomes visible, i.e. from onStart() in your Activity. - */ - public void startListening() { - } - - /** - * Stop receiving onGadgetChanged calls for your gadgets. Call this when your activity is - * no longer visible, i.e. from onStop() in your Activity. - */ - public void stopListening() { - } - - /** - * Stop listening to changes for this gadget. - */ - public void gadgetRemoved(int gadgetId) { - } - - /** - * Remove all records about gadget instances from the gadget manager. Call this when - * initializing your database, as it might be because of a data wipe. - */ - public void clearGadgets() { - } - - public final GadgetHostView createView(Context context, int gadgetId, GadgetInfo gadget) { - GadgetHostView view = onCreateView(context, gadgetId, gadget); - view.setGadget(gadgetId, gadget); - view.updateGadget(null); - return view; - } - - /** - * Called to create the GadgetHostView. Override to return a custom subclass if you - * need it. {@more} - */ - protected GadgetHostView onCreateView(Context context, int gadgetId, GadgetInfo gadget) { - return new GadgetHostView(context); - } -} - diff --git a/core/java/android/gadget/GadgetHostView.java b/core/java/android/gadget/GadgetHostView.java deleted file mode 100644 index e2bef8c12e40b756839e223ba04c4a68f616fd0f..0000000000000000000000000000000000000000 --- a/core/java/android/gadget/GadgetHostView.java +++ /dev/null @@ -1,102 +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. - */ - -package android.gadget; - -import android.content.Context; -import android.content.pm.PackageManager; -import android.gadget.GadgetInfo; -import android.util.AttributeSet; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.FrameLayout; -import android.widget.RemoteViews; -import android.widget.TextView; - -public class GadgetHostView extends FrameLayout { - static final String TAG = "GadgetHostView"; - - // When we're inflating the initialLayout for a gadget, we only allow - // views that are allowed in RemoteViews. - static final LayoutInflater.Filter sInflaterFilter = new LayoutInflater.Filter() { - public boolean onLoadClass(Class clazz) { - return clazz.isAnnotationPresent(RemoteViews.RemoteView.class); - } - }; - - int mGadgetId; - GadgetInfo mInfo; - View mContentView; - - public GadgetHostView(Context context) { - super(context); - } - - public void setGadget(int gadgetId, GadgetInfo info) { - if (mInfo != null) { - // TODO: remove the old view, or whatever - } - mGadgetId = gadgetId; - mInfo = info; - } - - public void updateGadget(RemoteViews remoteViews) { - Context context = getContext(); - - View contentView = null; - Exception exception = null; - try { - if (remoteViews == null) { - // there is no remoteViews (yet), so use the initial layout - Context theirContext = context.createPackageContext(mInfo.provider.getPackageName(), - 0); - LayoutInflater inflater = (LayoutInflater)theirContext.getSystemService( - Context.LAYOUT_INFLATER_SERVICE); - inflater = inflater.cloneInContext(theirContext); - inflater.setFilter(sInflaterFilter); - contentView = inflater.inflate(mInfo.initialLayout, this, false); - } else { - // use the RemoteViews - contentView = remoteViews.apply(mContext, this); - } - } - catch (PackageManager.NameNotFoundException e) { - exception = e; - } - catch (RuntimeException e) { - exception = e; - } - if (contentView == null) { - Log.w(TAG, "Error inflating gadget " + mInfo, exception); - // TODO: Should we throw an exception here for the host activity to catch? - // Maybe we should show a generic error widget. - TextView tv = new TextView(context); - tv.setText("Error inflating gadget"); - contentView = tv; - } - - FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( - FrameLayout.LayoutParams.WRAP_CONTENT, - FrameLayout.LayoutParams.WRAP_CONTENT); - - mContentView = contentView; - this.addView(contentView, lp); - - // TODO: do an animation (maybe even one provided by the gadget). - } -} - diff --git a/core/java/android/gadget/GadgetInfo.java b/core/java/android/gadget/GadgetInfo.java deleted file mode 100644 index 1a7a9a0ef04439544bf25a6b199965d48880ec18..0000000000000000000000000000000000000000 --- a/core/java/android/gadget/GadgetInfo.java +++ /dev/null @@ -1,126 +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. - */ - -package android.gadget; - -import android.os.Parcel; -import android.os.Parcelable; -import android.content.ComponentName; - -/** - * Describes the meta data for an installed gadget. - */ -public class GadgetInfo implements Parcelable { - /** - * Identity of this gadget component. This component should be a {@link - * android.content.BroadcastReceiver}, and it will be sent the Gadget intents - * {@link android.gadget as described in the gadget package documentation}. - */ - public ComponentName provider; - - /** - * Minimum width of the gadget, in dp. - */ - public int minWidth; - - /** - * Minimum height of the gadget, in dp. - */ - public int minHeight; - - /** - * How often, in milliseconds, that this gadget wants to be updated. - * The gadget manager may place a limit on how often a gadget is updated. - */ - public int updatePeriodMillis; - - /** - * The resource id of the initial layout for this gadget. This should be - * displayed until the RemoteViews for the gadget is available. - */ - public int initialLayout; - - /** - * The activity to launch that will configure the gadget. - */ - public ComponentName configure; - - public GadgetInfo() { - } - - /** - * Unflatten the GadgetInfo from a parcel. - */ - public GadgetInfo(Parcel in) { - if (0 != in.readInt()) { - this.provider = new ComponentName(in); - } - this.minWidth = in.readInt(); - this.minHeight = in.readInt(); - this.updatePeriodMillis = in.readInt(); - this.initialLayout = in.readInt(); - if (0 != in.readInt()) { - this.configure = new ComponentName(in); - } - } - - - public void writeToParcel(android.os.Parcel out, int flags) { - if (this.provider != null) { - out.writeInt(1); - this.provider.writeToParcel(out, flags); - } else { - out.writeInt(0); - } - out.writeInt(this.minWidth); - out.writeInt(this.minHeight); - out.writeInt(this.updatePeriodMillis); - out.writeInt(this.initialLayout); - if (this.configure != null) { - out.writeInt(1); - this.configure.writeToParcel(out, flags); - } else { - out.writeInt(0); - } - } - - public int describeContents() { - return 0; - } - - /** - * Parcelable.Creator that instantiates GadgetInfo objects - */ - public static final Parcelable.Creator CREATOR - = new Parcelable.Creator() - { - public GadgetInfo createFromParcel(Parcel parcel) - { - return new GadgetInfo(parcel); - } - - public GadgetInfo[] newArray(int size) - { - return new GadgetInfo[size]; - } - }; - - public String toString() { - return "GadgetInfo(provider=" + this.provider + ")"; - } -} - - diff --git a/core/java/android/gadget/GadgetManager.java b/core/java/android/gadget/GadgetManager.java deleted file mode 100644 index 088dc86f9d588bf3b92475c1e3a0675b5f21cb46..0000000000000000000000000000000000000000 --- a/core/java/android/gadget/GadgetManager.java +++ /dev/null @@ -1,180 +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. - */ - -package android.gadget; - -import android.content.ComponentName; -import android.content.Context; -import android.os.IBinder; -import android.os.RemoteException; -import android.os.ServiceManager; -import android.util.Log; -import android.widget.RemoteViews; - -import com.android.internal.gadget.IGadgetService; - -import java.lang.ref.WeakReference; -import java.util.List; -import java.util.WeakHashMap; - -public class GadgetManager { - static final String TAG = "GadgetManager"; - - /** - * Send this when you want to pick a gadget to display. - * - *

      - * The system will respond with an onActivityResult call with the following extras in - * the intent: - *

        - *
      • gadgetId
      • - *
      • gadgetId
      • - *
      • gadgetId
      • - *
      - * TODO: Add constants for these. - * TODO: Where does this go? - */ - public static final String GADGET_PICK_ACTION = "android.gadget.action.PICK_GADGET"; - - public static final String EXTRA_GADGET_ID = "gadgetId"; - - /** - * Sent when it is time to update your gadget. - */ - public static final String GADGET_UPDATE_ACTION = "android.gadget.action.GADGET_UPDATE"; - - /** - * Sent when the gadget is added to a host for the first time. TODO: Maybe we don't want this. - */ - public static final String GADGET_ENABLE_ACTION = "android.gadget.action.GADGET_ENABLE"; - - /** - * Sent when the gadget is removed from the last host. TODO: Maybe we don't want this. - */ - public static final String GADGET_DISABLE_ACTION = "android.gadget.action.GADGET_DISABLE"; - - /** - * Field for the manifest meta-data tag. - */ - public static final String GADGET_PROVIDER_META_DATA = "android.gadget.provider"; - - static WeakHashMap> sManagerCache = new WeakHashMap(); - static IGadgetService sService; - - Context mContext; - - public static GadgetManager getInstance(Context context) { - synchronized (sManagerCache) { - if (sService == null) { - IBinder b = ServiceManager.getService(Context.GADGET_SERVICE); - sService = IGadgetService.Stub.asInterface(b); - } - - WeakReference ref = sManagerCache.get(context); - GadgetManager result = null; - if (ref != null) { - result = ref.get(); - } - if (result == null) { - result = new GadgetManager(context); - sManagerCache.put(context, new WeakReference(result)); - } - return result; - } - } - - private GadgetManager(Context context) { - mContext = context; - } - - /** - * Call this with the new RemoteViews for your gadget whenever you need to. - * - *

      - * This method will only work when called from the uid that owns the gadget provider. - * - * @param gadgetId The gadget instance for which to set the RemoteViews. - * @param views The RemoteViews object to show. - */ - public void updateGadget(int gadgetId, RemoteViews views) { - } - - /** - * Return a list of the gadget providers that are currently installed. - */ - public List getInstalledProviders() { - try { - return sService.getInstalledProviders(); - } - catch (RemoteException e) { - throw new RuntimeException("system server dead?", e); - } - } - - /** - * Get the available info about the gadget. If the gadgetId has not been bound yet, - * this method will return null. - * - * TODO: throws GadgetNotFoundException ??? if not valid - */ - public GadgetInfo getGadgetInfo(int gadgetId) { - try { - return sService.getGadgetInfo(gadgetId); - } - catch (RemoteException e) { - throw new RuntimeException("system server dead?", e); - } - } - - /** - * Get a gadgetId for a host in the calling process. - * - * @return a gadgetId - */ - public int allocateGadgetId(String hostPackage) { - try { - return sService.allocateGadgetId(hostPackage); - } - catch (RemoteException e) { - throw new RuntimeException("system server dead?", e); - } - } - - /** - * Delete the gadgetId. Same as removeGadget on GadgetHost. - */ - public void deleteGadgetId(int gadgetId) { - try { - sService.deleteGadgetId(gadgetId); - } - catch (RemoteException e) { - throw new RuntimeException("system server dead?", e); - } - } - - /** - * Set the component for a given gadgetId. You need the GADGET_LIST permission. - */ - public void bindGadgetId(int gadgetId, ComponentName provider) { - try { - sService.bindGadgetId(gadgetId, provider); - } - catch (RemoteException e) { - throw new RuntimeException("system server dead?", e); - } - } -} - diff --git a/core/java/android/gadget/package.html b/core/java/android/gadget/package.html deleted file mode 100644 index 280ccfb4512d4a18cab8c0c5e3167c94cf17903b..0000000000000000000000000000000000000000 --- a/core/java/android/gadget/package.html +++ /dev/null @@ -1,4 +0,0 @@ - -@hide - - diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java index c09567c7f0a6de59643f89aa202a93c2e053e3b7..106c9200b680c9fd020b13f0c2723ed0b4ed4a11 100644 --- a/core/java/android/hardware/Camera.java +++ b/core/java/android/hardware/Camera.java @@ -18,6 +18,7 @@ package android.hardware; import java.lang.ref.WeakReference; import java.util.HashMap; +import java.util.StringTokenizer; import java.io.IOException; import android.util.Log; @@ -47,7 +48,6 @@ public class Camera { private static final int ERROR_CALLBACK = 5; private int mNativeContext; // accessed by native methods - private int mListenerContext; private EventHandler mEventHandler; private ShutterCallback mShutterCallback; private PictureCallback mRawImageCallback; @@ -494,11 +494,17 @@ public class Camera { */ public void unflatten(String flattened) { mMap.clear(); - String[] pairs = flattened.split(";"); - for (String p : pairs) { - String[] kv = p.split("="); - if (kv.length == 2) - mMap.put(kv[0], kv[1]); + + StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); + while (tokenizer.hasMoreElements()) { + String kv = tokenizer.nextToken(); + int pos = kv.indexOf('='); + if (pos == -1) { + continue; + } + String k = kv.substring(0, pos); + String v = kv.substring(pos + 1); + mMap.put(k, v); } } diff --git a/core/java/android/hardware/GeomagneticField.java b/core/java/android/hardware/GeomagneticField.java new file mode 100644 index 0000000000000000000000000000000000000000..b4c04b1c023f402cfbdbab4d33a6d705986edb65 --- /dev/null +++ b/core/java/android/hardware/GeomagneticField.java @@ -0,0 +1,409 @@ +/* + * 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. + */ + +package android.hardware; + +import java.util.GregorianCalendar; + +/** + * This class is used to estimated estimate magnetic field at a given point on + * Earth, and in particular, to compute the magnetic declination from true + * north. + * + *

      This uses the World Magnetic Model produced by the United States National + * Geospatial-Intelligence Agency. More details about the model can be found at + * http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml. + * This class currently uses WMM-2005 which is valid until 2010, but should + * produce acceptable results for several years after that. + */ +public class GeomagneticField { + // The magnetic field at a given point, in nonoteslas in geodetic + // coordinates. + private float mX; + private float mY; + private float mZ; + + // Geocentric coordinates -- set by computeGeocentricCoordinates. + private float mGcLatitudeRad; + private float mGcLongitudeRad; + private float mGcRadiusKm; + + // Constants from WGS84 (the coordinate system used by GPS) + static private final float EARTH_SEMI_MAJOR_AXIS_KM = 6378.137f; + static private final float EARTH_SEMI_MINOR_AXIS_KM = 6356.7523f; + static private final float EARTH_REFERENCE_RADIUS_KM = 6371.2f; + + // These coefficients and the formulae used below are from: + // NOAA Technical Report: The US/UK World Magnetic Model for 2005-2010 + static private final float[][] G_COEFF = new float[][] { + { 0f }, + { -29556.8f, -1671.7f }, + { -2340.6f, 3046.9f, 1657.0f }, + { 1335.4f, -2305.1f, 1246.7f, 674.0f }, + { 919.8f, 798.1f, 211.3f, -379.4f, 100.0f }, + { -227.4f, 354.6f, 208.7f, -136.5f, -168.3f, -14.1f }, + { 73.2f, 69.7f, 76.7f, -151.2f, -14.9f, 14.6f, -86.3f }, + { 80.1f, -74.5f, -1.4f, 38.5f, 12.4f, 9.5f, 5.7f, 1.8f }, + { 24.9f, 7.7f, -11.6f, -6.9f, -18.2f, 10.0f, 9.2f, -11.6f, -5.2f }, + { 5.6f, 9.9f, 3.5f, -7.0f, 5.1f, -10.8f, -1.3f, 8.8f, -6.7f, -9.1f }, + { -2.3f, -6.3f, 1.6f, -2.6f, 0.0f, 3.1f, 0.4f, 2.1f, 3.9f, -0.1f, -2.3f }, + { 2.8f, -1.6f, -1.7f, 1.7f, -0.1f, 0.1f, -0.7f, 0.7f, 1.8f, 0.0f, 1.1f, 4.1f }, + { -2.4f, -0.4f, 0.2f, 0.8f, -0.3f, 1.1f, -0.5f, 0.4f, -0.3f, -0.3f, -0.1f, + -0.3f, -0.1f } }; + + static private final float[][] H_COEFF = new float[][] { + { 0f }, + { 0.0f, 5079.8f }, + { 0.0f, -2594.7f, -516.7f }, + { 0.0f, -199.9f, 269.3f, -524.2f }, + { 0.0f, 281.5f, -226.0f, 145.8f, -304.7f }, + { 0.0f, 42.4f, 179.8f, -123.0f, -19.5f, 103.6f }, + { 0.0f, -20.3f, 54.7f, 63.6f, -63.4f, -0.1f, 50.4f }, + { 0.0f, -61.5f, -22.4f, 7.2f, 25.4f, 11.0f, -26.4f, -5.1f }, + { 0.0f, 11.2f, -21.0f, 9.6f, -19.8f, 16.1f, 7.7f, -12.9f, -0.2f }, + { 0.0f, -20.1f, 12.9f, 12.6f, -6.7f, -8.1f, 8.0f, 2.9f, -7.9f, 6.0f }, + { 0.0f, 2.4f, 0.2f, 4.4f, 4.8f, -6.5f, -1.1f, -3.4f, -0.8f, -2.3f, -7.9f }, + { 0.0f, 0.3f, 1.2f, -0.8f, -2.5f, 0.9f, -0.6f, -2.7f, -0.9f, -1.3f, -2.0f, -1.2f }, + { 0.0f, -0.4f, 0.3f, 2.4f, -2.6f, 0.6f, 0.3f, 0.0f, 0.0f, 0.3f, -0.9f, -0.4f, + 0.8f } }; + + static private final float[][] DELTA_G = new float[][] { + { 0f }, + { 8.0f, 10.6f }, + { -15.1f, -7.8f, -0.8f }, + { 0.4f, -2.6f, -1.2f, -6.5f }, + { -2.5f, 2.8f, -7.0f, 6.2f, -3.8f }, + { -2.8f, 0.7f, -3.2f, -1.1f, 0.1f, -0.8f }, + { -0.7f, 0.4f, -0.3f, 2.3f, -2.1f, -0.6f, 1.4f }, + { 0.2f, -0.1f, -0.3f, 1.1f, 0.6f, 0.5f, -0.4f, 0.6f }, + { 0.1f, 0.3f, -0.4f, 0.3f, -0.3f, 0.2f, 0.4f, -0.7f, 0.4f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } }; + + static private final float[][] DELTA_H = new float[][] { + { 0f }, + { 0.0f, -20.9f }, + { 0.0f, -23.2f, -14.6f }, + { 0.0f, 5.0f, -7.0f, -0.6f }, + { 0.0f, 2.2f, 1.6f, 5.8f, 0.1f }, + { 0.0f, 0.0f, 1.7f, 2.1f, 4.8f, -1.1f }, + { 0.0f, -0.6f, -1.9f, -0.4f, -0.5f, -0.3f, 0.7f }, + { 0.0f, 0.6f, 0.4f, 0.2f, 0.3f, -0.8f, -0.2f, 0.1f }, + { 0.0f, -0.2f, 0.1f, 0.3f, 0.4f, 0.1f, -0.2f, 0.4f, 0.4f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } }; + + static private final long BASE_TIME = + new GregorianCalendar(2005, 1, 1).getTimeInMillis(); + + // The ratio between the Gauss-normalized associated Legendre functions and + // the Schmid quasi-normalized ones. Compute these once staticly since they + // don't depend on input variables at all. + static private final float[][] SCHMIDT_QUASI_NORM_FACTORS = + computeSchmidtQuasiNormFactors(G_COEFF.length); + + /** + * Estimate the magnetic field at a given point and time. + * + * @param gdLatitudeDeg + * Latitude in WGS84 geodetic coordinates -- positive is east. + * @param gdLongitudeDeg + * Longitude in WGS84 geodetic coordinates -- positive is north. + * @param altitudeMeters + * Altitude in WGS84 geodetic coordinates, in meters. + * @param timeMillis + * Time at which to evaluate the declination, in milliseconds + * since January 1, 1970. (approximate is fine -- the declination + * changes very slowly). + */ + public GeomagneticField(float gdLatitudeDeg, + float gdLongitudeDeg, + float altitudeMeters, + long timeMillis) { + final int MAX_N = G_COEFF.length; // Maximum degree of the coefficients. + + // We don't handle the north and south poles correctly -- pretend that + // we're not quite at them to avoid crashing. + gdLatitudeDeg = Math.min(90.0f - 1e-5f, + Math.max(-90.0f + 1e-5f, gdLatitudeDeg)); + computeGeocentricCoordinates(gdLatitudeDeg, + gdLongitudeDeg, + altitudeMeters); + + assert G_COEFF.length == H_COEFF.length; + + // Note: LegendreTable computes associated Legendre functions for + // cos(theta). We want the associated Legendre functions for + // sin(latitude), which is the same as cos(PI/2 - latitude), except the + // derivate will be negated. + LegendreTable legendre = + new LegendreTable(MAX_N - 1, + (float) (Math.PI / 2.0 - mGcLatitudeRad)); + + // Compute a table of (EARTH_REFERENCE_RADIUS_KM / radius)^n for i in + // 0..MAX_N-2 (this is much faster than calling Math.pow MAX_N+1 times). + float[] relativeRadiusPower = new float[MAX_N + 2]; + relativeRadiusPower[0] = 1.0f; + relativeRadiusPower[1] = EARTH_REFERENCE_RADIUS_KM / mGcRadiusKm; + for (int i = 2; i < relativeRadiusPower.length; ++i) { + relativeRadiusPower[i] = relativeRadiusPower[i - 1] * + relativeRadiusPower[1]; + } + + // Compute tables of sin(lon * m) and cos(lon * m) for m = 0..MAX_N -- + // this is much faster than calling Math.sin and Math.com MAX_N+1 times. + float[] sinMLon = new float[MAX_N]; + float[] cosMLon = new float[MAX_N]; + sinMLon[0] = 0.0f; + cosMLon[0] = 1.0f; + sinMLon[1] = (float) Math.sin(mGcLongitudeRad); + cosMLon[1] = (float) Math.cos(mGcLongitudeRad); + + for (int m = 2; m < MAX_N; ++m) { + // Standard expansions for sin((m-x)*theta + x*theta) and + // cos((m-x)*theta + x*theta). + int x = m >> 1; + sinMLon[m] = sinMLon[m-x] * cosMLon[x] + cosMLon[m-x] * sinMLon[x]; + cosMLon[m] = cosMLon[m-x] * cosMLon[x] - sinMLon[m-x] * sinMLon[x]; + } + + float inverseCosLatitude = 1.0f / (float) Math.cos(mGcLatitudeRad); + float yearsSinceBase = + (timeMillis - BASE_TIME) / (365f * 24f * 60f * 60f * 1000f); + + // We now compute the magnetic field strength given the geocentric + // location. The magnetic field is the derivative of the potential + // function defined by the model. See NOAA Technical Report: The US/UK + // World Magnetic Model for 2005-2010 for the derivation. + float gcX = 0.0f; // Geocentric northwards component. + float gcY = 0.0f; // Geocentric eastwards component. + float gcZ = 0.0f; // Geocentric downwards component. + + for (int n = 1; n < MAX_N; n++) { + for (int m = 0; m <= n; m++) { + // Adjust the coefficients for the current date. + float g = G_COEFF[n][m] + yearsSinceBase * DELTA_G[n][m]; + float h = H_COEFF[n][m] + yearsSinceBase * DELTA_H[n][m]; + + // Negative derivative with respect to latitude, divided by + // radius. This looks like the negation of the version in the + // NOAA Techincal report because that report used + // P_n^m(sin(theta)) and we use P_n^m(cos(90 - theta)), so the + // derivative with respect to theta is negated. + gcX += relativeRadiusPower[n+2] + * (g * cosMLon[m] + h * sinMLon[m]) + * legendre.mPDeriv[n][m] + * SCHMIDT_QUASI_NORM_FACTORS[n][m]; + + // Negative derivative with respect to longitude, divided by + // radius. + gcY += relativeRadiusPower[n+2] * m + * (g * sinMLon[m] - h * cosMLon[m]) + * legendre.mP[n][m] + * SCHMIDT_QUASI_NORM_FACTORS[n][m] + * inverseCosLatitude; + + // Negative derivative with respect to radius. + gcZ -= (n + 1) * relativeRadiusPower[n+2] + * (g * cosMLon[m] + h * sinMLon[m]) + * legendre.mP[n][m] + * SCHMIDT_QUASI_NORM_FACTORS[n][m]; + } + } + + // Convert back to geodetic coordinates. This is basically just a + // rotation around the Y-axis by the difference in latitudes between the + // geocentric frame and the geodetic frame. + double latDiffRad = Math.toRadians(gdLatitudeDeg) - mGcLatitudeRad; + mX = (float) (gcX * Math.cos(latDiffRad) + + gcZ * Math.sin(latDiffRad)); + mY = gcY; + mZ = (float) (- gcX * Math.sin(latDiffRad) + + gcZ * Math.cos(latDiffRad)); + } + + /** + * @return The X (northward) component of the magnetic field in nanoteslas. + */ + public float getX() { + return mX; + } + + /** + * @return The Y (eastward) component of the magnetic field in nanoteslas. + */ + public float getY() { + return mY; + } + + /** + * @return The Z (downward) component of the magnetic field in nanoteslas. + */ + public float getZ() { + return mZ; + } + + /** + * @return The declination of the horizontal component of the magnetic + * field from true north, in degrees (i.e. positive means the + * magnetic field is rotated east that much from true north). + */ + public float getDeclination() { + return (float) Math.toDegrees(Math.atan2(mY, mX)); + } + + /** + * @return The inclination of the magnetic field in degrees -- positive + * means the magnetic field is rotated downwards. + */ + public float getInclination() { + return (float) Math.toDegrees(Math.atan2(mZ, + getHorizontalStrength())); + } + + /** + * @return Horizontal component of the field strength in nonoteslas. + */ + public float getHorizontalStrength() { + return (float) Math.sqrt(mX * mX + mY * mY); + } + + /** + * @return Total field strength in nanoteslas. + */ + public float getFieldStrength() { + return (float) Math.sqrt(mX * mX + mY * mY + mZ * mZ); + } + + /** + * @param gdLatitudeDeg + * Latitude in WGS84 geodetic coordinates. + * @param gdLongitudeDeg + * Longitude in WGS84 geodetic coordinates. + * @param altitudeMeters + * Altitude above sea level in WGS84 geodetic coordinates. + * @return Geocentric latitude (i.e. angle between closest point on the + * equator and this point, at the center of the earth. + */ + private void computeGeocentricCoordinates(float gdLatitudeDeg, + float gdLongitudeDeg, + float altitudeMeters) { + float altitudeKm = altitudeMeters / 1000.0f; + float a2 = EARTH_SEMI_MAJOR_AXIS_KM * EARTH_SEMI_MAJOR_AXIS_KM; + float b2 = EARTH_SEMI_MINOR_AXIS_KM * EARTH_SEMI_MINOR_AXIS_KM; + double gdLatRad = Math.toRadians(gdLatitudeDeg); + float clat = (float) Math.cos(gdLatRad); + float slat = (float) Math.sin(gdLatRad); + float tlat = slat / clat; + float latRad = + (float) Math.sqrt(a2 * clat * clat + b2 * slat * slat); + + mGcLatitudeRad = (float) Math.atan(tlat * (latRad * altitudeKm + b2) + / (latRad * altitudeKm + a2)); + + mGcLongitudeRad = (float) Math.toRadians(gdLongitudeDeg); + + float radSq = altitudeKm * altitudeKm + + 2 * altitudeKm * (float) Math.sqrt(a2 * clat * clat + + b2 * slat * slat) + + (a2 * a2 * clat * clat + b2 * b2 * slat * slat) + / (a2 * clat * clat + b2 * slat * slat); + mGcRadiusKm = (float) Math.sqrt(radSq); + } + + + /** + * Utility class to compute a table of Gauss-normalized associated Legendre + * functions P_n^m(cos(theta)) + */ + static private class LegendreTable { + // These are the Gauss-normalized associated Legendre functions -- that + // is, they are normal Legendre functions multiplied by + // (n-m)!/(2n-1)!! (where (2n-1)!! = 1*3*5*...*2n-1) + public final float[][] mP; + + // Derivative of mP, with respect to theta. + public final float[][] mPDeriv; + + /** + * @param maxN + * The maximum n- and m-values to support + * @param thetaRad + * Returned functions will be Gauss-normalized + * P_n^m(cos(thetaRad)), with thetaRad in radians. + */ + public LegendreTable(int maxN, float thetaRad) { + // Compute the table of Gauss-normalized associated Legendre + // functions using standard recursion relations. Also compute the + // table of derivatives using the derivative of the recursion + // relations. + float cos = (float) Math.cos(thetaRad); + float sin = (float) Math.sin(thetaRad); + + mP = new float[maxN + 1][]; + mPDeriv = new float[maxN + 1][]; + mP[0] = new float[] { 1.0f }; + mPDeriv[0] = new float[] { 0.0f }; + for (int n = 1; n <= maxN; n++) { + mP[n] = new float[n + 1]; + mPDeriv[n] = new float[n + 1]; + for (int m = 0; m <= n; m++) { + if (n == m) { + mP[n][m] = sin * mP[n - 1][m - 1]; + mPDeriv[n][m] = cos * mP[n - 1][m - 1] + + sin * mPDeriv[n - 1][m - 1]; + } else if (n == 1 || m == n - 1) { + mP[n][m] = cos * mP[n - 1][m]; + mPDeriv[n][m] = -sin * mP[n - 1][m] + + cos * mPDeriv[n - 1][m]; + } else { + assert n > 1 && m < n - 1; + float k = ((n - 1) * (n - 1) - m * m) + / (float) ((2 * n - 1) * (2 * n - 3)); + mP[n][m] = cos * mP[n - 1][m] - k * mP[n - 2][m]; + mPDeriv[n][m] = -sin * mP[n - 1][m] + + cos * mPDeriv[n - 1][m] - k * mPDeriv[n - 2][m]; + } + } + } + } + } + + /** + * Compute the ration between the Gauss-normalized associated Legendre + * functions and the Schmidt quasi-normalized version. This is equivalent to + * sqrt((m==0?1:2)*(n-m)!/(n+m!))*(2n-1)!!/(n-m)! + */ + private static float[][] computeSchmidtQuasiNormFactors(int maxN) { + float[][] schmidtQuasiNorm = new float[maxN + 1][]; + schmidtQuasiNorm[0] = new float[] { 1.0f }; + for (int n = 1; n <= maxN; n++) { + schmidtQuasiNorm[n] = new float[n + 1]; + schmidtQuasiNorm[n][0] = + schmidtQuasiNorm[n - 1][0] * (2 * n - 1) / (float) n; + for (int m = 1; m <= n; m++) { + schmidtQuasiNorm[n][m] = schmidtQuasiNorm[n][m - 1] + * (float) Math.sqrt((n - m + 1) * (m == 1 ? 2 : 1) + / (float) (n + m)); + } + } + return schmidtQuasiNorm; + } +} \ No newline at end of file diff --git a/core/java/android/hardware/ISensorService.aidl b/core/java/android/hardware/ISensorService.aidl index 8aad9b465bda06c5c0278d02d5b72aa3995f4de8..04af2aec45239f6d160eab888b0ce152de6d7f11 100644 --- a/core/java/android/hardware/ISensorService.aidl +++ b/core/java/android/hardware/ISensorService.aidl @@ -25,5 +25,5 @@ import android.os.ParcelFileDescriptor; interface ISensorService { ParcelFileDescriptor getDataChanel(); - boolean enableSensor(IBinder listener, int sensor, int enable); + boolean enableSensor(IBinder listener, String name, int sensor, int enable); } diff --git a/core/java/android/hardware/SensorManager.java b/core/java/android/hardware/SensorManager.java index f02094eed63d11f8b98b5c4f477ac464fee952e0..e232c2cee04355f8b8ccbd237cbb81bf26db4a69 100644 --- a/core/java/android/hardware/SensorManager.java +++ b/core/java/android/hardware/SensorManager.java @@ -620,6 +620,9 @@ public class SensorManager extends IRotationWatcher.Stub */ @Deprecated public boolean registerListener(SensorListener listener, int sensors, int rate) { + if (listener == null) { + return false; + } boolean result = false; result = registerLegacyListener(SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER, listener, sensors, rate) || result; @@ -638,6 +641,9 @@ public class SensorManager extends IRotationWatcher.Stub private boolean registerLegacyListener(int legacyType, int type, SensorListener listener, int sensors, int rate) { + if (listener == null) { + return false; + } boolean result = false; // Are we activating this legacy sensor? if ((sensors & legacyType) != 0) { @@ -693,6 +699,9 @@ public class SensorManager extends IRotationWatcher.Stub private void unregisterLegacyListener(int legacyType, int type, SensorListener listener, int sensors) { + if (listener == null) { + return; + } // do we know about this listener? LegacyListener legacyListener = null; synchronized (mLegacyListenersMap) { @@ -741,7 +750,7 @@ public class SensorManager extends IRotationWatcher.Stub */ @Deprecated public void unregisterListener(SensorListener listener) { - unregisterListener(listener, SENSOR_ALL); + unregisterListener(listener, SENSOR_ALL | SENSOR_ORIENTATION_RAW); } /** @@ -800,6 +809,9 @@ public class SensorManager extends IRotationWatcher.Stub */ public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate, Handler handler) { + if (listener == null || sensor == null) { + return false; + } boolean result; int delay = -1; switch (rate) { @@ -829,9 +841,11 @@ public class SensorManager extends IRotationWatcher.Stub } } + String name = sensor.getName(); + int handle = sensor.getHandle(); if (l == null) { l = new ListenerDelegate(listener, sensor, handler); - result = mSensorService.enableSensor(l, sensor.getHandle(), delay); + result = mSensorService.enableSensor(l, name, handle, delay); if (result) { sListeners.add(l); sListeners.notify(); @@ -840,7 +854,7 @@ public class SensorManager extends IRotationWatcher.Stub sSensorThread.startLocked(mSensorService); } } else { - result = mSensorService.enableSensor(l, sensor.getHandle(), delay); + result = mSensorService.enableSensor(l, name, handle, delay); if (result) { l.addSensor(sensor); } @@ -854,6 +868,9 @@ public class SensorManager extends IRotationWatcher.Stub } private void unregisterListener(Object listener, Sensor sensor) { + if (listener == null || sensor == null) { + return; + } try { synchronized (sListeners) { final int size = sListeners.size(); @@ -861,8 +878,9 @@ public class SensorManager extends IRotationWatcher.Stub ListenerDelegate l = sListeners.get(i); if (l.getListener() == listener) { // disable these sensors + String name = sensor.getName(); int handle = sensor.getHandle(); - mSensorService.enableSensor(l, handle, SENSOR_DISABLE); + mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE); // if we have no more sensors enabled on this listener, // take it off the list. if (l.removeSensor(sensor) == 0) { @@ -878,6 +896,9 @@ public class SensorManager extends IRotationWatcher.Stub } private void unregisterListener(Object listener) { + if (listener == null) { + return; + } try { synchronized (sListeners) { final int size = sListeners.size(); @@ -886,7 +907,9 @@ public class SensorManager extends IRotationWatcher.Stub if (l.getListener() == listener) { // disable all sensors for this listener for (Sensor sensor : l.getSensors()) { - mSensorService.enableSensor(l, sensor.getHandle(), SENSOR_DISABLE); + String name = sensor.getName(); + int handle = sensor.getHandle(); + mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE); } sListeners.remove(i); break; diff --git a/core/java/android/inputmethodservice/AbstractInputMethodService.java b/core/java/android/inputmethodservice/AbstractInputMethodService.java index 7d02f6588db4cdf9e0351315bc4e3edea0eaefc7..eedcc354e61337a931919511095620f58dbbd4f6 100644 --- a/core/java/android/inputmethodservice/AbstractInputMethodService.java +++ b/core/java/android/inputmethodservice/AbstractInputMethodService.java @@ -24,6 +24,9 @@ import android.view.MotionEvent; import android.view.inputmethod.InputMethod; import android.view.inputmethod.InputMethodSession; +import java.io.FileDescriptor; +import java.io.PrintWriter; + /** * AbstractInputMethodService provides a abstract base class for input methods. * Normal input method implementations will not derive from this directly, @@ -156,6 +159,13 @@ public abstract class AbstractInputMethodService extends Service */ public abstract AbstractInputMethodSessionImpl onCreateInputMethodSessionInterface(); + /** + * Implement this to handle {@link android.os.Binder#dump Binder.dump()} + * calls on your input method. + */ + protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { + } + @Override final public IBinder onBind(Intent intent) { if (mInputMethod == null) { diff --git a/core/java/android/inputmethodservice/ExtractButton.java b/core/java/android/inputmethodservice/ExtractButton.java new file mode 100644 index 0000000000000000000000000000000000000000..d6fe38d3ea4a4b2502df2acc7ade068e7e69b057 --- /dev/null +++ b/core/java/android/inputmethodservice/ExtractButton.java @@ -0,0 +1,30 @@ +package android.inputmethodservice; + +import android.content.Context; +import android.util.AttributeSet; +import android.widget.Button; + +/*** + * Specialization of {@link Button} that ignores the window not being focused. + */ +class ExtractButton extends Button { + public ExtractButton(Context context) { + super(context, null); + } + + public ExtractButton(Context context, AttributeSet attrs) { + super(context, attrs, com.android.internal.R.attr.buttonStyle); + } + + public ExtractButton(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + /** + * Pretend like the window this view is in always has focus, so it will + * highlight when selected. + */ + @Override public boolean hasWindowFocus() { + return this.isEnabled() ? true : false; + } +} diff --git a/core/java/android/inputmethodservice/ExtractEditText.java b/core/java/android/inputmethodservice/ExtractEditText.java index e59f38b368db04843ea52868959886b6fb206fa3..0295f695784f29258374accc31254f4926fae66e 100644 --- a/core/java/android/inputmethodservice/ExtractEditText.java +++ b/core/java/android/inputmethodservice/ExtractEditText.java @@ -2,6 +2,7 @@ package android.inputmethodservice; import android.content.Context; import android.util.AttributeSet; +import android.view.inputmethod.ExtractedText; import android.widget.EditText; /*** @@ -9,6 +10,9 @@ import android.widget.EditText; * extracted text in a full-screen input method. */ public class ExtractEditText extends EditText { + private InputMethodService mIME; + private int mSettingExtractedText; + public ExtractEditText(Context context) { super(context, null); } @@ -20,4 +24,107 @@ public class ExtractEditText extends EditText { public ExtractEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } + + void setIME(InputMethodService ime) { + mIME = ime; + } + + /** + * Start making changes that will not be reported to the client. That + * is, {@link #onSelectionChanged(int, int)} will not result in sending + * the new selection to the client + */ + public void startInternalChanges() { + mSettingExtractedText += 1; + } + + /** + * Finish making changes that will not be reported to the client. That + * is, {@link #onSelectionChanged(int, int)} will not result in sending + * the new selection to the client + */ + public void finishInternalChanges() { + mSettingExtractedText -= 1; + } + + /** + * Implement just to keep track of when we are setting text from the + * client (vs. seeing changes in ourself from the user). + */ + @Override public void setExtractedText(ExtractedText text) { + try { + mSettingExtractedText++; + super.setExtractedText(text); + } finally { + mSettingExtractedText--; + } + } + + /** + * Report to the underlying text editor about selection changes. + */ + @Override protected void onSelectionChanged(int selStart, int selEnd) { + if (mSettingExtractedText == 0 && mIME != null && selStart >= 0 && selEnd >= 0) { + mIME.onExtractedSelectionChanged(selStart, selEnd); + } + } + + /** + * Redirect clicks to the IME for handling there. First allows any + * on click handler to run, though. + */ + @Override public boolean performClick() { + if (!super.performClick() && mIME != null) { + mIME.onExtractedTextClicked(); + return true; + } + return false; + } + + @Override public boolean onTextContextMenuItem(int id) { + if (mIME != null) { + if (mIME.onExtractTextContextMenuItem(id)) { + return true; + } + } + return super.onTextContextMenuItem(id); + } + + /** + * We are always considered to be an input method target. + */ + public boolean isInputMethodTarget() { + return true; + } + + /** + * Return true if the edit text is currently showing a scroll bar. + */ + public boolean hasVerticalScrollBar() { + return computeVerticalScrollRange() > computeVerticalScrollExtent(); + } + + /** + * Pretend like the window this view is in always has focus, so its + * highlight and cursor will be displayed. + */ + @Override public boolean hasWindowFocus() { + return this.isEnabled() ? true : false; + } + + /** + * Pretend like this view always has focus, so its + * highlight and cursor will be displayed. + */ + @Override public boolean isFocused() { + return this.isEnabled() ? true : false; + } + + /** + * Pretend like this view always has focus, so its + * highlight and cursor will be displayed. + */ + @Override public boolean hasFocus() { + return this.isEnabled() ? true : false; + } } diff --git a/core/java/android/inputmethodservice/IInputMethodSessionWrapper.java b/core/java/android/inputmethodservice/IInputMethodSessionWrapper.java index 5a85c66f42904fb47679f5a11e9a15b7c1133f05..6cf90d673579717a9571f29d785d0e04bc9ddbf4 100644 --- a/core/java/android/inputmethodservice/IInputMethodSessionWrapper.java +++ b/core/java/android/inputmethodservice/IInputMethodSessionWrapper.java @@ -30,6 +30,7 @@ class IInputMethodSessionWrapper extends IInputMethodSession.Stub private static final int DO_UPDATE_SELECTION = 90; private static final int DO_UPDATE_CURSOR = 95; private static final int DO_APP_PRIVATE_COMMAND = 100; + private static final int DO_TOGGLE_SOFT_INPUT = 105; final HandlerCaller mCaller; final InputMethodSession mInputMethodSession; @@ -106,6 +107,10 @@ class IInputMethodSessionWrapper extends IInputMethodSession.Stub mCaller.recycleArgs(args); return; } + case DO_TOGGLE_SOFT_INPUT: { + mInputMethodSession.toggleSoftInput(msg.arg1, msg.arg2); + return; + } } Log.w(TAG, "Unhandled message code: " + msg.what); } @@ -149,4 +154,8 @@ class IInputMethodSessionWrapper extends IInputMethodSession.Stub public void appPrivateCommand(String action, Bundle data) { mCaller.executeOrSendMessage(mCaller.obtainMessageOO(DO_APP_PRIVATE_COMMAND, action, data)); } + + public void toggleSoftInput(int showFlags, int hideFlags) { + mCaller.executeOrSendMessage(mCaller.obtainMessageII(DO_TOGGLE_SOFT_INPUT, showFlags, hideFlags)); + } } diff --git a/core/java/android/inputmethodservice/IInputMethodWrapper.java b/core/java/android/inputmethodservice/IInputMethodWrapper.java index 9abc23ba670327f09c0b3cadac2612f5cfc49c0a..20a05a5aea426da303be6d108642fec4bd45612a 100644 --- a/core/java/android/inputmethodservice/IInputMethodWrapper.java +++ b/core/java/android/inputmethodservice/IInputMethodWrapper.java @@ -8,9 +8,12 @@ import com.android.internal.view.IInputMethodSession; import com.android.internal.view.InputConnectionWrapper; import android.content.Context; +import android.content.pm.PackageManager; +import android.os.Binder; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; +import android.os.ResultReceiver; import android.util.Log; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputBinding; @@ -18,6 +21,11 @@ import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethod; import android.view.inputmethod.InputMethodSession; +import java.io.FileDescriptor; +import java.io.PrintWriter; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + /** * Implements the internal IInputMethod interface to convert incoming calls * on to it back to calls on the public InputMethod interface, scheduling @@ -28,6 +36,7 @@ class IInputMethodWrapper extends IInputMethod.Stub private static final String TAG = "InputMethodWrapper"; private static final boolean DEBUG = false; + private static final int DO_DUMP = 1; private static final int DO_ATTACH_TOKEN = 10; private static final int DO_SET_INPUT_CONTEXT = 20; private static final int DO_UNSET_INPUT_CONTEXT = 30; @@ -39,9 +48,14 @@ class IInputMethodWrapper extends IInputMethod.Stub private static final int DO_SHOW_SOFT_INPUT = 60; private static final int DO_HIDE_SOFT_INPUT = 70; + final AbstractInputMethodService mTarget; final HandlerCaller mCaller; final InputMethod mInputMethod; + static class Notifier { + boolean notified; + } + // NOTE: we should have a cache of these. static class InputMethodSessionCallbackWrapper implements InputMethod.SessionCallback { final Context mContext; @@ -64,7 +78,9 @@ class IInputMethodWrapper extends IInputMethod.Stub } } - public IInputMethodWrapper(Context context, InputMethod inputMethod) { + public IInputMethodWrapper(AbstractInputMethodService context, + InputMethod inputMethod) { + mTarget = context; mCaller = new HandlerCaller(context, this); mInputMethod = inputMethod; } @@ -75,6 +91,20 @@ class IInputMethodWrapper extends IInputMethod.Stub public void executeMessage(Message msg) { switch (msg.what) { + case DO_DUMP: { + HandlerCaller.SomeArgs args = (HandlerCaller.SomeArgs)msg.obj; + try { + mTarget.dump((FileDescriptor)args.arg1, + (PrintWriter)args.arg2, (String[])args.arg3); + } catch (RuntimeException e) { + ((PrintWriter)args.arg2).println("Exception: " + e); + } + synchronized (args.arg4) { + ((CountDownLatch)args.arg4).countDown(); + } + return; + } + case DO_ATTACH_TOKEN: { mInputMethod.attachToken((IBinder)msg.obj); return; @@ -86,12 +116,22 @@ class IInputMethodWrapper extends IInputMethod.Stub case DO_UNSET_INPUT_CONTEXT: mInputMethod.unbindInput(); return; - case DO_START_INPUT: - mInputMethod.startInput((EditorInfo)msg.obj); + case DO_START_INPUT: { + HandlerCaller.SomeArgs args = (HandlerCaller.SomeArgs)msg.obj; + IInputContext inputContext = (IInputContext)args.arg1; + InputConnection ic = inputContext != null + ? new InputConnectionWrapper(inputContext) : null; + mInputMethod.startInput(ic, (EditorInfo)args.arg2); return; - case DO_RESTART_INPUT: - mInputMethod.restartInput((EditorInfo)msg.obj); + } + case DO_RESTART_INPUT: { + HandlerCaller.SomeArgs args = (HandlerCaller.SomeArgs)msg.obj; + IInputContext inputContext = (IInputContext)args.arg1; + InputConnection ic = inputContext != null + ? new InputConnectionWrapper(inputContext) : null; + mInputMethod.restartInput(ic, (EditorInfo)args.arg2); return; + } case DO_CREATE_SESSION: { mInputMethod.createSession(new InputMethodSessionCallbackWrapper( mCaller.mContext, (IInputMethodCallback)msg.obj)); @@ -105,16 +145,37 @@ class IInputMethodWrapper extends IInputMethod.Stub mInputMethod.revokeSession((InputMethodSession)msg.obj); return; case DO_SHOW_SOFT_INPUT: - mInputMethod.showSoftInput( - msg.arg1 != 0 ? InputMethod.SHOW_EXPLICIT : 0); + mInputMethod.showSoftInput(msg.arg1, (ResultReceiver)msg.obj); return; case DO_HIDE_SOFT_INPUT: - mInputMethod.hideSoftInput(); + mInputMethod.hideSoftInput(msg.arg1, (ResultReceiver)msg.obj); return; } Log.w(TAG, "Unhandled message code: " + msg.what); } + @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { + if (mTarget.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) + != PackageManager.PERMISSION_GRANTED) { + + fout.println("Permission Denial: can't dump InputMethodManager from from pid=" + + Binder.getCallingPid() + + ", uid=" + Binder.getCallingUid()); + return; + } + + CountDownLatch latch = new CountDownLatch(1); + mCaller.executeOrSendMessage(mCaller.obtainMessageOOOO(DO_DUMP, + fd, fout, args, latch)); + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + fout.println("Timeout waiting for dump"); + } + } catch (InterruptedException e) { + fout.println("Interrupted waiting for dump"); + } + } + public void attachToken(IBinder token) { mCaller.executeOrSendMessage(mCaller.obtainMessageO(DO_ATTACH_TOKEN, token)); } @@ -130,12 +191,14 @@ class IInputMethodWrapper extends IInputMethod.Stub mCaller.executeOrSendMessage(mCaller.obtainMessage(DO_UNSET_INPUT_CONTEXT)); } - public void startInput(EditorInfo attribute) { - mCaller.executeOrSendMessage(mCaller.obtainMessageO(DO_START_INPUT, attribute)); + public void startInput(IInputContext inputContext, EditorInfo attribute) { + mCaller.executeOrSendMessage(mCaller.obtainMessageOO(DO_START_INPUT, + inputContext, attribute)); } - public void restartInput(EditorInfo attribute) { - mCaller.executeOrSendMessage(mCaller.obtainMessageO(DO_RESTART_INPUT, attribute)); + public void restartInput(IInputContext inputContext, EditorInfo attribute) { + mCaller.executeOrSendMessage(mCaller.obtainMessageOO(DO_RESTART_INPUT, + inputContext, attribute)); } public void createSession(IInputMethodCallback callback) { @@ -163,12 +226,13 @@ class IInputMethodWrapper extends IInputMethod.Stub } } - public void showSoftInput(boolean explicit) { - mCaller.executeOrSendMessage(mCaller.obtainMessageI(DO_SHOW_SOFT_INPUT, - explicit ? 1 : 0)); + public void showSoftInput(int flags, ResultReceiver resultReceiver) { + mCaller.executeOrSendMessage(mCaller.obtainMessageIO(DO_SHOW_SOFT_INPUT, + flags, resultReceiver)); } - public void hideSoftInput() { - mCaller.executeOrSendMessage(mCaller.obtainMessage(DO_HIDE_SOFT_INPUT)); + public void hideSoftInput(int flags, ResultReceiver resultReceiver) { + mCaller.executeOrSendMessage(mCaller.obtainMessageIO(DO_HIDE_SOFT_INPUT, + flags, resultReceiver)); } } diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java index 3a9b26a9c6f5496fc22c9890136cf161cbfa17b4..32270c46d039a8cf8b7300428449a6ce1aa4a1e7 100644 --- a/core/java/android/inputmethodservice/InputMethodService.java +++ b/core/java/android/inputmethodservice/InputMethodService.java @@ -26,7 +26,16 @@ import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.IBinder; +import android.os.ResultReceiver; +import android.os.SystemClock; +import android.provider.Settings; +import android.text.InputType; +import android.text.Layout; +import android.text.Spannable; +import android.text.method.MovementMethod; import android.util.Log; +import android.util.PrintWriterPrinter; +import android.util.Printer; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; @@ -43,7 +52,10 @@ import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethod; import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.EditorInfo; +import android.widget.Button; import android.widget.FrameLayout; +import java.io.FileDescriptor; +import java.io.PrintWriter; /** * InputMethodService provides a standard implementation of an InputMethod, @@ -51,6 +63,22 @@ import android.widget.FrameLayout; * base class {@link AbstractInputMethodService} and the {@link InputMethod} * interface for more information on the basics of writing input methods. * + *

      In addition to the normal Service lifecycle methods, this class + * introduces some new specific callbacks that most subclasses will want + * to make use of:

      + *
        + *
      • {@link #onInitializeInterface()} for user-interface initialization, + * in particular to deal with configuration changes while the service is + * running. + *
      • {@link #onBindInput} to find out about switching to a new client. + *
      • {@link #onStartInput} to deal with an input session starting with + * the client. + *
      • {@link #onCreateInputView()}, {@link #onCreateCandidatesView()}, + * and {@link #onCreateExtractTextView()} for non-demand generation of the UI. + *
      • {@link #onStartInputView(EditorInfo, boolean)} to deal with input + * starting within the input area of the IME. + *
      + * *

      An input method has significant discretion in how it goes about its * work: the {@link android.inputmethodservice.InputMethodService} provides * a basic framework for standard UI elements (input view, candidates view, @@ -181,9 +209,12 @@ public class InputMethodService extends AbstractInputMethodService { static final String TAG = "InputMethodService"; static final boolean DEBUG = false; + InputMethodManager mImm; + LayoutInflater mInflater; View mRootView; SoftInputWindow mWindow; + boolean mInitialized; boolean mWindowCreated; boolean mWindowAdded; boolean mWindowVisible; @@ -196,16 +227,25 @@ public class InputMethodService extends AbstractInputMethodService { InputBinding mInputBinding; InputConnection mInputConnection; boolean mInputStarted; + boolean mInputViewStarted; + boolean mCandidatesViewStarted; + InputConnection mStartedInputConnection; EditorInfo mInputEditorInfo; + int mShowInputFlags; boolean mShowInputRequested; boolean mLastShowInputRequested; - boolean mShowCandidatesRequested; + int mCandidatesVisibility; + CompletionInfo[] mCurCompletions; + + boolean mShowInputForced; boolean mFullscreenApplied; boolean mIsFullscreen; View mExtractView; ExtractEditText mExtractEditText; + ViewGroup mExtractAccessories; + Button mExtractAction; ExtractedText mExtractedText; int mExtractedToken; @@ -236,6 +276,21 @@ public class InputMethodService extends AbstractInputMethodService { } }; + final View.OnClickListener mActionClickListener = new View.OnClickListener() { + public void onClick(View v) { + final EditorInfo ei = getCurrentInputEditorInfo(); + final InputConnection ic = getCurrentInputConnection(); + if (ei != null && ic != null) { + if (ei.actionId != 0) { + ic.performEditorAction(ei.actionId); + } else if ((ei.imeOptions&EditorInfo.IME_MASK_ACTION) + != EditorInfo.IME_ACTION_NONE) { + ic.performEditorAction(ei.imeOptions&EditorInfo.IME_MASK_ACTION); + } + } + } + }; + /** * Concrete implementation of * {@link AbstractInputMethodService.AbstractInputMethodImpl} that provides @@ -262,6 +317,9 @@ public class InputMethodService extends AbstractInputMethodService { mInputConnection = binding.getConnection(); if (DEBUG) Log.v(TAG, "bindInput(): binding=" + binding + " ic=" + mInputConnection); + InputConnection ic = getCurrentInputConnection(); + if (ic != null) ic.reportFullscreenMode(mIsFullscreen); + initialize(); onBindInput(); } @@ -277,31 +335,50 @@ public class InputMethodService extends AbstractInputMethodService { mInputConnection = null; } - public void startInput(EditorInfo attribute) { + public void startInput(InputConnection ic, EditorInfo attribute) { if (DEBUG) Log.v(TAG, "startInput(): editor=" + attribute); - doStartInput(attribute, false); + doStartInput(ic, attribute, false); } - public void restartInput(EditorInfo attribute) { + public void restartInput(InputConnection ic, EditorInfo attribute) { if (DEBUG) Log.v(TAG, "restartInput(): editor=" + attribute); - doStartInput(attribute, true); + doStartInput(ic, attribute, true); } /** * Handle a request by the system to hide the soft input area. */ - public void hideSoftInput() { + public void hideSoftInput(int flags, ResultReceiver resultReceiver) { if (DEBUG) Log.v(TAG, "hideSoftInput()"); + boolean wasVis = isInputViewShown(); + mShowInputFlags = 0; mShowInputRequested = false; + mShowInputForced = false; hideWindow(); + if (resultReceiver != null) { + resultReceiver.send(wasVis != isInputViewShown() + ? InputMethodManager.RESULT_HIDDEN + : (wasVis ? InputMethodManager.RESULT_UNCHANGED_SHOWN + : InputMethodManager.RESULT_UNCHANGED_HIDDEN), null); + } } /** * Handle a request by the system to show the soft input area. */ - public void showSoftInput(int flags) { + public void showSoftInput(int flags, ResultReceiver resultReceiver) { if (DEBUG) Log.v(TAG, "showSoftInput()"); - onShowRequested(flags); + boolean wasVis = isInputViewShown(); + mShowInputFlags = 0; + if (onShowInputRequested(flags, false)) { + showWindow(true); + } + if (resultReceiver != null) { + resultReceiver.send(wasVis != isInputViewShown() + ? InputMethodManager.RESULT_SHOWN + : (wasVis ? InputMethodManager.RESULT_UNCHANGED_SHOWN + : InputMethodManager.RESULT_UNCHANGED_HIDDEN), null); + } } } @@ -316,8 +393,7 @@ public class InputMethodService extends AbstractInputMethodService { return; } if (DEBUG) Log.v(TAG, "finishInput() in " + this); - onFinishInput(); - mInputStarted = false; + doFinishInput(); } /** @@ -328,6 +404,7 @@ public class InputMethodService extends AbstractInputMethodService { if (!isEnabled()) { return; } + mCurCompletions = completions; onDisplayCompletions(completions); } @@ -377,6 +454,13 @@ public class InputMethodService extends AbstractInputMethodService { } InputMethodService.this.onAppPrivateCommand(action, data); } + + /** + * + */ + public void toggleSoftInput(int showFlags, int hideFlags) { + InputMethodService.this.onToggleSoftInput(showFlags, hideFlags); + } } /** @@ -391,7 +475,7 @@ public class InputMethodService extends AbstractInputMethodService { * of the application behind. This value is relative to the top edge * of the input method window. */ - int contentTopInsets; + public int contentTopInsets; /** * This is the top part of the UI that is visibly covering the @@ -404,7 +488,7 @@ public class InputMethodService extends AbstractInputMethodService { * needed to make the focus visible. This value is relative to the top edge * of the input method window. */ - int visibleTopInsets; + public int visibleTopInsets; /** * Option for {@link #touchableInsets}: the entire window frame @@ -437,6 +521,7 @@ public class InputMethodService extends AbstractInputMethodService { @Override public void onCreate() { super.onCreate(); + mImm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); mInflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); mWindow = new SoftInputWindow(this); @@ -444,20 +529,42 @@ public class InputMethodService extends AbstractInputMethodService { mWindow.getWindow().setLayout(FILL_PARENT, WRAP_CONTENT); } + /** + * This is a hook that subclasses can use to perform initialization of + * their interface. It is called for you prior to any of your UI objects + * being created, both after the service is first created and after a + * configuration change happens. + */ + public void onInitializeInterface() { + } + + void initialize() { + if (!mInitialized) { + mInitialized = true; + onInitializeInterface(); + } + } + void initViews() { - mWindowVisible = false; + mInitialized = false; mWindowCreated = false; mShowInputRequested = false; - mShowCandidatesRequested = false; + mShowInputForced = false; mRootView = mInflater.inflate( com.android.internal.R.layout.input_method, null); mWindow.setContentView(mRootView); mRootView.getViewTreeObserver().addOnComputeInternalInsetsListener(mInsetsComputer); - + if (Settings.System.getInt(getContentResolver(), + Settings.System.FANCY_IME_ANIMATIONS, 0) != 0) { + mWindow.getWindow().setWindowAnimations( + com.android.internal.R.style.Animation_InputMethodFancy); + } mExtractFrame = (FrameLayout)mRootView.findViewById(android.R.id.extractArea); mExtractView = null; mExtractEditText = null; + mExtractAccessories = null; + mExtractAction = null; mFullscreenApplied = false; mCandidatesFrame = (FrameLayout)mRootView.findViewById(android.R.id.candidatesArea); @@ -466,7 +573,8 @@ public class InputMethodService extends AbstractInputMethodService { mIsInputViewShown = false; mExtractFrame.setVisibility(View.GONE); - mCandidatesFrame.setVisibility(View.INVISIBLE); + mCandidatesVisibility = getCandidatesHiddenVisibility(); + mCandidatesFrame.setVisibility(mCandidatesVisibility); mInputFrame.setVisibility(View.GONE); } @@ -486,26 +594,48 @@ public class InputMethodService extends AbstractInputMethodService { * regenerating the input method UI as a result of the configuration * change, so you can rely on your {@link #onCreateInputView} and * other methods being called as appropriate due to a configuration change. + * + *

      When a configuration change does happen, + * {@link #onInitializeInterface()} is guaranteed to be called the next + * time prior to any of the other input or UI creation callbacks. The + * following will be called immediately depending if appropriate for current + * state: {@link #onStartInput} if input is active, and + * {@link #onCreateInputView} and {@link #onStartInputView} and related + * appropriate functions if the UI is displayed. */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean visible = mWindowVisible; + int showFlags = mShowInputFlags; boolean showingInput = mShowInputRequested; - boolean showingCandidates = mShowCandidatesRequested; + CompletionInfo[] completions = mCurCompletions; initViews(); + mInputViewStarted = false; + mCandidatesViewStarted = false; + if (mInputStarted) { + doStartInput(getCurrentInputConnection(), + getCurrentInputEditorInfo(), true); + } if (visible) { - if (showingCandidates) { - setCandidatesViewShown(true); - } if (showingInput) { - // If we are showing the full soft keyboard, then go through - // this path to take care of current decisions about fullscreen - // etc. - onShowRequested(InputMethod.SHOW_EXPLICIT); - } else { - // Otherwise just put it back for its candidates. + // If we were last showing the soft keyboard, try to do so again. + if (onShowInputRequested(showFlags, true)) { + showWindow(true); + if (completions != null) { + mCurCompletions = completions; + onDisplayCompletions(completions); + } + } else { + hideWindow(); + } + } else if (mCandidatesVisibility == View.VISIBLE) { + // If the candidates are currently visible, make sure the + // window is shown for them. showWindow(false); + } else { + // Otherwise hide the window. + hideWindow(); } } } @@ -568,6 +698,10 @@ public class InputMethodService extends AbstractInputMethodService { * the input method, or null if there is none. */ public InputConnection getCurrentInputConnection() { + InputConnection ic = mStartedInputConnection; + if (ic != null) { + return ic; + } return mInputConnection; } @@ -593,7 +727,10 @@ public class InputMethodService extends AbstractInputMethodService { if (mIsFullscreen != isFullscreen || !mFullscreenApplied) { changed = true; mIsFullscreen = isFullscreen; + InputConnection ic = getCurrentInputConnection(); + if (ic != null) ic.reportFullscreenMode(isFullscreen); mFullscreenApplied = true; + initialize(); Drawable bg = onCreateBackgroundDrawable(); if (bg == null) { // We need to give the window a real drawable, so that it @@ -609,7 +746,7 @@ public class InputMethodService extends AbstractInputMethodService { setExtractView(v); } } - startExtractingText(); + startExtractingText(false); } } @@ -708,6 +845,7 @@ public class InputMethodService extends AbstractInputMethodService { mIsInputViewShown = isShown; mInputFrame.setVisibility(isShown ? View.VISIBLE : View.GONE); if (mInputView == null) { + initialize(); View v = onCreateInputView(); if (v != null) { setInputView(v); @@ -716,13 +854,20 @@ public class InputMethodService extends AbstractInputMethodService { } } + /** + * Returns true if we have been asked to show our input view. + */ + public boolean isShowInputRequested() { + return mShowInputRequested; + } + /** * Return whether the soft input view is currently shown to the * user. This is the state that was last determined and * applied by {@link #updateInputViewShown()}. */ public boolean isInputViewShown() { - return mIsInputViewShown; + return mIsInputViewShown && mWindowVisible; } /** @@ -744,9 +889,10 @@ public class InputMethodService extends AbstractInputMethodService { * it is hidden. */ public void setCandidatesViewShown(boolean shown) { - if (mShowCandidatesRequested != shown) { - mCandidatesFrame.setVisibility(shown ? View.VISIBLE : View.INVISIBLE); - mShowCandidatesRequested = shown; + int vis = shown ? View.VISIBLE : getCandidatesHiddenVisibility(); + if (mCandidatesVisibility != vis) { + mCandidatesFrame.setVisibility(vis); + mCandidatesVisibility = vis; } if (!mShowInputRequested && mWindowVisible != shown) { // If we are being asked to show the candidates view while the app @@ -760,11 +906,27 @@ public class InputMethodService extends AbstractInputMethodService { } } - public void setStatusIcon(int iconResId) { + /** + * Returns the visibility mode (either {@link View#INVISIBLE View.INVISIBLE} + * or {@link View#GONE View.GONE}) of the candidates view when it is not + * shown. The default implementation returns GONE when in fullscreen mode, + * otherwise VISIBLE. Be careful if you change this to return GONE in + * other situations -- if showing or hiding the candidates view causes + * your window to resize, this can cause temporary drawing artifacts as + * the resize takes place. + */ + public int getCandidatesHiddenVisibility() { + return isFullscreenMode() ? View.GONE : View.INVISIBLE; + } + + public void showStatusIcon(int iconResId) { mStatusIcon = iconResId; - if (mInputConnection != null && mWindowVisible) { - mInputConnection.showStatusIcon(getPackageName(), iconResId); - } + mImm.showStatusIcon(mToken, getPackageName(), iconResId); + } + + public void hideStatusIcon() { + mStatusIcon = 0; + mImm.hideStatusIcon(mToken); } /** @@ -775,22 +937,30 @@ public class InputMethodService extends AbstractInputMethodService { * @param id Unique identifier of the new input method ot start. */ public void switchInputMethod(String id) { - ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)) - .setInputMethod(mToken, id); + mImm.setInputMethod(mToken, id); } public void setExtractView(View view) { mExtractFrame.removeAllViews(); mExtractFrame.addView(view, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT)); + ViewGroup.LayoutParams.FILL_PARENT)); mExtractView = view; if (view != null) { mExtractEditText = (ExtractEditText)view.findViewById( com.android.internal.R.id.inputExtractEditText); - startExtractingText(); + mExtractEditText.setIME(this); + mExtractAction = (Button)view.findViewById( + com.android.internal.R.id.inputExtractAction); + if (mExtractAction != null) { + mExtractAccessories = (ViewGroup)view.findViewById( + com.android.internal.R.id.inputExtractAccessories); + } + startExtractingText(false); } else { mExtractEditText = null; + mExtractAccessories = null; + mExtractAction = null; } } @@ -889,28 +1059,112 @@ public class InputMethodService extends AbstractInputMethodService { public void onStartInputView(EditorInfo info, boolean restarting) { } + /** + * Called when the input view is being hidden from the user. This will + * be called either prior to hiding the window, or prior to switching to + * another target for editing. + * + *

      The default + * implementation uses the InputConnection to clear any active composing + * text; you can override this (not calling the base class implementation) + * to perform whatever behavior you would like. + * + * @param finishingInput If true, {@link #onFinishInput} will be + * called immediately after. + */ + public void onFinishInputView(boolean finishingInput) { + if (!finishingInput) { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.finishComposingText(); + } + } + } + + /** + * Called when only the candidates view has been shown for showing + * processing as the user enters text through a hard keyboard. + * This will always be called after {@link #onStartInput}, + * allowing you to do your general setup there and just view-specific + * setup here. You are guaranteed that {@link #onCreateCandidatesView()} + * will have been called some time before this function is called. + * + *

      Note that this will not be called when the input method + * is running in full editing mode, and thus receiving + * {@link #onStartInputView} to initiate that operation. This is only + * for the case when candidates are being shown while the input method + * editor is hidden but wants to show its candidates UI as text is + * entered through some other mechanism. + * + * @param info Description of the type of text being edited. + * @param restarting Set to true if we are restarting input on the + * same text field as before. + */ + public void onStartCandidatesView(EditorInfo info, boolean restarting) { + } + + /** + * Called when the candidates view is being hidden from the user. This will + * be called either prior to hiding the window, or prior to switching to + * another target for editing. + * + *

      The default + * implementation uses the InputConnection to clear any active composing + * text; you can override this (not calling the base class implementation) + * to perform whatever behavior you would like. + * + * @param finishingInput If true, {@link #onFinishInput} will be + * called immediately after. + */ + public void onFinishCandidatesView(boolean finishingInput) { + if (!finishingInput) { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.finishComposingText(); + } + } + } + /** * The system has decided that it may be time to show your input method. * This is called due to a corresponding call to your - * {@link InputMethod#showSoftInput(int) InputMethod.showSoftInput(int)} - * method. The default implementation simply calls - * {@link #showWindow(boolean)}, except if the - * {@link InputMethod#SHOW_EXPLICIT InputMethod.SHOW_EXPLICIT} flag is - * not set and the input method is running in fullscreen mode. + * {@link InputMethod#showSoftInput InputMethod.showSoftInput()} + * method. The default implementation uses + * {@link #onEvaluateInputViewShown()}, {@link #onEvaluateFullscreenMode()}, + * and the current configuration to decide whether the input view should + * be shown at this point. * * @param flags Provides additional information about the show request, - * as per {@link InputMethod#showSoftInput(int) InputMethod.showSoftInput(int)}. + * as per {@link InputMethod#showSoftInput InputMethod.showSoftInput()}. + * @param configChange This is true if we are re-showing due to a + * configuration change. + * @return Returns true to indicate that the window should be shown. */ - public void onShowRequested(int flags) { + public boolean onShowInputRequested(int flags, boolean configChange) { if (!onEvaluateInputViewShown()) { - return; + return false; } - if ((flags&InputMethod.SHOW_EXPLICIT) == 0 && onEvaluateFullscreenMode()) { - // Don't show if this is not explicit requested by the user and - // the input method is fullscreen. That would be too disruptive. - return; + if ((flags&InputMethod.SHOW_EXPLICIT) == 0) { + if (!configChange && onEvaluateFullscreenMode()) { + // Don't show if this is not explicitly requested by the user and + // the input method is fullscreen. That would be too disruptive. + // However, we skip this change for a config change, since if + // the IME is already shown we do want to go into fullscreen + // mode at this point. + return false; + } + Configuration config = getResources().getConfiguration(); + if (config.keyboard != Configuration.KEYBOARD_NOKEYS) { + // And if the device has a hard keyboard, even if it is + // currently hidden, don't show the input method implicitly. + // These kinds of devices don't need it that much. + return false; + } } - showWindow(true); + if ((flags&InputMethod.SHOW_FORCED) != 0) { + mShowInputForced = true; + } + return true; } public void showWindow(boolean showInput) { @@ -935,45 +1189,76 @@ public class InputMethodService extends AbstractInputMethodService { } if (DEBUG) Log.v(TAG, "showWindow: updating UI"); + initialize(); updateFullscreenMode(); updateInputViewShown(); if (!mWindowAdded || !mWindowCreated) { mWindowAdded = true; mWindowCreated = true; + initialize(); + if (DEBUG) Log.v(TAG, "CALL: onCreateCandidatesView"); View v = onCreateCandidatesView(); if (DEBUG) Log.v(TAG, "showWindow: candidates=" + v); if (v != null) { setCandidatesView(v); } } - if (doShowInput) { - if (mInputStarted) { - if (DEBUG) Log.v(TAG, "showWindow: starting input view"); + if (mShowInputRequested) { + if (!mInputViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onStartInputView"); + mInputViewStarted = true; onStartInputView(mInputEditorInfo, false); } - startExtractingText(); + } else if (!mCandidatesViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onStartCandidatesView"); + mCandidatesViewStarted = true; + onStartCandidatesView(mInputEditorInfo, false); + } + + if (doShowInput) { + startExtractingText(false); } if (!wasVisible) { if (DEBUG) Log.v(TAG, "showWindow: showing!"); + onWindowShown(); mWindow.show(); - if (mInputConnection != null) { - mInputConnection.showStatusIcon(getPackageName(), mStatusIcon); - } } } public void hideWindow() { + if (mInputViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishInputView"); + onFinishInputView(false); + } else if (mCandidatesViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishCandidatesView"); + onFinishCandidatesView(false); + } + mInputViewStarted = false; + mCandidatesViewStarted = false; if (mWindowVisible) { mWindow.hide(); mWindowVisible = false; - if (mInputConnection != null) { - mInputConnection.hideStatusIcon(); - } + onWindowHidden(); } } + /** + * Called when the input method window has been shown to the user, after + * previously not being visible. This is done after all of the UI setup + * for the window has occurred (creating its views etc). + */ + public void onWindowShown() { + } + + /** + * Called when the input method window has been hidden from the user, + * after previously being visible. + */ + public void onWindowHidden() { + } + /** * Called when a new client has bound to the input method. This * may be followed by a series of {@link #onStartInput(EditorInfo, boolean)} @@ -1008,18 +1293,46 @@ public class InputMethodService extends AbstractInputMethodService { public void onStartInput(EditorInfo attribute, boolean restarting) { } - void doStartInput(EditorInfo attribute, boolean restarting) { - if (mInputStarted && !restarting) { + void doFinishInput() { + if (mInputViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishInputView"); + onFinishInputView(true); + } else if (mCandidatesViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishCandidatesView"); + onFinishCandidatesView(true); + } + mInputViewStarted = false; + mCandidatesViewStarted = false; + if (mInputStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishInput"); onFinishInput(); } + mInputStarted = false; + mStartedInputConnection = null; + mCurCompletions = null; + } + + void doStartInput(InputConnection ic, EditorInfo attribute, boolean restarting) { + if (!restarting) { + doFinishInput(); + } mInputStarted = true; + mStartedInputConnection = ic; mInputEditorInfo = attribute; + initialize(); + if (DEBUG) Log.v(TAG, "CALL: onStartInput"); onStartInput(attribute, restarting); if (mWindowVisible) { if (mShowInputRequested) { + if (DEBUG) Log.v(TAG, "CALL: onStartInputView"); + mInputViewStarted = true; onStartInputView(mInputEditorInfo, restarting); + startExtractingText(true); + } else if (mCandidatesVisibility == View.VISIBLE) { + if (DEBUG) Log.v(TAG, "CALL: onStartCandidatesView"); + mCandidatesViewStarted = true; + onStartCandidatesView(mInputEditorInfo, restarting); } - startExtractingText(); } } @@ -1029,8 +1342,17 @@ public class InputMethodService extends AbstractInputMethodService { * {@link #onStartInput(EditorInfo, boolean)} to perform input in a * new editor, or the input method may be left idle. This method is * not called when input restarts in the same editor. + * + *

      The default + * implementation uses the InputConnection to clear any active composing + * text; you can override this (not calling the base class implementation) + * to perform whatever behavior you would like. */ public void onFinishInput() { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.finishComposingText(); + } } /** @@ -1055,9 +1377,11 @@ public class InputMethodService extends AbstractInputMethodService { if (mExtractedToken != token) { return; } - if (mExtractEditText != null && text != null) { - mExtractedText = text; - mExtractEditText.setExtractedText(text); + if (text != null) { + if (mExtractEditText != null) { + mExtractedText = text; + mExtractEditText.setExtractedText(text); + } } } @@ -1073,9 +1397,19 @@ public class InputMethodService extends AbstractInputMethodService { public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { - if (mExtractEditText != null && mExtractedText != null) { + final ExtractEditText eet = mExtractEditText; + if (eet != null && isFullscreenMode() && mExtractedText != null) { final int off = mExtractedText.startOffset; - mExtractEditText.setSelection(newSelStart-off, newSelEnd-off); + eet.startInternalChanges(); + newSelStart -= off; + newSelEnd -= off; + final int len = eet.getText().length(); + if (newSelStart < 0) newSelStart = 0; + else if (newSelStart > len) newSelStart = len; + if (newSelEnd < 0) newSelEnd = 0; + else if (newSelEnd > len) newSelEnd = len; + eet.setSelection(newSelStart, newSelEnd); + eet.finishInternalChanges(); } } @@ -1095,38 +1429,91 @@ public class InputMethodService extends AbstractInputMethodService { * 0 or have the {@link InputMethodManager#HIDE_IMPLICIT_ONLY * InputMethodManager.HIDE_IMPLICIT_ONLY} bit set. */ - public void dismissSoftInput(int flags) { - ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)) - .hideSoftInputFromInputMethod(mToken, flags); + public void requestHideSelf(int flags) { + mImm.hideSoftInputFromInputMethod(mToken, flags); + } + + /** + * Show the input method. This is a call back to the + * IMF to handle showing the input method. + * Close this input method's soft input area, removing it from the display. + * The input method will continue running, but the user can no longer use + * it to generate input by touching the screen. + * @param flags Provides additional operating flags. Currently may be + * 0 or have the {@link InputMethodManager#SHOW_FORCED + * InputMethodManager.} bit set. + */ + private void requestShowSelf(int flags) { + mImm.showSoftInputFromInputMethod(mToken, flags); } + /** + * Override this to intercept key down events before they are processed by the + * application. If you return true, the application will not itself + * process the event. If you return true, the normal application processing + * will occur as if the IME had not seen the event at all. + * + *

      The default implementation intercepts {@link KeyEvent#KEYCODE_BACK + * KeyEvent.KEYCODE_BACK} to hide the current IME UI if it is shown. In + * additional, in fullscreen mode only, it will consume DPAD movement + * events to move the cursor in the extracted text view, not allowing + * them to perform navigation in the underlying application. + */ public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if (mShowInputRequested) { // If the soft input area is shown, back closes it and we // consume the back key. - dismissSoftInput(0); + requestHideSelf(0); return true; - } - if (mShowCandidatesRequested) { - // If the candidates are shown, we just want to make sure - // they are now hidden but otherwise let the app execute - // the back. - // XXX this needs better interaction with the soft input - // implementation. - //setCandidatesViewShown(false); + } else if (mWindowVisible) { + if (mCandidatesVisibility == View.VISIBLE) { + // If we are showing candidates even if no input area, then + // hide them. + setCandidatesViewShown(false); + return true; + } else { + // If we have the window visible for some other reason -- + // most likely to show candidates -- then just get rid + // of it. This really shouldn't happen, but just in case... + hideWindow(); + return true; + } } } - return false; + return doMovementKey(keyCode, event, MOVEMENT_DOWN); } + /** + * Override this to intercept special key multiple events before they are + * processed by the + * application. If you return true, the application will not itself + * process the event. If you return true, the normal application processing + * will occur as if the IME had not seen the event at all. + * + *

      The default implementation always returns false, except when + * in fullscreen mode, where it will consume DPAD movement + * events to move the cursor in the extracted text view, not allowing + * them to perform navigation in the underlying application. + */ public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) { - return false; + return doMovementKey(keyCode, event, count); } + /** + * Override this to intercept key up events before they are processed by the + * application. If you return true, the application will not itself + * process the event. If you return true, the normal application processing + * will occur as if the IME had not seen the event at all. + * + *

      The default implementation always returns false, except when + * in fullscreen mode, where it will consume DPAD movement + * events to move the cursor in the extracted text view, not allowing + * them to perform navigation in the underlying application. + */ public boolean onKeyUp(int keyCode, KeyEvent event) { - return false; + return doMovementKey(keyCode, event, MOVEMENT_UP); } public boolean onTrackballEvent(MotionEvent event) { @@ -1136,21 +1523,415 @@ public class InputMethodService extends AbstractInputMethodService { public void onAppPrivateCommand(String action, Bundle data) { } - void startExtractingText() { - if (mExtractEditText != null && getCurrentInputStarted() + /** + * Handle a request by the system to toggle the soft input area. + */ + private void onToggleSoftInput(int showFlags, int hideFlags) { + if (DEBUG) Log.v(TAG, "toggleSoftInput()"); + if (isInputViewShown()) { + requestHideSelf(hideFlags); + } else { + requestShowSelf(showFlags); + } + } + + static final int MOVEMENT_DOWN = -1; + static final int MOVEMENT_UP = -2; + + void reportExtractedMovement(int keyCode, int count) { + int dx = 0, dy = 0; + switch (keyCode) { + case KeyEvent.KEYCODE_DPAD_LEFT: + dx = -count; + break; + case KeyEvent.KEYCODE_DPAD_RIGHT: + dx = count; + break; + case KeyEvent.KEYCODE_DPAD_UP: + dy = -count; + break; + case KeyEvent.KEYCODE_DPAD_DOWN: + dy = count; + break; + } + onExtractedCursorMovement(dx, dy); + } + + boolean doMovementKey(int keyCode, KeyEvent event, int count) { + final ExtractEditText eet = mExtractEditText; + if (isFullscreenMode() && isInputViewShown() && eet != null) { + // If we are in fullscreen mode, the cursor will move around + // the extract edit text, but should NOT cause focus to move + // to other fields. + MovementMethod movement = eet.getMovementMethod(); + Layout layout = eet.getLayout(); + if (movement != null && layout != null) { + // We want our own movement method to handle the key, so the + // cursor will properly move in our own word wrapping. + if (count == MOVEMENT_DOWN) { + if (movement.onKeyDown(eet, + (Spannable)eet.getText(), keyCode, event)) { + reportExtractedMovement(keyCode, 1); + return true; + } + } else if (count == MOVEMENT_UP) { + if (movement.onKeyUp(eet, + (Spannable)eet.getText(), keyCode, event)) { + return true; + } + } else { + if (movement.onKeyOther(eet, (Spannable)eet.getText(), event)) { + reportExtractedMovement(keyCode, count); + } else { + KeyEvent down = new KeyEvent(event, KeyEvent.ACTION_DOWN); + if (movement.onKeyDown(eet, + (Spannable)eet.getText(), keyCode, down)) { + KeyEvent up = new KeyEvent(event, KeyEvent.ACTION_UP); + movement.onKeyUp(eet, + (Spannable)eet.getText(), keyCode, up); + while (--count > 0) { + movement.onKeyDown(eet, + (Spannable)eet.getText(), keyCode, down); + movement.onKeyUp(eet, + (Spannable)eet.getText(), keyCode, up); + } + reportExtractedMovement(keyCode, count); + } + } + } + } + // Regardless of whether the movement method handled the key, + // we never allow DPAD navigation to the application. + switch (keyCode) { + case KeyEvent.KEYCODE_DPAD_LEFT: + case KeyEvent.KEYCODE_DPAD_RIGHT: + case KeyEvent.KEYCODE_DPAD_UP: + case KeyEvent.KEYCODE_DPAD_DOWN: + return true; + } + } + + return false; + } + + /** + * Send the given key event code (as defined by {@link KeyEvent}) to the + * current input connection is a key down + key up event pair. The sent + * events have {@link KeyEvent#FLAG_SOFT_KEYBOARD KeyEvent.FLAG_SOFT_KEYBOARD} + * set, so that the recipient can identify them as coming from a software + * input method, and + * {@link KeyEvent#FLAG_KEEP_TOUCH_MODE KeyEvent.FLAG_KEEP_TOUCH_MODE}, so + * that they don't impact the current touch mode of the UI. + * + * @param keyEventCode The raw key code to send, as defined by + * {@link KeyEvent}. + */ + public void sendDownUpKeyEvents(int keyEventCode) { + InputConnection ic = getCurrentInputConnection(); + if (ic == null) return; + long eventTime = SystemClock.uptimeMillis(); + ic.sendKeyEvent(new KeyEvent(eventTime, eventTime, + KeyEvent.ACTION_DOWN, keyEventCode, 0, 0, 0, 0, + KeyEvent.FLAG_SOFT_KEYBOARD|KeyEvent.FLAG_KEEP_TOUCH_MODE)); + ic.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime, + KeyEvent.ACTION_UP, keyEventCode, 0, 0, 0, 0, + KeyEvent.FLAG_SOFT_KEYBOARD|KeyEvent.FLAG_KEEP_TOUCH_MODE)); + } + + /** + * Ask the input target to execute its default action via + * {@link InputConnection#performEditorAction + * InputConnection.performEditorAction()}. + * + * @param fromEnterKey If true, this will be executed as if the user had + * pressed an enter key on the keyboard, that is it will not + * be done if the editor has set {@link EditorInfo#IME_FLAG_NO_ENTER_ACTION + * EditorInfo.IME_FLAG_NO_ENTER_ACTION}. If false, the action will be + * sent regardless of how the editor has set that flag. + * + * @return Returns a boolean indicating whether an action has been sent. + * If false, either the editor did not specify a default action or it + * does not want an action from the enter key. If true, the action was + * sent (or there was no input connection at all). + */ + public boolean sendDefaultEditorAction(boolean fromEnterKey) { + EditorInfo ei = getCurrentInputEditorInfo(); + if (ei != null && + (!fromEnterKey || (ei.imeOptions & + EditorInfo.IME_FLAG_NO_ENTER_ACTION) == 0) && + (ei.imeOptions & EditorInfo.IME_MASK_ACTION) != + EditorInfo.IME_ACTION_NONE) { + // If the enter key was pressed, and the editor has a default + // action associated with pressing enter, then send it that + // explicit action instead of the key event. + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.performEditorAction(ei.imeOptions&EditorInfo.IME_MASK_ACTION); + } + return true; + } + + return false; + } + + /** + * Send the given UTF-16 character to the current input connection. Most + * characters will be delivered simply by calling + * {@link InputConnection#commitText InputConnection.commitText()} with + * the character; some, however, may be handled different. In particular, + * the enter character ('\n') will either be delivered as an action code + * or a raw key event, as appropriate. + * + * @param charCode The UTF-16 character code to send. + */ + public void sendKeyChar(char charCode) { + switch (charCode) { + case '\n': // Apps may be listening to an enter key to perform an action + if (!sendDefaultEditorAction(true)) { + sendDownUpKeyEvents(KeyEvent.KEYCODE_ENTER); + } + break; + default: + // Make sure that digits go through any text watcher on the client side. + if (charCode >= '0' && charCode <= '9') { + sendDownUpKeyEvents(charCode - '0' + KeyEvent.KEYCODE_0); + } else { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.commitText(String.valueOf((char) charCode), 1); + } + } + break; + } + } + + /** + * This is called when the user has moved the cursor in the extracted + * text view, when running in fullsreen mode. The default implementation + * performs the corresponding selection change on the underlying text + * editor. + */ + public void onExtractedSelectionChanged(int start, int end) { + InputConnection conn = getCurrentInputConnection(); + if (conn != null) { + conn.setSelection(start, end); + } + } + + /** + * This is called when the user has clicked on the extracted text view, + * when running in fullscreen mode. The default implementation hides + * the candidates view when this happens, but only if the extracted text + * editor has a vertical scroll bar because its text doesn't fit. + * Re-implement this to provide whatever behavior you want. + */ + public void onExtractedTextClicked() { + if (mExtractEditText == null) { + return; + } + if (mExtractEditText.hasVerticalScrollBar()) { + setCandidatesViewShown(false); + } + } + + /** + * This is called when the user has performed a cursor movement in the + * extracted text view, when it is running in fullscreen mode. The default + * implementation hides the candidates view when a vertical movement + * happens, but only if the extracted text editor has a vertical scroll bar + * because its text doesn't fit. + * Re-implement this to provide whatever behavior you want. + * @param dx The amount of cursor movement in the x dimension. + * @param dy The amount of cursor movement in the y dimension. + */ + public void onExtractedCursorMovement(int dx, int dy) { + if (mExtractEditText == null || dy == 0) { + return; + } + if (mExtractEditText.hasVerticalScrollBar()) { + setCandidatesViewShown(false); + } + } + + /** + * This is called when the user has selected a context menu item from the + * extracted text view, when running in fullscreen mode. The default + * implementation sends this action to the current InputConnection's + * {@link InputConnection#performContextMenuAction(int)}, for it + * to be processed in underlying "real" editor. Re-implement this to + * provide whatever behavior you want. + */ + public boolean onExtractTextContextMenuItem(int id) { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.performContextMenuAction(id); + } + return true; + } + + /** + * Return text that can be used as a button label for the given + * {@link EditorInfo#imeOptions EditorInfo.imeOptions}. Returns null + * if there is no action requested. Note that there is no guarantee that + * the returned text will be relatively short, so you probably do not + * want to use it as text on a soft keyboard key label. + * + * @param imeOptions The value from @link EditorInfo#imeOptions EditorInfo.imeOptions}. + * + * @return Returns a label to use, or null if there is no action. + */ + public CharSequence getTextForImeAction(int imeOptions) { + switch (imeOptions&EditorInfo.IME_MASK_ACTION) { + case EditorInfo.IME_ACTION_NONE: + return null; + case EditorInfo.IME_ACTION_GO: + return getText(com.android.internal.R.string.ime_action_go); + case EditorInfo.IME_ACTION_SEARCH: + return getText(com.android.internal.R.string.ime_action_search); + case EditorInfo.IME_ACTION_SEND: + return getText(com.android.internal.R.string.ime_action_send); + case EditorInfo.IME_ACTION_NEXT: + return getText(com.android.internal.R.string.ime_action_next); + case EditorInfo.IME_ACTION_DONE: + return getText(com.android.internal.R.string.ime_action_done); + default: + return getText(com.android.internal.R.string.ime_action_default); + } + } + + /** + * Called when it is time to update the actions available from a full-screen + * IME. You do not need to deal with this if you are using the standard + * full screen extract UI. If replacing it, you will need to re-implement + * this to put the action in your own UI and handle it. + */ + public void onUpdateExtractingAccessories(EditorInfo ei) { + if (mExtractAccessories == null) { + return; + } + final boolean hasAction = ei.actionLabel != null || ( + (ei.imeOptions&EditorInfo.IME_MASK_ACTION) != EditorInfo.IME_ACTION_NONE && + (ei.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0); + if (hasAction) { + mExtractAccessories.setVisibility(View.VISIBLE); + if (ei.actionLabel != null) { + mExtractAction.setText(ei.actionLabel); + } else { + mExtractAction.setText(getTextForImeAction(ei.imeOptions)); + } + mExtractAction.setOnClickListener(mActionClickListener); + } else { + mExtractAccessories.setVisibility(View.GONE); + mExtractAction.setOnClickListener(null); + } + } + + /** + * This is called when, while currently displayed in extract mode, the + * current input target changes. The default implementation will + * auto-hide the IME if the new target is not a full editor, since this + * can be an confusing experience for the user. + */ + public void onExtractingInputChanged(EditorInfo ei) { + if (ei.inputType == InputType.TYPE_NULL) { + requestHideSelf(InputMethodManager.HIDE_NOT_ALWAYS); + } + } + + void startExtractingText(boolean inputChanged) { + final ExtractEditText eet = mExtractEditText; + if (eet != null && getCurrentInputStarted() && isFullscreenMode()) { mExtractedToken++; ExtractedTextRequest req = new ExtractedTextRequest(); req.token = mExtractedToken; + req.flags = InputConnection.GET_TEXT_WITH_STYLES; req.hintMaxLines = 10; req.hintMaxChars = 10000; - mExtractedText = mInputConnection.getExtractedText(req, - InputConnection.EXTRACTED_TEXT_MONITOR); - if (mExtractedText != null) { - mExtractEditText.setExtractedText(mExtractedText); + mExtractedText = getCurrentInputConnection().getExtractedText(req, + InputConnection.GET_EXTRACTED_TEXT_MONITOR); + + final EditorInfo ei = getCurrentInputEditorInfo(); + + try { + eet.startInternalChanges(); + onUpdateExtractingAccessories(ei); + int inputType = ei.inputType; + if ((inputType&EditorInfo.TYPE_MASK_CLASS) + == EditorInfo.TYPE_CLASS_TEXT) { + if ((inputType&EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE) != 0) { + inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; + } + } + eet.setInputType(inputType); + eet.setHint(ei.hintText); + if (mExtractedText != null) { + eet.setEnabled(true); + eet.setExtractedText(mExtractedText); + } else { + eet.setEnabled(false); + eet.setText(""); + } + } finally { + eet.finishInternalChanges(); + } + + if (inputChanged) { + onExtractingInputChanged(ei); } - mExtractEditText.setInputType(getCurrentInputEditorInfo().inputType); - mExtractEditText.setHint(mInputEditorInfo.hintText); } } + + /** + * Performs a dump of the InputMethodService's internal state. Override + * to add your own information to the dump. + */ + @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { + final Printer p = new PrintWriterPrinter(fout); + p.println("Input method service state for " + this + ":"); + p.println(" mWindowCreated=" + mWindowCreated + + " mWindowAdded=" + mWindowAdded + + " mWindowVisible=" + mWindowVisible); + p.println(" Configuration=" + getResources().getConfiguration()); + p.println(" mToken=" + mToken); + p.println(" mInputBinding=" + mInputBinding); + p.println(" mInputConnection=" + mInputConnection); + p.println(" mStartedInputConnection=" + mStartedInputConnection); + p.println(" mInputStarted=" + mInputStarted + + " mInputViewStarted=" + mInputViewStarted + + " mCandidatesViewStarted=" + mCandidatesViewStarted); + + if (mInputEditorInfo != null) { + p.println(" mInputEditorInfo:"); + mInputEditorInfo.dump(p, " "); + } else { + p.println(" mInputEditorInfo: null"); + } + + p.println(" mShowInputRequested=" + mShowInputRequested + + " mLastShowInputRequested=" + mLastShowInputRequested + + " mShowInputForced=" + mShowInputForced + + " mShowInputFlags=0x" + Integer.toHexString(mShowInputFlags)); + p.println(" mCandidatesVisibility=" + mCandidatesVisibility + + " mFullscreenApplied=" + mFullscreenApplied + + " mIsFullscreen=" + mIsFullscreen); + + if (mExtractedText != null) { + p.println(" mExtractedText:"); + p.println(" text=" + mExtractedText.text.length() + " chars" + + " startOffset=" + mExtractedText.startOffset); + p.println(" selectionStart=" + mExtractedText.selectionStart + + " selectionEnd=" + mExtractedText.selectionEnd + + " flags=0x" + Integer.toHexString(mExtractedText.flags)); + } else { + p.println(" mExtractedText: null"); + } + p.println(" mExtractedToken=" + mExtractedToken); + p.println(" mIsInputViewShown=" + mIsInputViewShown + + " mStatusIcon=" + mStatusIcon); + p.println("Last computed insets:"); + p.println(" contentTopInsets=" + mTmpInsets.contentTopInsets + + " visibleTopInsets=" + mTmpInsets.visibleTopInsets + + " touchableInsets=" + mTmpInsets.touchableInsets); + } } diff --git a/core/java/android/inputmethodservice/Keyboard.java b/core/java/android/inputmethodservice/Keyboard.java index cfd3188bec4df45cab11cae9e8213334eac3b565..6a560ce0150bedff3917561567d6fb565ecd15ee 100755 --- a/core/java/android/inputmethodservice/Keyboard.java +++ b/core/java/android/inputmethodservice/Keyboard.java @@ -132,7 +132,19 @@ public class Keyboard { /** Keyboard mode, or zero, if none. */ private int mKeyboardMode; + + // Variables for pre-computing nearest keys. + private static final int GRID_WIDTH = 10; + private static final int GRID_HEIGHT = 5; + private static final int GRID_SIZE = GRID_WIDTH * GRID_HEIGHT; + private int mCellWidth; + private int mCellHeight; + private int[][] mGridNeighbors; + private int mProximityThreshold; + /** Number of key widths from current touch point to search for nearest keys. */ + private static float SEARCH_DISTANCE = 1.4f; + /** * Container for keys in the keyboard. All keys in a row are at the same Y-coordinate. * Some of the key size defaults can be overridden per row from what the {@link Keyboard} @@ -177,13 +189,13 @@ public class Keyboard { parent.mDisplayWidth, parent.mDefaultWidth); defaultHeight = getDimensionOrFraction(a, com.android.internal.R.styleable.Keyboard_keyHeight, - parent.mDisplayWidth, parent.mDefaultHeight); - defaultHorizontalGap = getDimensionOrFraction(a, + parent.mDisplayHeight, parent.mDefaultHeight); + defaultHorizontalGap = getDimensionOrFraction(a, com.android.internal.R.styleable.Keyboard_horizontalGap, parent.mDisplayWidth, parent.mDefaultHorizontalGap); verticalGap = getDimensionOrFraction(a, com.android.internal.R.styleable.Keyboard_verticalGap, - parent.mDisplayWidth, parent.mDefaultVerticalGap); + parent.mDisplayHeight, parent.mDefaultVerticalGap); a.recycle(); a = res.obtainAttributes(Xml.asAttributeSet(parser), com.android.internal.R.styleable.Keyboard_Row); @@ -540,7 +552,6 @@ public class Keyboard { row.defaultHorizontalGap = mDefaultHorizontalGap; row.verticalGap = mDefaultVerticalGap; row.rowEdgeFlags = EDGE_TOP | EDGE_BOTTOM; - final int maxColumns = columns == -1 ? Integer.MAX_VALUE : columns; for (int i = 0; i < characters.length(); i++) { char c = characters.charAt(i); @@ -638,6 +649,52 @@ public class Keyboard { public int getShiftKeyIndex() { return mShiftKeyIndex; } + + private void computeNearestNeighbors() { + // Round-up so we don't have any pixels outside the grid + mCellWidth = (getMinWidth() + GRID_WIDTH - 1) / GRID_WIDTH; + mCellHeight = (getHeight() + GRID_HEIGHT - 1) / GRID_HEIGHT; + mGridNeighbors = new int[GRID_SIZE][]; + int[] indices = new int[mKeys.size()]; + final int gridWidth = GRID_WIDTH * mCellWidth; + final int gridHeight = GRID_HEIGHT * mCellHeight; + for (int x = 0; x < gridWidth; x += mCellWidth) { + for (int y = 0; y < gridHeight; y += mCellHeight) { + int count = 0; + for (int i = 0; i < mKeys.size(); i++) { + final Key key = mKeys.get(i); + if (key.squaredDistanceFrom(x, y) < mProximityThreshold || + key.squaredDistanceFrom(x + mCellWidth - 1, y) < mProximityThreshold || + key.squaredDistanceFrom(x + mCellWidth - 1, y + mCellHeight - 1) + < mProximityThreshold || + key.squaredDistanceFrom(x, y + mCellHeight - 1) < mProximityThreshold) { + indices[count++] = i; + } + } + int [] cell = new int[count]; + System.arraycopy(indices, 0, cell, 0, count); + mGridNeighbors[(y / mCellHeight) * GRID_WIDTH + (x / mCellWidth)] = cell; + } + } + } + + /** + * Returns the indices of the keys that are closest to the given point. + * @param x the x-coordinate of the point + * @param y the y-coordinate of the point + * @return the array of integer indices for the nearest keys to the given point. If the given + * point is out of range, then an array of size zero is returned. + */ + public int[] getNearestKeys(int x, int y) { + if (mGridNeighbors == null) computeNearestNeighbors(); + if (x >= 0 && x < getMinWidth() && y >= 0 && y < getHeight()) { + int index = (y / mCellHeight) * GRID_WIDTH + (x / mCellWidth); + if (index < GRID_SIZE) { + return mGridNeighbors[index]; + } + } + return new int[0]; + } protected Row createRowFromXml(Resources res, XmlResourceParser parser) { return new Row(res, this, parser); @@ -739,6 +796,8 @@ public class Keyboard { mDefaultVerticalGap = getDimensionOrFraction(a, com.android.internal.R.styleable.Keyboard_verticalGap, mDisplayHeight, 0); + mProximityThreshold = (int) (mDefaultWidth * SEARCH_DISTANCE); + mProximityThreshold = mProximityThreshold * mProximityThreshold; // Square it for comparison a.recycle(); } diff --git a/core/java/android/inputmethodservice/KeyboardView.java b/core/java/android/inputmethodservice/KeyboardView.java index 2f3b54bee71613f51777c614ca23fd1e7ccfa7c3..7a63c0c02161bd81f27508b9b1f7c22f0e45f206 100755 --- a/core/java/android/inputmethodservice/KeyboardView.java +++ b/core/java/android/inputmethodservice/KeyboardView.java @@ -16,34 +16,33 @@ package android.inputmethodservice; -import com.android.internal.R; - import android.content.Context; -import android.content.SharedPreferences; import android.content.res.TypedArray; +import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; +import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.Paint.Align; +import android.graphics.Region.Op; import android.graphics.drawable.Drawable; import android.inputmethodservice.Keyboard.Key; import android.os.Handler; import android.os.Message; -import android.os.Vibrator; -import android.preference.PreferenceManager; +import android.os.SystemClock; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; -import android.view.ViewConfiguration; import android.view.ViewGroup.LayoutParams; -import android.widget.Button; import android.widget.PopupWindow; import android.widget.TextView; +import com.android.internal.R; + import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -74,7 +73,6 @@ public class KeyboardView extends View implements View.OnClickListener { * For keys that repeat, this is only called once. * @param primaryCode the unicode of the key being pressed. If the touch is not on a valid * key, the value will be zero. - * @hide Pending API Council approval */ void onPress(int primaryCode); @@ -82,7 +80,6 @@ public class KeyboardView extends View implements View.OnClickListener { * Called when the user releases a key. This is sent after the {@link #onKey} is called. * For keys that repeat, this is only called once. * @param primaryCode the code of the key that was released - * @hide Pending API Council approval */ void onRelease(int primaryCode); @@ -98,6 +95,12 @@ public class KeyboardView extends View implements View.OnClickListener { */ void onKey(int primaryCode, int[] keyCodes); + /** + * Sends a sequence of characters to the listener. + * @param text the sequence of characters to be displayed. + */ + void onText(CharSequence text); + /** * Called when the user quickly moves the finger from right to left. */ @@ -149,6 +152,7 @@ public class KeyboardView extends View implements View.OnClickListener { private int mMiniKeyboardOffsetY; private Map mMiniKeyboardCache; private int[] mWindowOffset; + private Key[] mKeys; /** Listener for {@link OnKeyboardActionListener}. */ private OnKeyboardActionListener mKeyboardActionListener; @@ -158,12 +162,15 @@ public class KeyboardView extends View implements View.OnClickListener { private static final int MSG_REPEAT = 3; private static final int MSG_LONGPRESS = 4; + private static final int DELAY_BEFORE_PREVIEW = 70; + private static final int DELAY_AFTER_PREVIEW = 60; + private int mVerticalCorrection; private int mProximityThreshold; private boolean mPreviewCentered = false; private boolean mShowPreview = true; - private boolean mShowTouchPoints = false; + private boolean mShowTouchPoints = true; private int mPopupPreviewX; private int mPopupPreviewY; @@ -213,12 +220,21 @@ public class KeyboardView extends View implements View.OnClickListener { private static final int MULTITAP_INTERVAL = 800; // milliseconds private StringBuilder mPreviewLabel = new StringBuilder(1); + /** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/ + private boolean mDrawPending; + /** The dirty region in the keyboard bitmap */ + private Rect mDirtyRect = new Rect(); + /** The keyboard bitmap for faster updates */ + private Bitmap mBuffer; + /** The canvas for the above mutable keyboard bitmap */ + private Canvas mCanvas; + Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SHOW_PREVIEW: - mPreviewText.setVisibility(VISIBLE); + showKey(msg.arg1); break; case MSG_REMOVE_PREVIEW: mPreviewText.setVisibility(INVISIBLE); @@ -233,7 +249,6 @@ public class KeyboardView extends View implements View.OnClickListener { openPopupIfRequired((MotionEvent) msg.obj); break; } - } }; @@ -334,7 +349,7 @@ public class KeyboardView extends View implements View.OnClickListener { } private void initGestureDetector() { - mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { + mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) { @@ -386,9 +401,15 @@ public class KeyboardView extends View implements View.OnClickListener { showPreview(NOT_A_KEY); } mKeyboard = keyboard; + List keys = mKeyboard.getKeys(); + mKeys = keys.toArray(new Key[keys.size()]); requestLayout(); - invalidate(); + // Release buffer, just in case the new keyboard has a different size. + // It will be reallocated on the next draw. + mBuffer = null; + invalidateAll(); computeProximityThreshold(keyboard); + mMiniKeyboardCache.clear(); // Not really necessary to do every time, but will free up views } /** @@ -410,7 +431,7 @@ public class KeyboardView extends View implements View.OnClickListener { if (mKeyboard != null) { if (mKeyboard.setShifted(shifted)) { // The whole keyboard probably needs to be redrawn - invalidate(); + invalidateAll(); return true; } } @@ -492,7 +513,7 @@ public class KeyboardView extends View implements View.OnClickListener { } private CharSequence adjustCase(CharSequence label) { - if (mKeyboard.isShifted() && label != null && label.length() == 1 + if (mKeyboard.isShifted() && label != null && label.length() < 3 && Character.isLowerCase(label.charAt(0))) { label = label.toString().toUpperCase(); } @@ -521,22 +542,44 @@ public class KeyboardView extends View implements View.OnClickListener { */ private void computeProximityThreshold(Keyboard keyboard) { if (keyboard == null) return; - List keys = keyboard.getKeys(); + final Key[] keys = mKeys; if (keys == null) return; - int length = keys.size(); + int length = keys.length; int dimensionSum = 0; for (int i = 0; i < length; i++) { - Key key = keys.get(i); - dimensionSum += key.width + key.gap + key.height; + Key key = keys[i]; + dimensionSum += Math.min(key.width, key.height) + key.gap; } if (dimensionSum < 0 || length == 0) return; - mProximityThreshold = dimensionSum / (length * 2); + mProximityThreshold = (int) (dimensionSum * 1.4f / length); mProximityThreshold *= mProximityThreshold; // Square it } - + + @Override + public void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + // Release the buffer, if any and it will be reallocated on the next draw + mBuffer = null; + } + @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); + if (mDrawPending || mBuffer == null) { + onBufferDraw(); + } + canvas.drawBitmap(mBuffer, 0, 0, null); + } + + private void onBufferDraw() { + if (mBuffer == null) { + mBuffer = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); + mCanvas = new Canvas(mBuffer); + invalidateAll(); + } + final Canvas canvas = mCanvas; + canvas.clipRect(mDirtyRect, Op.REPLACE); + if (mKeyboard == null) return; final Paint paint = mPaint; @@ -545,29 +588,25 @@ public class KeyboardView extends View implements View.OnClickListener { final Rect padding = mPadding; final int kbdPaddingLeft = mPaddingLeft; final int kbdPaddingTop = mPaddingTop; - final List keys = mKeyboard.getKeys(); + final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; - //canvas.translate(0, mKeyboardPaddingTop); + paint.setAlpha(255); paint.setColor(mKeyTextColor); boolean drawSingleKey = false; if (invalidKey != null && canvas.getClipBounds(clipRegion)) { -// System.out.println("Key bounds = " + (invalidKey.x + mPaddingLeft) + "," -// + (invalidKey.y + mPaddingTop) + "," -// + (invalidKey.x + invalidKey.width + mPaddingLeft) + "," -// + (invalidKey.y + invalidKey.height + mPaddingTop)); -// System.out.println("Clip bounds =" + clipRegion.toShortString()); - // Is clipRegion completely contained within the invalidated key? - if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && - invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && - invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && - invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { - drawSingleKey = true; - } + // Is clipRegion completely contained within the invalidated key? + if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && + invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && + invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && + invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { + drawSingleKey = true; + } } - final int keyCount = keys.size(); + canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); + final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { - final Key key = keys.get(i); + final Key key = keys[i]; if (drawSingleKey && invalidKey != key) { continue; } @@ -635,18 +674,22 @@ public class KeyboardView extends View implements View.OnClickListener { paint.setColor(0xFF00FF00); canvas.drawCircle((mStartX + mLastX) / 2, (mStartY + mLastY) / 2, 2, paint); } + + mDrawPending = false; + mDirtyRect.setEmpty(); } private int getKeyIndices(int x, int y, int[] allKeys) { - final List keys = mKeyboard.getKeys(); + final Key[] keys = mKeys; final boolean shifted = mKeyboard.isShifted(); int primaryIndex = NOT_A_KEY; int closestKey = NOT_A_KEY; int closestKeyDist = mProximityThreshold + 1; java.util.Arrays.fill(mDistances, Integer.MAX_VALUE); - final int keyCount = keys.size(); + int [] nearestKeyIndices = mKeyboard.getNearestKeys(x, y); + final int keyCount = nearestKeyIndices.length; for (int i = 0; i < keyCount; i++) { - final Key key = keys.get(i); + final Key key = keys[nearestKeyIndices[i]]; int dist = 0; boolean isInside = key.isInside(x,y); if (((mProximityCorrectOn @@ -657,7 +700,7 @@ public class KeyboardView extends View implements View.OnClickListener { final int nCodes = key.codes.length; if (dist < closestKeyDist) { closestKeyDist = dist; - closestKey = i; + closestKey = nearestKeyIndices[i]; } if (allKeys == null) continue; @@ -671,9 +714,6 @@ public class KeyboardView extends View implements View.OnClickListener { allKeys.length - j - nCodes); for (int c = 0; c < nCodes; c++) { allKeys[j + c] = key.codes[c]; - if (shifted) { - //allKeys[j + c] = Character.toUpperCase(key.codes[c]); - } mDistances[j + c] = dist; } break; @@ -682,7 +722,7 @@ public class KeyboardView extends View implements View.OnClickListener { } if (isInside) { - primaryIndex = i; + primaryIndex = nearestKeyIndices[i]; } } if (primaryIndex == NOT_A_KEY) { @@ -693,12 +733,10 @@ public class KeyboardView extends View implements View.OnClickListener { private void detectAndSendKey(int x, int y, long eventTime) { int index = mCurrentKey; - if (index != NOT_A_KEY) { - final Key key = mKeyboard.getKeys().get(index); + if (index != NOT_A_KEY && index < mKeys.length) { + final Key key = mKeys[index]; if (key.text != null) { - for (int i = 0; i < key.text.length(); i++) { - mKeyboardActionListener.onKey(key.text.charAt(i), key.codes); - } + mKeyboardActionListener.onText(key.text); mKeyboardActionListener.onRelease(NOT_A_KEY); } else { int code = key.codes[0]; @@ -743,14 +781,14 @@ public class KeyboardView extends View implements View.OnClickListener { mCurrentKeyIndex = keyIndex; // Release the old key and press the new key - final List keys = mKeyboard.getKeys(); + final Key[] keys = mKeys; if (oldKeyIndex != mCurrentKeyIndex) { - if (oldKeyIndex != NOT_A_KEY && keys.size() > oldKeyIndex) { - keys.get(oldKeyIndex).onReleased(mCurrentKeyIndex == NOT_A_KEY); + if (oldKeyIndex != NOT_A_KEY && keys.length > oldKeyIndex) { + keys[oldKeyIndex].onReleased(mCurrentKeyIndex == NOT_A_KEY); invalidateKey(oldKeyIndex); } - if (mCurrentKeyIndex != NOT_A_KEY && keys.size() > mCurrentKeyIndex) { - keys.get(mCurrentKeyIndex).onPressed(); + if (mCurrentKeyIndex != NOT_A_KEY && keys.length > mCurrentKeyIndex) { + keys[mCurrentKeyIndex].onPressed(); invalidateKey(mCurrentKeyIndex); } } @@ -760,75 +798,99 @@ public class KeyboardView extends View implements View.OnClickListener { if (previewPopup.isShowing()) { if (keyIndex == NOT_A_KEY) { mHandler.sendMessageDelayed(mHandler - .obtainMessage(MSG_REMOVE_PREVIEW), 60); + .obtainMessage(MSG_REMOVE_PREVIEW), + DELAY_AFTER_PREVIEW); } } if (keyIndex != NOT_A_KEY) { - Key key = keys.get(keyIndex); - if (key.icon != null) { - mPreviewText.setCompoundDrawables(null, null, null, - key.iconPreview != null ? key.iconPreview : key.icon); - mPreviewText.setText(null); - } else { - mPreviewText.setCompoundDrawables(null, null, null, null); - mPreviewText.setText(getPreviewText(key)); - if (key.label.length() > 1 && key.codes.length < 2) { - mPreviewText.setTextSize(mLabelTextSize); - } else { - mPreviewText.setTextSize(mPreviewTextSizeLarge); - } - } - mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), - MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); - int popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.width - + mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight()); - final int popupHeight = mPreviewHeight; - LayoutParams lp = mPreviewText.getLayoutParams(); - if (lp != null) { - lp.width = popupWidth; - lp.height = popupHeight; - } - previewPopup.setWidth(popupWidth); - previewPopup.setHeight(popupHeight); - if (!mPreviewCentered) { - mPopupPreviewX = key.x - mPreviewText.getPaddingLeft() + mPaddingLeft; - mPopupPreviewY = key.y - popupHeight + mPreviewOffset; - } else { - // TODO: Fix this if centering is brought back - mPopupPreviewX = 160 - mPreviewText.getMeasuredWidth() / 2; - mPopupPreviewY = - mPreviewText.getMeasuredHeight(); - } - mHandler.removeMessages(MSG_REMOVE_PREVIEW); - if (mOffsetInWindow == null) { - mOffsetInWindow = new int[2]; - getLocationInWindow(mOffsetInWindow); - mOffsetInWindow[0] += mMiniKeyboardOffsetX; // Offset may be zero - mOffsetInWindow[1] += mMiniKeyboardOffsetY; // Offset may be zero - } - // Set the preview background state - mPreviewText.getBackground().setState( - key.popupResId != 0 ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET); - if (previewPopup.isShowing()) { - previewPopup.update(mPopupParent, mPopupPreviewX + mOffsetInWindow[0], - mPopupPreviewY + mOffsetInWindow[1], - popupWidth, popupHeight); + if (previewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) { + // Show right away, if it's already visible and finger is moving around + showKey(keyIndex); } else { - previewPopup.showAtLocation(mPopupParent, Gravity.NO_GRAVITY, - mPopupPreviewX + mOffsetInWindow[0], - mPopupPreviewY + mOffsetInWindow[1]); + mHandler.sendMessageDelayed( + mHandler.obtainMessage(MSG_SHOW_PREVIEW, keyIndex, 0), + DELAY_BEFORE_PREVIEW); } - mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SHOW_PREVIEW, keyIndex, 0), - ViewConfiguration.getTapTimeout()); } } } + + private void showKey(final int keyIndex) { + final PopupWindow previewPopup = mPreviewPopup; + final Key[] keys = mKeys; + Key key = keys[keyIndex]; + if (key.icon != null) { + mPreviewText.setCompoundDrawables(null, null, null, + key.iconPreview != null ? key.iconPreview : key.icon); + mPreviewText.setText(null); + } else { + mPreviewText.setCompoundDrawables(null, null, null, null); + mPreviewText.setText(getPreviewText(key)); + if (key.label.length() > 1 && key.codes.length < 2) { + mPreviewText.setTextSize(mKeyTextSize); + mPreviewText.setTypeface(Typeface.DEFAULT_BOLD); + } else { + mPreviewText.setTextSize(mPreviewTextSizeLarge); + mPreviewText.setTypeface(Typeface.DEFAULT); + } + } + mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), + MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); + int popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.width + + mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight()); + final int popupHeight = mPreviewHeight; + LayoutParams lp = mPreviewText.getLayoutParams(); + if (lp != null) { + lp.width = popupWidth; + lp.height = popupHeight; + } + if (!mPreviewCentered) { + mPopupPreviewX = key.x - mPreviewText.getPaddingLeft() + mPaddingLeft; + mPopupPreviewY = key.y - popupHeight + mPreviewOffset; + } else { + // TODO: Fix this if centering is brought back + mPopupPreviewX = 160 - mPreviewText.getMeasuredWidth() / 2; + mPopupPreviewY = - mPreviewText.getMeasuredHeight(); + } + mHandler.removeMessages(MSG_REMOVE_PREVIEW); + if (mOffsetInWindow == null) { + mOffsetInWindow = new int[2]; + getLocationInWindow(mOffsetInWindow); + mOffsetInWindow[0] += mMiniKeyboardOffsetX; // Offset may be zero + mOffsetInWindow[1] += mMiniKeyboardOffsetY; // Offset may be zero + } + // Set the preview background state + mPreviewText.getBackground().setState( + key.popupResId != 0 ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET); + if (previewPopup.isShowing()) { + previewPopup.update(mPopupPreviewX + mOffsetInWindow[0], + mPopupPreviewY + mOffsetInWindow[1], + popupWidth, popupHeight); + } else { + previewPopup.setWidth(popupWidth); + previewPopup.setHeight(popupHeight); + previewPopup.showAtLocation(mPopupParent, Gravity.NO_GRAVITY, + mPopupPreviewX + mOffsetInWindow[0], + mPopupPreviewY + mOffsetInWindow[1]); + } + mPreviewText.setVisibility(VISIBLE); + } + private void invalidateAll() { + mDirtyRect.union(0, 0, getWidth(), getHeight()); + mDrawPending = true; + invalidate(); + } + private void invalidateKey(int keyIndex) { - if (keyIndex < 0 || keyIndex >= mKeyboard.getKeys().size()) { + if (keyIndex < 0 || keyIndex >= mKeys.length) { return; } - final Key key = mKeyboard.getKeys().get(keyIndex); + final Key key = mKeys[keyIndex]; mInvalidatedKey = key; + mDirtyRect.union(key.x + mPaddingLeft, key.y + mPaddingTop, + key.x + key.width + mPaddingLeft, key.y + key.height + mPaddingTop); + onBufferDraw(); invalidate(key.x + mPaddingLeft, key.y + mPaddingTop, key.x + key.width + mPaddingLeft, key.y + key.height + mPaddingTop); } @@ -838,11 +900,11 @@ public class KeyboardView extends View implements View.OnClickListener { if (mPopupLayout == 0) { return false; } - if (mCurrentKey < 0 || mCurrentKey >= mKeyboard.getKeys().size()) { + if (mCurrentKey < 0 || mCurrentKey >= mKeys.length) { return false; } - Key popupKey = mKeyboard.getKeys().get(mCurrentKey); + Key popupKey = mKeys[mCurrentKey]; boolean result = onLongPress(popupKey); if (result) { mAbortKey = true; @@ -878,6 +940,11 @@ public class KeyboardView extends View implements View.OnClickListener { dismissPopupKeyboard(); } + public void onText(CharSequence text) { + mKeyboardActionListener.onText(text); + dismissPopupKeyboard(); + } + public void swipeLeft() { } public void swipeRight() { } public void swipeUp() { } @@ -926,7 +993,7 @@ public class KeyboardView extends View implements View.OnClickListener { mPopupKeyboard.showAtLocation(this, Gravity.NO_GRAVITY, x, y); mMiniKeyboardOnScreen = true; //mMiniKeyboard.onTouchEvent(getTranslatedEvent(me)); - invalidate(); + invalidateAll(); return true; } return false; @@ -968,8 +1035,8 @@ public class KeyboardView extends View implements View.OnClickListener { mLastMoveTime = mDownTime; checkMultiTap(eventTime, keyIndex); mKeyboardActionListener.onPress(keyIndex != NOT_A_KEY ? - mKeyboard.getKeys().get(keyIndex).codes[0] : 0); - if (mCurrentKey >= 0 && mKeyboard.getKeys().get(mCurrentKey).repeatable) { + mKeys[keyIndex].codes[0] : 0); + if (mCurrentKey >= 0 && mKeys[mCurrentKey].repeatable) { mRepeatKeyIndex = mCurrentKey; repeatKey(); Message msg = mHandler.obtainMessage(MSG_REPEAT); @@ -1040,11 +1107,11 @@ public class KeyboardView extends View implements View.OnClickListener { } showPreview(NOT_A_KEY); Arrays.fill(mKeyIndices, NOT_A_KEY); - invalidateKey(keyIndex); // If we're not on a repeating key (which sends on a DOWN event) if (mRepeatKeyIndex == NOT_A_KEY && !mMiniKeyboardOnScreen && !mAbortKey) { detectAndSendKey(touchX, touchY, eventTime); } + invalidateKey(keyIndex); mRepeatKeyIndex = NOT_A_KEY; break; } @@ -1054,7 +1121,7 @@ public class KeyboardView extends View implements View.OnClickListener { } private boolean repeatKey() { - Key key = mKeyboard.getKeys().get(mRepeatKeyIndex); + Key key = mKeys[mRepeatKeyIndex]; detectAndSendKey(key.x, key.y, mLastTapTime); return true; } @@ -1079,7 +1146,14 @@ public class KeyboardView extends View implements View.OnClickListener { if (mPreviewPopup.isShowing()) { mPreviewPopup.dismiss(); } + mHandler.removeMessages(MSG_REPEAT); + mHandler.removeMessages(MSG_LONGPRESS); + mHandler.removeMessages(MSG_SHOW_PREVIEW); + dismissPopupKeyboard(); + mBuffer = null; + mCanvas = null; + mMiniKeyboardCache.clear(); } @Override @@ -1092,10 +1166,10 @@ public class KeyboardView extends View implements View.OnClickListener { if (mPopupKeyboard.isShowing()) { mPopupKeyboard.dismiss(); mMiniKeyboardOnScreen = false; - invalidate(); + invalidateAll(); } } - + public boolean handleBack() { if (mPopupKeyboard.isShowing()) { dismissPopupKeyboard(); @@ -1113,7 +1187,7 @@ public class KeyboardView extends View implements View.OnClickListener { private void checkMultiTap(long eventTime, int keyIndex) { if (keyIndex == NOT_A_KEY) return; - Key key = mKeyboard.getKeys().get(keyIndex); + Key key = mKeys[keyIndex]; if (key.codes.length > 1) { mInMultiTap = true; if (eventTime < mLastTapTime + MULTITAP_INTERVAL diff --git a/core/java/android/inputmethodservice/SoftInputWindow.java b/core/java/android/inputmethodservice/SoftInputWindow.java index 9ff1665988dad640c6a78e7a15d3de0b00fa38d4..c37845f02b6328118e95fd2818f7479d0867da53 100644 --- a/core/java/android/inputmethodservice/SoftInputWindow.java +++ b/core/java/android/inputmethodservice/SoftInputWindow.java @@ -18,6 +18,7 @@ package android.inputmethodservice; import android.app.Dialog; import android.content.Context; +import android.content.pm.ActivityInfo; import android.os.IBinder; import android.view.Gravity; import android.view.WindowManager; @@ -139,6 +140,9 @@ class SoftInputWindow extends Dialog { lp.gravity = Gravity.BOTTOM; lp.width = -1; + // Let the input method window's orientation follow sensor based rotation + // Turn this off for now, it is very problematic. + //lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_USER; getWindow().setAttributes(lp); getWindow().setFlags( diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java index 213813a81493d81d6cb030f237bdc13d2a5b3607..1429bc1aff4d1f42411b1e12baeadac7a56156d3 100644 --- a/core/java/android/net/ConnectivityManager.java +++ b/core/java/android/net/ConnectivityManager.java @@ -16,6 +16,8 @@ package android.net; +import android.annotation.SdkConstant; +import android.annotation.SdkConstant.SdkConstantType; import android.os.RemoteException; /** @@ -100,6 +102,18 @@ public class ConnectivityManager */ public static final String EXTRA_EXTRA_INFO = "extraInfo"; + /** + * Broadcast Action: The setting for background data usage has changed + * values. Use {@link #getBackgroundDataSetting()} to get the current value. + *

      + * If an application uses the network in the background, it should listen + * for this broadcast and stop using the background data if the value is + * false. + */ + @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED = + "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED"; + public static final int TYPE_MOBILE = 0; public static final int TYPE_WIFI = 1; @@ -223,6 +237,43 @@ public class ConnectivityManager } } + /** + * Returns the value of the setting for background data usage. If false, + * applications should not use the network if the application is not in the + * foreground. Developers should respect this setting, and check the value + * of this before performing any background data operations. + *

      + * All applications that have background services that use the network + * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}. + * + * @return Whether background data usage is allowed. + */ + public boolean getBackgroundDataSetting() { + try { + return mService.getBackgroundDataSetting(); + } catch (RemoteException e) { + // Err on the side of safety + return false; + } + } + + /** + * Sets the value of the setting for background data usage. + * + * @param allowBackgroundData Whether an application should use data while + * it is in the background. + * + * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING + * @see #getBackgroundDataSetting() + * @hide + */ + public void setBackgroundDataSetting(boolean allowBackgroundData) { + try { + mService.setBackgroundDataSetting(allowBackgroundData); + } catch (RemoteException e) { + } + } + /** * Don't allow use of default constructor. */ diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl index e1d921f4d9a0cd7f01dcaa115236b283c6a3312f..de6859809d82e20ee41fa5d3a0327f729249395c 100644 --- a/core/java/android/net/IConnectivityManager.aidl +++ b/core/java/android/net/IConnectivityManager.aidl @@ -44,4 +44,8 @@ interface IConnectivityManager int stopUsingNetworkFeature(int networkType, in String feature); boolean requestRouteToHost(int networkType, int hostAddress); + + boolean getBackgroundDataSetting(); + + void setBackgroundDataSetting(boolean allowBackgroundData); } diff --git a/core/java/android/net/SSLCertificateSocketFactory.java b/core/java/android/net/SSLCertificateSocketFactory.java index f816caa6da2f77eac5fbabe78d5290b1387716d3..deaa3c35f99bca3238bcb5f733d5823121cc14cf 100644 --- a/core/java/android/net/SSLCertificateSocketFactory.java +++ b/core/java/android/net/SSLCertificateSocketFactory.java @@ -16,38 +16,45 @@ package android.net; -import android.util.Log; -import android.util.Config; import android.net.http.DomainNameChecker; import android.os.SystemProperties; - -import javax.net.SocketFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; +import android.util.Config; +import android.util.Log; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; -import java.security.NoSuchAlgorithmException; +import java.security.GeneralSecurityException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; -import java.security.GeneralSecurityException; +import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import javax.net.SocketFactory; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; +import org.apache.harmony.xnet.provider.jsse.SSLContextImpl; + +/** + * SSLSocketFactory that provides optional (on debug devices, only) skipping of ssl certificfate + * chain validation and custom read timeouts used just when connecting to the server/negotiating + * an ssl session. + * + * You can skip the ssl certificate checking at runtime by setting socket.relaxsslcheck=yes on + * devices that do not have have ro.secure set. + */ public class SSLCertificateSocketFactory extends SSLSocketFactory { - private static final boolean DBG = true; private static final String LOG_TAG = "SSLCertificateSocketFactory"; - - private static X509TrustManager sDefaultTrustManager; - private final int socketReadTimeoutForSslHandshake; + private static X509TrustManager sDefaultTrustManager; static { try { @@ -83,27 +90,56 @@ public class SSLCertificateSocketFactory extends SSLSocketFactory { } }; - private SSLSocketFactory factory; + private final SSLSocketFactory mFactory; + + private final int mSocketReadTimeoutForSslHandshake; + /** + * Do not use this constructor (will be deprecated). Use {@link #getDefault(int)} instead. + */ public SSLCertificateSocketFactory(int socketReadTimeoutForSslHandshake) - throws NoSuchAlgorithmException, KeyManagementException { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, TRUST_MANAGER, new java.security.SecureRandom()); - factory = (SSLSocketFactory) context.getSocketFactory(); - this.socketReadTimeoutForSslHandshake = socketReadTimeoutForSslHandshake; + throws NoSuchAlgorithmException, KeyManagementException { + this(socketReadTimeoutForSslHandshake, null /* cache */); + } + + private SSLCertificateSocketFactory(int socketReadTimeoutForSslHandshake, + SSLClientSessionCache cache) throws NoSuchAlgorithmException, KeyManagementException { + SSLContextImpl sslContext = new SSLContextImpl(); + sslContext.engineInit(null /* kms */, + TRUST_MANAGER, new java.security.SecureRandom(), + cache /* client cache */, null /* server cache */); + this.mFactory = sslContext.engineGetSocketFactory(); + this.mSocketReadTimeoutForSslHandshake = socketReadTimeoutForSslHandshake; } /** - * Returns a default instantiation of a new socket factory which - * only allows SSL connections with valid certificates. + * Returns a new instance of a socket factory using the specified socket read + * timeout while connecting with the server/negotiating an ssl session. * * @param socketReadTimeoutForSslHandshake the socket read timeout used for performing * ssl handshake. The socket read timeout is set back to 0 after the handshake. * @return a new SocketFactory, or null on error */ public static SocketFactory getDefault(int socketReadTimeoutForSslHandshake) { + return getDefault(socketReadTimeoutForSslHandshake, null /* cache */); + } + + /** + * Returns a new instance of a socket factory using the specified socket read + * timeout while connecting with the server/negotiating an ssl session. + * Persists ssl sessions using the provided {@link SSLClientSessionCache}. + * + * @param socketReadTimeoutForSslHandshake the socket read timeout used for performing + * ssl handshake. The socket read timeout is set back to 0 after the handshake. + * @param cache The {@link SSLClientSessionCache} to use, if any. + * @return a new SocketFactory, or null on error + * + * @hide + */ + public static SocketFactory getDefault(int socketReadTimeoutForSslHandshake, + SSLClientSessionCache cache) { try { - return new SSLCertificateSocketFactory(socketReadTimeoutForSslHandshake); + return new SSLCertificateSocketFactory(socketReadTimeoutForSslHandshake, cache); } catch (NoSuchAlgorithmException e) { Log.e(LOG_TAG, "SSLCertifcateSocketFactory.getDefault" + @@ -217,10 +253,10 @@ public class SSLCertificateSocketFactory extends SSLSocketFactory { } public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException { - SSLSocket sslSock = (SSLSocket) factory.createSocket(s, i, inaddr, j); + SSLSocket sslSock = (SSLSocket) mFactory.createSocket(s, i, inaddr, j); - if (socketReadTimeoutForSslHandshake >= 0) { - sslSock.setSoTimeout(socketReadTimeoutForSslHandshake); + if (mSocketReadTimeoutForSslHandshake >= 0) { + sslSock.setSoTimeout(mSocketReadTimeoutForSslHandshake); } validateSocket(sslSock,s); @@ -230,10 +266,10 @@ public class SSLCertificateSocketFactory extends SSLSocketFactory { } public Socket createSocket(String s, int i) throws IOException { - SSLSocket sslSock = (SSLSocket) factory.createSocket(s, i); + SSLSocket sslSock = (SSLSocket) mFactory.createSocket(s, i); - if (socketReadTimeoutForSslHandshake >= 0) { - sslSock.setSoTimeout(socketReadTimeoutForSslHandshake); + if (mSocketReadTimeoutForSslHandshake >= 0) { + sslSock.setSoTimeout(mSocketReadTimeoutForSslHandshake); } validateSocket(sslSock,s); @@ -243,11 +279,11 @@ public class SSLCertificateSocketFactory extends SSLSocketFactory { } public String[] getDefaultCipherSuites() { - return factory.getSupportedCipherSuites(); + return mFactory.getSupportedCipherSuites(); } public String[] getSupportedCipherSuites() { - return factory.getSupportedCipherSuites(); + return mFactory.getSupportedCipherSuites(); } } diff --git a/core/java/android/net/Uri.java b/core/java/android/net/Uri.java index 32a26e42d6157731851c443e750a51abed8d9183..c23df217a856d3e3a58517af4cf30ff61dcc251e 100644 --- a/core/java/android/net/Uri.java +++ b/core/java/android/net/Uri.java @@ -2235,12 +2235,13 @@ public abstract class Uri implements Parcelable, Comparable { } /** - * Creates a new Uri by encoding and appending a path segment to a base Uri. + * Creates a new Uri by appending an already-encoded path segment to a + * base Uri. * * @param baseUri Uri to append path segment to - * @param pathSegment to encode and append - * @return a new Uri based on baseUri with the given segment encoded and - * appended to the path + * @param pathSegment encoded path segment to append + * @return a new Uri based on baseUri with the given segment appended to + * the path * @throws NullPointerException if baseUri is null */ public static Uri withAppendedPath(Uri baseUri, String pathSegment) { diff --git a/core/java/android/net/UrlQuerySanitizer.java b/core/java/android/net/UrlQuerySanitizer.java index 70e50b7c2635789e4efbb29cbaad3d7f80d7b3d5..a6efcdd3da517715e84d38aa2b177ff7d86bae1e 100644 --- a/core/java/android/net/UrlQuerySanitizer.java +++ b/core/java/android/net/UrlQuerySanitizer.java @@ -23,7 +23,7 @@ import java.util.Set; import java.util.StringTokenizer; /** - * + * * Sanitizes the Query portion of a URL. Simple example: * * UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(); @@ -32,7 +32,7 @@ import java.util.StringTokenizer; * String name = sanitizer.getValue("name")); * // name now contains "Joe_User" * - * + * * Register ValueSanitizers to customize the way individual * parameters are sanitized: * @@ -46,7 +46,7 @@ import java.util.StringTokenizer; * unregistered parameter sanitizer does not allow any special characters, * and ' ' is a special character.) * - * + * * There are several ways to create ValueSanitizers. In order of increasing * sophistication: *

        @@ -56,7 +56,7 @@ import java.util.StringTokenizer; *
      1. Subclass UrlQuerySanitizer.ValueSanitizer to define your own value * sanitizer. *
      - * + * */ public class UrlQuerySanitizer { @@ -84,7 +84,7 @@ public class UrlQuerySanitizer { */ public String mValue; } - + final private HashMap mSanitizers = new HashMap(); final private HashMap mEntries = @@ -95,9 +95,9 @@ public class UrlQuerySanitizer { private boolean mPreferFirstRepeatedParameter; private ValueSanitizer mUnregisteredParameterValueSanitizer = getAllIllegal(); - + /** - * A functor used to sanitize a single query value. + * A functor used to sanitize a single query value. * */ public static interface ValueSanitizer { @@ -108,7 +108,7 @@ public class UrlQuerySanitizer { */ public String sanitize(String value); } - + /** * Sanitize values based on which characters they contain. Illegal * characters are replaced with either space or '_', depending upon @@ -117,7 +117,7 @@ public class UrlQuerySanitizer { public static class IllegalCharacterValueSanitizer implements ValueSanitizer { private int mFlags; - + /** * Allow space (' ') characters. */ @@ -165,21 +165,21 @@ public class UrlQuerySanitizer { * such as "javascript:" or "vbscript:" */ public final static int SCRIPT_URL_OK = 1 << 10; - + /** * Mask with all fields set to OK */ public final static int ALL_OK = 0x7ff; - + /** * Mask with both regular space and other whitespace OK */ public final static int ALL_WHITESPACE_OK = SPACE_OK | OTHER_WHITESPACE_OK; - + // Common flag combinations: - + /** *
        *
      • Deny all special characters. @@ -262,18 +262,18 @@ public class UrlQuerySanitizer { */ public final static int ALL_BUT_NUL_AND_ANGLE_BRACKETS_LEGAL = ALL_OK & ~(NUL_OK | LT_OK | GT_OK); - + /** * Script URL definitions */ - + private final static String JAVASCRIPT_PREFIX = "javascript:"; - + private final static String VBSCRIPT_PREFIX = "vbscript:"; - + private final static int MIN_SCRIPT_PREFIX_LENGTH = Math.min( JAVASCRIPT_PREFIX.length(), VBSCRIPT_PREFIX.length()); - + /** * Construct a sanitizer. The parameters set the behavior of the * sanitizer. @@ -312,7 +312,7 @@ public class UrlQuerySanitizer { } } } - + // If whitespace isn't OK, get rid of whitespace at beginning // and end of value. if ( (mFlags & ALL_WHITESPACE_OK) == 0) { @@ -337,7 +337,7 @@ public class UrlQuerySanitizer { } return stringBuilder.toString(); } - + /** * Trim whitespace from the beginning and end of a string. *

        @@ -361,7 +361,7 @@ public class UrlQuerySanitizer { } return value.substring(start, end + 1); } - + /** * Check if c is whitespace. * @param c character to test @@ -380,7 +380,7 @@ public class UrlQuerySanitizer { return false; } } - + /** * Check whether an individual character is legal. Uses the * flag bit-set passed into the constructor. @@ -400,11 +400,11 @@ public class UrlQuerySanitizer { case '%' : return (mFlags & PCT_OK) != 0; case '\0': return (mFlags & NUL_OK) != 0; default : return (c >= 32 && c < 127) || - (c >= 128 && c <= 255 && ((mFlags & NON_7_BIT_ASCII_OK) != 0)); - } + ((c >= 128) && ((mFlags & NON_7_BIT_ASCII_OK) != 0)); + } } } - + /** * Get the current value sanitizer used when processing * unregistered parameter values. @@ -412,14 +412,14 @@ public class UrlQuerySanitizer { * Note: The default unregistered parameter value sanitizer is * one that doesn't allow any special characters, similar to what * is returned by calling createAllIllegal. - * + * * @return the current ValueSanitizer used to sanitize unregistered * parameter values. */ public ValueSanitizer getUnregisteredParameterValueSanitizer() { return mUnregisteredParameterValueSanitizer; } - + /** * Set the value sanitizer used when processing unregistered * parameter values. @@ -430,46 +430,46 @@ public class UrlQuerySanitizer { ValueSanitizer sanitizer) { mUnregisteredParameterValueSanitizer = sanitizer; } - - + + // Private fields for singleton sanitizers: - + private static final ValueSanitizer sAllIllegal = new IllegalCharacterValueSanitizer( IllegalCharacterValueSanitizer.ALL_ILLEGAL); - + private static final ValueSanitizer sAllButNulLegal = new IllegalCharacterValueSanitizer( IllegalCharacterValueSanitizer.ALL_BUT_NUL_LEGAL); - + private static final ValueSanitizer sAllButWhitespaceLegal = new IllegalCharacterValueSanitizer( IllegalCharacterValueSanitizer.ALL_BUT_WHITESPACE_LEGAL); - + private static final ValueSanitizer sURLLegal = new IllegalCharacterValueSanitizer( IllegalCharacterValueSanitizer.URL_LEGAL); - + private static final ValueSanitizer sUrlAndSpaceLegal = new IllegalCharacterValueSanitizer( IllegalCharacterValueSanitizer.URL_AND_SPACE_LEGAL); - + private static final ValueSanitizer sAmpLegal = new IllegalCharacterValueSanitizer( - IllegalCharacterValueSanitizer.AMP_LEGAL); - + IllegalCharacterValueSanitizer.AMP_LEGAL); + private static final ValueSanitizer sAmpAndSpaceLegal = new IllegalCharacterValueSanitizer( IllegalCharacterValueSanitizer.AMP_AND_SPACE_LEGAL); - + private static final ValueSanitizer sSpaceLegal = new IllegalCharacterValueSanitizer( IllegalCharacterValueSanitizer.SPACE_LEGAL); - + private static final ValueSanitizer sAllButNulAndAngleBracketsLegal = new IllegalCharacterValueSanitizer( IllegalCharacterValueSanitizer.ALL_BUT_NUL_AND_ANGLE_BRACKETS_LEGAL); - + /** * Return a value sanitizer that does not allow any special characters, * and also does not allow script URLs. @@ -478,7 +478,7 @@ public class UrlQuerySanitizer { public static final ValueSanitizer getAllIllegal() { return sAllIllegal; } - + /** * Return a value sanitizer that allows everything except Nul ('\0') * characters. Script URLs are allowed. @@ -547,7 +547,7 @@ public class UrlQuerySanitizer { public static final ValueSanitizer getAllButNulAndAngleBracketsLegal() { return sAllButNulAndAngleBracketsLegal; } - + /** * Constructs a UrlQuerySanitizer. *

        @@ -560,7 +560,7 @@ public class UrlQuerySanitizer { */ public UrlQuerySanitizer() { } - + /** * Constructs a UrlQuerySanitizer and parse a URL. * This constructor is provided for convenience when the @@ -585,7 +585,7 @@ public class UrlQuerySanitizer { setAllowUnregisteredParamaters(true); parseUrl(url); } - + /** * Parse the query parameters out of an encoded URL. * Works by extracting the query portion from the URL and then @@ -604,7 +604,7 @@ public class UrlQuerySanitizer { } parseQuery(query); } - + /** * Parse a query. A query string is any number of parameter-value clauses * separated by any non-zero number of ampersands. A parameter-value clause @@ -631,7 +631,7 @@ public class UrlQuerySanitizer { } } } - + /** * Get a set of all of the parameters found in the sanitized query. *

        @@ -641,7 +641,7 @@ public class UrlQuerySanitizer { public Set getParameterSet() { return mEntries.keySet(); } - + /** * An array list of all of the parameter value pairs in the sanitized * query, in the order they appeared in the query. May contain duplicate @@ -691,7 +691,7 @@ public class UrlQuerySanitizer { } mSanitizers.put(parameter, valueSanitizer); } - + /** * Register a value sanitizer for an array of parameters. * @param parameters An array of unencoded parameter names. @@ -705,7 +705,7 @@ public class UrlQuerySanitizer { mSanitizers.put(parameters[i], valueSanitizer); } } - + /** * Set whether or not unregistered parameters are allowed. If they * are not allowed, then they will be dropped when a query is sanitized. @@ -718,7 +718,7 @@ public class UrlQuerySanitizer { boolean allowUnregisteredParamaters) { mAllowUnregisteredParamaters = allowUnregisteredParamaters; } - + /** * Get whether or not unregistered parameters are allowed. If not * allowed, they will be dropped when a query is parsed. @@ -728,10 +728,10 @@ public class UrlQuerySanitizer { public boolean getAllowUnregisteredParamaters() { return mAllowUnregisteredParamaters; } - + /** * Set whether or not the first occurrence of a repeated parameter is - * preferred. True means the first repeated parameter is preferred. + * preferred. True means the first repeated parameter is preferred. * False means that the last repeated parameter is preferred. *

        * The preferred parameter is the one that is returned when getParameter @@ -746,7 +746,7 @@ public class UrlQuerySanitizer { boolean preferFirstRepeatedParameter) { mPreferFirstRepeatedParameter = preferFirstRepeatedParameter; } - + /** * Get whether or not the first occurrence of a repeated parameter is * preferred. @@ -757,10 +757,10 @@ public class UrlQuerySanitizer { public boolean getPreferFirstRepeatedParameter() { return mPreferFirstRepeatedParameter; } - + /** * Parse an escaped parameter-value pair. The default implementation - * unescapes both the parameter and the value, then looks up the + * unescapes both the parameter and the value, then looks up the * effective value sanitizer for the parameter and uses it to sanitize * the value. If all goes well then addSanitizedValue is called with * the unescaped parameter and the sanitized unescaped value. @@ -779,7 +779,7 @@ public class UrlQuerySanitizer { String sanitizedValue = valueSanitizer.sanitize(unescapedValue); addSanitizedEntry(unescapedParameter, sanitizedValue); } - + /** * Record a sanitized parameter-value pair. Override if you want to * do additional filtering or validation. @@ -796,7 +796,7 @@ public class UrlQuerySanitizer { } mEntries.put(parameter, value); } - + /** * Get the value sanitizer for a parameter. Returns null if there * is no value sanitizer registered for the parameter. @@ -807,7 +807,7 @@ public class UrlQuerySanitizer { public ValueSanitizer getValueSanitizer(String parameter) { return mSanitizers.get(parameter); } - + /** * Get the effective value sanitizer for a parameter. Like getValueSanitizer, * except if there is no value sanitizer registered for a parameter, and @@ -823,7 +823,7 @@ public class UrlQuerySanitizer { } return sanitizer; } - + /** * Unescape an escaped string. *

          @@ -867,7 +867,7 @@ public class UrlQuerySanitizer { } return stringBuilder.toString(); } - + /** * Test if a character is a hexidecimal digit. Both upper case and lower * case hex digits are allowed. @@ -877,7 +877,7 @@ public class UrlQuerySanitizer { protected boolean isHexDigit(char c) { return decodeHexDigit(c) >= 0; } - + /** * Convert a character that represents a hexidecimal digit into an integer. * If the character is not a hexidecimal digit, then -1 is returned. @@ -885,7 +885,7 @@ public class UrlQuerySanitizer { * @param c the hexidecimal digit. * @return the integer value of the hexidecimal digit. */ - + protected int decodeHexDigit(char c) { if (c >= '0' && c <= '9') { return c - '0'; @@ -900,7 +900,7 @@ public class UrlQuerySanitizer { return -1; } } - + /** * Clear the existing entries. Called to get ready to parse a new * query string. diff --git a/core/java/android/net/http/AndroidHttpClient.java b/core/java/android/net/http/AndroidHttpClient.java index 01442aecaac13c7907d98352b259886bf4e6e3d0..c2013d5bfcd4d97934281973acdcc17df51cc875 100644 --- a/core/java/android/net/http/AndroidHttpClient.java +++ b/core/java/android/net/http/AndroidHttpClient.java @@ -26,7 +26,6 @@ import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.ClientProtocolException; @@ -48,6 +47,8 @@ import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.BasicHttpContext; +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; +import org.apache.harmony.xnet.provider.jsse.SSLContextImpl; import java.io.IOException; import java.io.InputStream; @@ -56,12 +57,13 @@ import java.io.OutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.net.URI; -import java.util.concurrent.atomic.AtomicInteger; +import java.security.KeyManagementException; import android.util.Log; import android.content.ContentResolver; import android.provider.Settings; import android.text.TextUtils; +import android.os.SystemProperties; /** * Subclass of the Apache {@link DefaultHttpClient} that is configured with @@ -100,10 +102,13 @@ public final class AndroidHttpClient implements HttpClient { /** * Create a new HttpClient with reasonable defaults (which you can update). + * * @param userAgent to report in your HTTP requests. + * @param sessionCache persistent session cache * @return AndroidHttpClient for you to use for all your requests. */ - public static AndroidHttpClient newInstance(String userAgent) { + public static AndroidHttpClient newInstance(String userAgent, + SSLClientSessionCache sessionCache) { HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, @@ -125,7 +130,8 @@ public final class AndroidHttpClient implements HttpClient { schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", - SSLSocketFactory.getSocketFactory(), 443)); + socketFactoryWithCache(sessionCache), 443)); + ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); @@ -134,6 +140,41 @@ public final class AndroidHttpClient implements HttpClient { return new AndroidHttpClient(manager, params); } + /** + * Returns a socket factory backed by the given persistent session cache. + * + * @param sessionCache to retrieve sessions from, null for no cache + */ + private static SSLSocketFactory socketFactoryWithCache( + SSLClientSessionCache sessionCache) { + if (sessionCache == null) { + // Use the default factory which doesn't support persistent + // caching. + return SSLSocketFactory.getSocketFactory(); + } + + // Create a new SSL context backed by the cache. + // TODO: Keep a weak *identity* hash map of caches to engines. In the + // mean time, if we have two engines for the same cache, they'll still + // share sessions but will have to do so through the persistent cache. + SSLContextImpl sslContext = new SSLContextImpl(); + try { + sslContext.engineInit(null, null, null, sessionCache, null); + } catch (KeyManagementException e) { + throw new AssertionError(e); + } + return new SSLSocketFactory(sslContext.engineGetSocketFactory()); + } + + /** + * Create a new HttpClient with reasonable defaults (which you can update). + * @param userAgent to report in your HTTP requests. + * @return AndroidHttpClient for you to use for all your requests. + */ + public static AndroidHttpClient newInstance(String userAgent) { + return newInstance(userAgent, null /* session cache */); + } + private final HttpClient delegate; private RuntimeException mLeakedException = new IllegalStateException( @@ -346,6 +387,15 @@ public final class AndroidHttpClient implements HttpClient { return Log.isLoggable(tag, level); } + /** + * Returns true if auth logging is turned on for this configuration. Can only be set on + * insecure devices. + */ + private boolean isAuthLoggable() { + String secure = SystemProperties.get("ro.secure"); + return "0".equals(secure) && Log.isLoggable(tag + "-auth", level); + } + /** * Prints a message using this configuration. */ @@ -392,7 +442,8 @@ public final class AndroidHttpClient implements HttpClient { if (configuration != null && configuration.isLoggable() && request instanceof HttpUriRequest) { - configuration.println(toCurl((HttpUriRequest) request)); + configuration.println(toCurl((HttpUriRequest) request, + configuration.isAuthLoggable())); } } } @@ -400,12 +451,17 @@ public final class AndroidHttpClient implements HttpClient { /** * Generates a cURL command equivalent to the given request. */ - private static String toCurl(HttpUriRequest request) throws IOException { + private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException { StringBuilder builder = new StringBuilder(); builder.append("curl "); for (Header header: request.getAllHeaders()) { + if (!logAuthToken + && (header.getName().equals("Authorization") || + header.getName().equals("Cookie"))) { + continue; + } builder.append("--header \""); builder.append(header.toString().trim()); builder.append("\" "); diff --git a/core/java/android/net/http/CertificateChainValidator.java b/core/java/android/net/http/CertificateChainValidator.java index b7f7368ae24ebad039c4a46c9f2a6bdaad9be739..0edbe5b7e1a187f93ebfdc6ec0641497a612404e 100644 --- a/core/java/android/net/http/CertificateChainValidator.java +++ b/core/java/android/net/http/CertificateChainValidator.java @@ -16,8 +16,6 @@ package android.net.http; -import android.os.SystemClock; - import java.io.IOException; import java.security.cert.Certificate; @@ -28,23 +26,13 @@ import java.security.cert.X509Certificate; import java.security.GeneralSecurityException; import java.security.KeyStore; -import java.util.Arrays; -import java.util.Date; -import java.util.Enumeration; - -import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; -import org.apache.http.HttpHost; - -import org.bouncycastle.asn1.x509.X509Name; - /** * Class responsible for all server certificate validation functionality * @@ -52,9 +40,6 @@ import org.bouncycastle.asn1.x509.X509Name; */ class CertificateChainValidator { - private static long sTotal = 0; - private static long sTotalReused = 0; - /** * The singleton instance of the certificate chain validator */ @@ -110,91 +95,42 @@ class CertificateChainValidator { * @return An SSL error object if there is an error and null otherwise */ public SslError doHandshakeAndValidateServerCertificates( - HttpsConnection connection, SSLSocket sslSocket, String domain) - throws SSLHandshakeException, IOException { - - ++sTotal; - - SSLContext sslContext = HttpsConnection.getContext(); - if (sslContext == null) { - closeSocketThrowException(sslSocket, "SSL context is null"); - } - + HttpsConnection connection, SSLSocket sslSocket, String domain) + throws IOException { X509Certificate[] serverCertificates = null; - long sessionBeforeHandshakeLastAccessedTime = 0; - byte[] sessionBeforeHandshakeId = null; - - SSLSession sessionAfterHandshake = null; - - synchronized(sslContext) { - // get SSL session before the handshake - SSLSession sessionBeforeHandshake = - getSSLSession(sslContext, connection.getHost()); - if (sessionBeforeHandshake != null) { - sessionBeforeHandshakeLastAccessedTime = - sessionBeforeHandshake.getLastAccessedTime(); + // start handshake, close the socket if we fail + try { + sslSocket.setUseClientMode(true); + sslSocket.startHandshake(); + } catch (IOException e) { + closeSocketThrowException( + sslSocket, e.getMessage(), + "failed to perform SSL handshake"); + } - sessionBeforeHandshakeId = - sessionBeforeHandshake.getId(); - } + // retrieve the chain of the server peer certificates + Certificate[] peerCertificates = + sslSocket.getSession().getPeerCertificates(); - // start handshake, close the socket if we fail - try { - sslSocket.setUseClientMode(true); - sslSocket.startHandshake(); - } catch (IOException e) { - closeSocketThrowException( - sslSocket, e.getMessage(), - "failed to perform SSL handshake"); + if (peerCertificates == null || peerCertificates.length <= 0) { + closeSocketThrowException( + sslSocket, "failed to retrieve peer certificates"); + } else { + serverCertificates = + new X509Certificate[peerCertificates.length]; + for (int i = 0; i < peerCertificates.length; ++i) { + serverCertificates[i] = + (X509Certificate)(peerCertificates[i]); } - // retrieve the chain of the server peer certificates - Certificate[] peerCertificates = - sslSocket.getSession().getPeerCertificates(); - - if (peerCertificates == null || peerCertificates.length <= 0) { - closeSocketThrowException( - sslSocket, "failed to retrieve peer certificates"); - } else { - serverCertificates = - new X509Certificate[peerCertificates.length]; - for (int i = 0; i < peerCertificates.length; ++i) { - serverCertificates[i] = - (X509Certificate)(peerCertificates[i]); - } - - // update the SSL certificate associated with the connection - if (connection != null) { - if (serverCertificates[0] != null) { - connection.setCertificate( - new SslCertificate(serverCertificates[0])); - } + // update the SSL certificate associated with the connection + if (connection != null) { + if (serverCertificates[0] != null) { + connection.setCertificate( + new SslCertificate(serverCertificates[0])); } } - - // get SSL session after the handshake - sessionAfterHandshake = - getSSLSession(sslContext, connection.getHost()); - } - - if (sessionBeforeHandshakeLastAccessedTime != 0 && - sessionAfterHandshake != null && - Arrays.equals( - sessionBeforeHandshakeId, sessionAfterHandshake.getId()) && - sessionBeforeHandshakeLastAccessedTime < - sessionAfterHandshake.getLastAccessedTime()) { - - if (HttpLog.LOGV) { - HttpLog.v("SSL session was reused: total reused: " - + sTotalReused - + " out of total of: " + sTotal); - - ++sTotalReused; - } - - // no errors!!! - return null; } // check if the first certificate in the chain is for this site @@ -216,7 +152,6 @@ class CertificateChainValidator { } } - // // first, we validate the chain using the standard validation // solution; if we do not find any errors, we are done; if we // fail the standard validation, we re-validate again below, @@ -393,14 +328,14 @@ class CertificateChainValidator { } private void closeSocketThrowException( - SSLSocket socket, String errorMessage, String defaultErrorMessage) - throws SSLHandshakeException, IOException { + SSLSocket socket, String errorMessage, String defaultErrorMessage) + throws IOException { closeSocketThrowException( socket, errorMessage != null ? errorMessage : defaultErrorMessage); } - private void closeSocketThrowException(SSLSocket socket, String errorMessage) - throws SSLHandshakeException, IOException { + private void closeSocketThrowException(SSLSocket socket, + String errorMessage) throws IOException { if (HttpLog.LOGV) { HttpLog.v("validation error: " + errorMessage); } @@ -416,29 +351,4 @@ class CertificateChainValidator { throw new SSLHandshakeException(errorMessage); } - - /** - * @param sslContext The SSL context shared accross all the SSL sessions - * @param host The host associated with the session - * @return A suitable SSL session from the SSL context - */ - private SSLSession getSSLSession(SSLContext sslContext, HttpHost host) { - if (sslContext != null && host != null) { - Enumeration en = sslContext.getClientSessionContext().getIds(); - while (en.hasMoreElements()) { - byte[] id = (byte[]) en.nextElement(); - if (id != null) { - SSLSession session = - sslContext.getClientSessionContext().getSession(id); - if (session.isValid() && - host.getHostName().equals(session.getPeerHost()) && - host.getPort() == session.getPeerPort()) { - return session; - } - } - } - } - - return null; - } } diff --git a/core/java/android/net/http/RequestHandle.java b/core/java/android/net/http/RequestHandle.java index 65e6117d2de0e638a53873e5880eb8af3d4ae9c4..c4ee5b0da0e2bfe43082616c705cff3d0dbdc072 100644 --- a/core/java/android/net/http/RequestHandle.java +++ b/core/java/android/net/http/RequestHandle.java @@ -55,7 +55,7 @@ public class RequestHandle { private final static String AUTHORIZATION_HEADER = "Authorization"; private final static String PROXY_AUTHORIZATION_HEADER = "Proxy-Authorization"; - private final static int MAX_REDIRECT_COUNT = 16; + public final static int MAX_REDIRECT_COUNT = 16; /** * Creates a new request session. @@ -106,6 +106,14 @@ public class RequestHandle { return mRedirectCount >= MAX_REDIRECT_COUNT; } + public int getRedirectCount() { + return mRedirectCount; + } + + public void setRedirectCount(int count) { + mRedirectCount = count; + } + /** * Create and queue a redirect request. * diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java index ed7c3663ce285ccbb48e9a8525d18254bb605e1c..7590bfef4535559615ba810bdd9f9e28a9f26640 100644 --- a/core/java/android/os/BatteryStats.java +++ b/core/java/android/os/BatteryStats.java @@ -1,33 +1,44 @@ package android.os; -import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.Formatter; import java.util.Map; +import android.util.Log; +import android.util.Printer; import android.util.SparseArray; /** * A class providing access to battery usage statistics, including information on * wakelocks, processes, packages, and services. All times are represented in microseconds * except where indicated otherwise. + * @hide */ -public abstract class BatteryStats { +public abstract class BatteryStats implements Parcelable { + private static final boolean LOCAL_LOGV = false; + /** - * A constant indicating a partial wake lock. + * A constant indicating a partial wake lock timer. */ public static final int WAKE_TYPE_PARTIAL = 0; /** - * A constant indicating a full wake lock. + * A constant indicating a full wake lock timer. */ public static final int WAKE_TYPE_FULL = 1; /** - * A constant indicating a window wake lock. + * A constant indicating a window wake lock timer. */ public static final int WAKE_TYPE_WINDOW = 2; + + /** + * A constant indicating a sensor timer. + * + * {@hide} + */ + public static final int SENSOR = 3; /** * Include all of the data in the stats, including previously saved data. @@ -48,6 +59,22 @@ public abstract class BatteryStats { * Include only the run since the last time the device was unplugged in the stats. */ public static final int STATS_UNPLUGGED = 3; + + /** + * Bump the version on this if the checkin format changes. + */ + private static final int BATTERY_STATS_CHECKIN_VERSION = 1; + + // TODO: Update this list if you add/change any stats above. + private static final String[] STAT_NAMES = { "total", "last", "current", "unplugged" }; + + private static final String APK_DATA = "apk"; + private static final String PROCESS_DATA = "process"; + private static final String SENSOR_DATA = "sensor"; + private static final String WAKELOCK_DATA = "wakelock"; + private static final String NETWORK_DATA = "network"; + private static final String BATTERY_DATA = "battery"; + private static final String MISC_DATA = "misc"; private final StringBuilder mFormatBuilder = new StringBuilder(8); private final Formatter mFormatter = new Formatter(mFormatBuilder); @@ -69,11 +96,16 @@ public abstract class BatteryStats { * Returns the total time in microseconds associated with this Timer for the * selected type of statistics. * - * @param now system uptime time in microseconds + * @param batteryRealtime system realtime on battery in microseconds * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT * @return a time in microseconds */ - public abstract long getTotalTime(long now, int which); + public abstract long getTotalTime(long batteryRealtime, int which); + + /** + * Temporary for debugging. + */ + public abstract void logState(); } /** @@ -115,8 +147,28 @@ public abstract class BatteryStats { * @return a Map from Strings to Uid.Pkg objects. */ public abstract Map getPackageStats(); + + /** + * {@hide} + */ + public abstract int getUid(); + + /** + * {@hide} + */ + public abstract long getTcpBytesReceived(int which); + + /** + * {@hide} + */ + public abstract long getTcpBytesSent(int which); public static abstract class Sensor { + // Magic sensor number for the GPS. + public static final int GPS = -10000; + + public abstract int getHandle(); + public abstract Timer getSensorTime(); } @@ -173,11 +225,11 @@ public abstract class BatteryStats { /** * Returns the amount of time spent started. * - * @param now elapsed realtime in microseconds. + * @param batteryUptime elapsed uptime on battery in microseconds. * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT. * @return */ - public abstract long getStartTime(long now, int which); + public abstract long getStartTime(long batteryUptime, int which); /** * Returns the total number of times startService() has been called. @@ -200,7 +252,28 @@ public abstract class BatteryStats { * Returns the number of times the device has been started. */ public abstract int getStartCount(); - + + /** + * Returns the time in milliseconds that the screen has been on while the device was + * running on battery. + * + * {@hide} + */ + public abstract long getScreenOnTime(long batteryRealtime, int which); + + /** + * Returns the time in milliseconds that the phone has been on while the device was + * running on battery. + * + * {@hide} + */ + public abstract long getPhoneOnTime(long batteryRealtime, int which); + + /** + * Return whether we are currently running on battery. + */ + public abstract boolean getIsOnBattery(); + /** * Returns a SparseArray containing the statistics for each uid. */ @@ -312,17 +385,20 @@ public abstract class BatteryStats { * * @param sb a StringBuilder object. * @param timer a Timer object contining the wakelock times. - * @param now the current time in microseconds. + * @param batteryRealtime the current on-battery time in microseconds. * @param name the name of the wakelock. * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT. * @param linePrefix a String to be prepended to each line of output. * @return the line prefix */ - private final String printWakeLock(StringBuilder sb, Timer timer, long now, - String name, int which, String linePrefix) { + private static final String printWakeLock(StringBuilder sb, Timer timer, + long batteryRealtime, String name, int which, String linePrefix) { + if (timer != null) { // Convert from microseconds to milliseconds with rounding - long totalTimeMillis = (timer.getTotalTime(now, which) + 500) / 1000; + long totalTimeMicros = timer.getTotalTime(batteryRealtime, which); + long totalTimeMillis = (totalTimeMicros + 500) / 1000; + int count = timer.getCount(which); if (totalTimeMillis != 0) { sb.append(linePrefix); @@ -337,40 +413,225 @@ public abstract class BatteryStats { } return linePrefix; } + + /** + * Checkin version of wakelock printer. Prints simple comma-separated list. + * + * @param sb a StringBuilder object. + * @param timer a Timer object contining the wakelock times. + * @param now the current time in microseconds. + * @param name the name of the wakelock. + * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT. + * @param linePrefix a String to be prepended to each line of output. + * @return the line prefix + */ + private static final String printWakeLockCheckin(StringBuilder sb, Timer timer, long now, + String name, int which, String linePrefix) { + long totalTimeMicros = 0; + int count = 0; + if (timer != null) { + totalTimeMicros = timer.getTotalTime(now, which); + count = timer.getCount(which); + } + sb.append(linePrefix); + sb.append((totalTimeMicros + 500) / 1000); // microseconds to milliseconds with rounding + sb.append(','); + sb.append(name); + sb.append(','); + sb.append(count); + return ","; + } + + /** + * Dump a comma-separated line of values for terse checkin mode. + * + * @param pw the PageWriter to dump log to + * @param category category of data (e.g. "total", "last", "unplugged", "current" ) + * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" , "process", "network") + * @param args type-dependent data arguments + */ + private static final void dumpLine(PrintWriter pw, int uid, String category, String type, + Object... args ) { + pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(','); + pw.print(uid); pw.print(','); + pw.print(category); pw.print(','); + pw.print(type); + + for (Object arg : args) { + pw.print(','); + pw.print(arg); + } + pw.print('\n'); + } + + /** + * Checkin server version of dump to produce more compact, computer-readable log. + * + * NOTE: all times are expressed in 'ms'. + * @param fd + * @param pw + * @param which + */ + private final void dumpCheckinLocked(PrintWriter pw, int which) { + final long rawUptime = SystemClock.uptimeMillis() * 1000; + final long rawRealtime = SystemClock.elapsedRealtime() * 1000; + final long batteryUptime = getBatteryUptime(rawUptime); + final long batteryRealtime = getBatteryRealtime(rawRealtime); + final long whichBatteryUptime = computeBatteryUptime(rawUptime, which); + final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which); + final long totalRealtime = computeRealtime(rawRealtime, which); + final long totalUptime = computeUptime(rawUptime, which); + final long screenOnTime = getScreenOnTime(batteryRealtime, which); + final long phoneOnTime = getPhoneOnTime(batteryRealtime, which); + + StringBuilder sb = new StringBuilder(128); + + String category = STAT_NAMES[which]; + + // Dump "battery" stat + dumpLine(pw, 0 /* uid */, category, BATTERY_DATA, + which == STATS_TOTAL ? getStartCount() : "N/A", + whichBatteryUptime / 1000, whichBatteryRealtime / 1000, + totalUptime / 1000, totalRealtime / 1000); + + // Dump misc stats + dumpLine(pw, 0 /* uid */, category, MISC_DATA, + screenOnTime / 1000, phoneOnTime / 1000); + + SparseArray uidStats = getUidStats(); + final int NU = uidStats.size(); + for (int iu = 0; iu < NU; iu++) { + final int uid = uidStats.keyAt(iu); + Uid u = uidStats.valueAt(iu); + // Dump Network stats per uid, if any + long rx = u.getTcpBytesReceived(which); + long tx = u.getTcpBytesSent(which); + if (rx > 0 || tx > 0) dumpLine(pw, uid, category, NETWORK_DATA, rx, tx); - @SuppressWarnings("unused") - private final void dumpLocked(FileDescriptor fd, PrintWriter pw, String prefix, int which) { - long uSecTime = SystemClock.elapsedRealtime() * 1000; - final long uSecNow = getBatteryUptime(uSecTime); + Map wakelocks = u.getWakelockStats(); + if (wakelocks.size() > 0) { + for (Map.Entry ent + : wakelocks.entrySet()) { + Uid.Wakelock wl = ent.getValue(); + String linePrefix = ""; + sb.setLength(0); + linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_FULL), batteryRealtime, + "full", which, linePrefix); + linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), batteryRealtime, + "partial", which, linePrefix); + linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), batteryRealtime, + "window", which, linePrefix); + + // Only log if we had at lease one wakelock... + if (sb.length() > 0) { + dumpLine(pw, uid, category, WAKELOCK_DATA, ent.getKey(), sb.toString()); + } + } + } + + Map sensors = u.getSensorStats(); + if (sensors.size() > 0) { + for (Map.Entry ent + : sensors.entrySet()) { + Uid.Sensor se = ent.getValue(); + int sensorNumber = ent.getKey(); + Timer timer = se.getSensorTime(); + if (timer != null) { + // Convert from microseconds to milliseconds with rounding + long totalTime = (timer.getTotalTime(batteryRealtime, which) + 500) / 1000; + int count = timer.getCount(which); + if (totalTime != 0) { + dumpLine(pw, uid, category, SENSOR_DATA, sensorNumber, totalTime, count); + } + } + } + } - StringBuilder sb = new StringBuilder(128); - if (which == STATS_TOTAL) { - pw.println(prefix + "Current and Historic Battery Usage Statistics:"); - pw.println(prefix + " System starts: " + getStartCount()); - } else if (which == STATS_LAST) { - pw.println(prefix + "Last Battery Usage Statistics:"); - } else { - pw.println(prefix + "Current Battery Usage Statistics:"); + Map processStats = u.getProcessStats(); + if (processStats.size() > 0) { + for (Map.Entry ent + : processStats.entrySet()) { + Uid.Proc ps = ent.getValue(); + + long userTime = ps.getUserTime(which); + long systemTime = ps.getSystemTime(which); + int starts = ps.getStarts(which); + + if (userTime != 0 || systemTime != 0 || starts != 0) { + dumpLine(pw, uid, category, PROCESS_DATA, + ent.getKey(), // proc + userTime * 10, // cpu time in ms + systemTime * 10, // user time in ms + starts); // process starts + } + } + } + + Map packageStats = u.getPackageStats(); + if (packageStats.size() > 0) { + for (Map.Entry ent + : packageStats.entrySet()) { + + Uid.Pkg ps = ent.getValue(); + int wakeups = ps.getWakeups(which); + Map serviceStats = ps.getServiceStats(); + for (Map.Entry sent + : serviceStats.entrySet()) { + BatteryStats.Uid.Pkg.Serv ss = sent.getValue(); + long startTime = ss.getStartTime(batteryUptime, which); + int starts = ss.getStarts(which); + int launches = ss.getLaunches(which); + if (startTime != 0 || starts != 0 || launches != 0) { + dumpLine(pw, uid, category, APK_DATA, + wakeups, // wakeup alarms + ent.getKey(), // Apk + sent.getKey(), // service + startTime / 1000, // time spent started, in ms + starts, + launches); + } + } + } + } } - long batteryUptime = computeBatteryUptime(uSecNow, which); - long batteryRealtime = computeBatteryRealtime(getBatteryRealtime(uSecTime), which); - long elapsedRealtime = computeRealtime(uSecTime, which); - long uptime = computeUptime(SystemClock.uptimeMillis() * 1000, which); + } + + @SuppressWarnings("unused") + private final void dumpLocked(Printer pw, String prefix, int which) { + final long rawUptime = SystemClock.uptimeMillis() * 1000; + final long rawRealtime = SystemClock.elapsedRealtime() * 1000; + final long batteryUptime = getBatteryUptime(rawUptime); + final long batteryRealtime = getBatteryUptime(rawRealtime); + + final long whichBatteryUptime = computeBatteryUptime(rawUptime, which); + final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which); + final long totalRealtime = computeRealtime(rawRealtime, which); + final long totalUptime = computeUptime(rawUptime, which); + + StringBuilder sb = new StringBuilder(128); pw.println(prefix - + " On battery: " + formatTimeMs(batteryUptime / 1000) + "(" - + formatRatioLocked(batteryUptime, batteryRealtime) + + " Time on battery: " + formatTimeMs(whichBatteryUptime / 1000) + + "(" + formatRatioLocked(whichBatteryUptime, totalRealtime) + ") uptime, " - + formatTimeMs(batteryRealtime / 1000) + "(" - + formatRatioLocked(batteryRealtime, elapsedRealtime) + + formatTimeMs(whichBatteryRealtime / 1000) + "(" + + formatRatioLocked(whichBatteryRealtime, totalRealtime) + ") realtime"); pw.println(prefix + " Total: " - + formatTimeMs(uptime / 1000) + + formatTimeMs(totalUptime / 1000) + "uptime, " - + formatTimeMs(elapsedRealtime / 1000) + + formatTimeMs(totalRealtime / 1000) + "realtime"); - + + long screenOnTime = getScreenOnTime(batteryRealtime, which); + long phoneOnTime = getPhoneOnTime(batteryRealtime, which); + pw.println(prefix + + " Time with screen on: " + formatTimeMs(screenOnTime / 1000) + + "(" + formatRatioLocked(screenOnTime, whichBatteryRealtime) + + "), time with phone on: " + formatTimeMs(phoneOnTime / 1000) + + "(" + formatRatioLocked(phoneOnTime, whichBatteryRealtime) + ")"); + pw.println(" "); SparseArray uidStats = getUidStats(); @@ -380,6 +641,13 @@ public abstract class BatteryStats { Uid u = uidStats.valueAt(iu); pw.println(prefix + " #" + uid + ":"); boolean uidActivity = false; + + long tcpReceived = u.getTcpBytesReceived(which); + long tcpSent = u.getTcpBytesSent(which); + if (tcpReceived != 0 || tcpSent != 0) { + pw.println(prefix + " Network: " + tcpReceived + " bytes received, " + + tcpSent + " bytes sent"); + } Map wakelocks = u.getWakelockStats(); if (wakelocks.size() > 0) { @@ -391,13 +659,15 @@ public abstract class BatteryStats { sb.append(prefix); sb.append(" Wake lock "); sb.append(ent.getKey()); - linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_FULL), uSecNow, + linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_FULL), batteryRealtime, "full", which, linePrefix); - linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), uSecNow, + linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), batteryRealtime, "partial", which, linePrefix); - linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), uSecNow, + linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), batteryRealtime, "window", which, linePrefix); - if (linePrefix.equals(": ")) { + if (!linePrefix.equals(": ")) { + sb.append(" realtime"); + } else { sb.append(": (nothing executed)"); } pw.println(sb.toString()); @@ -414,23 +684,30 @@ public abstract class BatteryStats { sb.setLength(0); sb.append(prefix); sb.append(" Sensor "); - sb.append(sensorNumber); + int handle = se.getHandle(); + if (handle == Uid.Sensor.GPS) { + sb.append("GPS"); + } else { + sb.append(handle); + } + sb.append(": "); Timer timer = se.getSensorTime(); if (timer != null) { // Convert from microseconds to milliseconds with rounding - long totalTime = (timer.getTotalTime(uSecNow, which) + 500) / 1000; + long totalTime = (timer.getTotalTime(batteryRealtime, which) + 500) / 1000; int count = timer.getCount(which); + //timer.logState(); if (totalTime != 0) { - sb.append(": "); sb.append(formatTimeMs(totalTime)); - sb.append(' '); - sb.append('('); + sb.append("realtime ("); sb.append(count); sb.append(" times)"); + } else { + sb.append("(not used)"); } } else { - sb.append(": (none used)"); + sb.append("(not used)"); } pw.println(sb.toString()); @@ -478,13 +755,14 @@ public abstract class BatteryStats { for (Map.Entry sent : serviceStats.entrySet()) { BatteryStats.Uid.Pkg.Serv ss = sent.getValue(); - long startTime = ss.getStartTime(uSecNow, which); + long startTime = ss.getStartTime(batteryUptime, which); int starts = ss.getStarts(which); int launches = ss.getLaunches(which); if (startTime != 0 || starts != 0 || launches != 0) { pw.println(prefix + " Service " + sent.getKey() + ":"); - pw.println(prefix + " Time spent started: " - + formatTimeMs(startTime / 1000)); + pw.println(prefix + " Created for: " + + formatTimeMs(startTime / 1000) + + " uptime"); pw.println(prefix + " Starts: " + starts + ", launches: " + launches); apkActivity = true; @@ -506,18 +784,45 @@ public abstract class BatteryStats { /** * Dumps a human-readable summary of the battery statistics to the given PrintWriter. * - * @param fd a FileDescriptor, currently unused. - * @param pw a PrintWriter to receive the dump output. - * @param args an array of Strings, currently unused. + * @param pw a Printer to receive the dump output. */ @SuppressWarnings("unused") - public void dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args) { - synchronized (this) { - dumpLocked(fd, pw, "", STATS_TOTAL); - pw.println(""); - dumpLocked(fd, pw, "", STATS_LAST); - pw.println(""); - dumpLocked(fd, pw, "", STATS_CURRENT); + public void dumpLocked(Printer pw) { + pw.println("Total Statistics (Current and Historic):"); + pw.println(" System starts: " + getStartCount() + + ", currently on battery: " + getIsOnBattery()); + dumpLocked(pw, "", STATS_TOTAL); + pw.println(""); + pw.println("Last Run Statistics (Previous run of system):"); + dumpLocked(pw, "", STATS_LAST); + pw.println(""); + pw.println("Current Battery Statistics (Currently running system):"); + dumpLocked(pw, "", STATS_CURRENT); + pw.println(""); + pw.println("Unplugged Statistics (Since last unplugged from power):"); + dumpLocked(pw, "", STATS_UNPLUGGED); + } + + @SuppressWarnings("unused") + public void dumpCheckinLocked(PrintWriter pw, String[] args) { + boolean isUnpluggedOnly = false; + + for (String arg : args) { + if ("-u".equals(arg)) { + if (LOCAL_LOGV) Log.v("BatteryStats", "Dumping unplugged data"); + isUnpluggedOnly = true; + } + } + + if (isUnpluggedOnly) { + dumpCheckinLocked(pw, STATS_UNPLUGGED); + } + else { + dumpCheckinLocked(pw, STATS_TOTAL); + dumpCheckinLocked(pw, STATS_LAST); + dumpCheckinLocked(pw, STATS_UNPLUGGED); + dumpCheckinLocked(pw, STATS_CURRENT); } } + } diff --git a/core/java/android/os/Binder.java b/core/java/android/os/Binder.java index 528e6bd6be5023865b28fad9d46c4a23f7fff489..df10c6aef904de648e2d0cd55aaa984a8615e14f 100644 --- a/core/java/android/os/Binder.java +++ b/core/java/android/os/Binder.java @@ -33,7 +33,7 @@ import java.lang.reflect.Modifier; * the standard support creating a local implementation of such an object. * *

          Most developers will not implement this class directly, instead using the - * aidl tool to describe the desired + * aidl tool to describe the desired * interface, having it generate the appropriate Binder subclass. You can, * however, derive directly from Binder to implement your own custom RPC * protocol or simply instantiate a raw Binder object directly to use as a @@ -194,18 +194,15 @@ public class Binder implements IBinder { return true; } else if (code == DUMP_TRANSACTION) { ParcelFileDescriptor fd = data.readFileDescriptor(); - FileOutputStream fout = fd != null - ? new FileOutputStream(fd.getFileDescriptor()) : null; - PrintWriter pw = fout != null ? new PrintWriter(fout) : null; - if (pw != null) { - String[] args = data.readStringArray(); - dump(fd.getFileDescriptor(), pw, args); - pw.flush(); - } + String[] args = data.readStringArray(); if (fd != null) { try { - fd.close(); - } catch (IOException e) { + dump(fd.getFileDescriptor(), args); + } finally { + try { + fd.close(); + } catch (IOException e) { + } } } return true; @@ -213,6 +210,20 @@ public class Binder implements IBinder { return false; } + /** + * Implemented to call the more convenient version + * {@link #dump(FileDescriptor, PrintWriter, String[])}. + */ + public void dump(FileDescriptor fd, String[] args) { + FileOutputStream fout = new FileOutputStream(fd); + PrintWriter pw = new PrintWriter(fout); + try { + dump(fd, pw, args); + } finally { + pw.flush(); + } + } + /** * Print the object's state into the given stream. * @@ -302,6 +313,17 @@ final class BinderProxy implements IBinder { throws RemoteException; public native boolean unlinkToDeath(DeathRecipient recipient, int flags); + public void dump(FileDescriptor fd, String[] args) throws RemoteException { + Parcel data = Parcel.obtain(); + data.writeFileDescriptor(fd); + data.writeStringArray(args); + try { + transact(DUMP_TRANSACTION, data, null, 0); + } finally { + data.recycle(); + } + } + BinderProxy() { mSelf = new WeakReference(this); } diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java index cdf907b1ad05da5435a86b2d7c134507045c2a83..467c17f7d3a196fd5f408281f6bb5c0b8bafe889 100644 --- a/core/java/android/os/Build.java +++ b/core/java/android/os/Build.java @@ -26,6 +26,9 @@ public class Build { /** Either a changelist number, or a label like "M4-rc20". */ public static final String ID = getString("ro.build.id"); + /** A build ID string meant for displaying to the user */ + public static final String DISPLAY = getString("ro.build.display.id"); + /** The name of the overall product. */ public static final String PRODUCT = getString("ro.product.name"); diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java index 5f7f91f4b9b07ed7e27991634e2c729c5b8a80c3..950bb09d03c4cf02654673e971a2d81747bb92da 100644 --- a/core/java/android/os/Debug.java +++ b/core/java/android/os/Debug.java @@ -17,6 +17,7 @@ package android.os; import java.io.FileOutputStream; +import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; @@ -28,12 +29,13 @@ import dalvik.bytecode.Opcodes; import dalvik.system.VMDebug; -/** Provides various debugging functions for Android applications, including +/** + * Provides various debugging functions for Android applications, including * tracing and allocation counts. *

          Logging Trace Files

          *

          Debug can create log files that give details about an application, such as * a call stack and start/stop times for any running methods. See Running the Traceview Debugging Program for +href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer for * information about reading trace files. To start logging trace files, call one * of the startMethodTracing() methods. To stop tracing, call * {@link #stopMethodTracing()}. @@ -285,7 +287,7 @@ public final class Debug /** * Start method tracing with default log name and buffer size. See Running the Traceview Debugging Program for +href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer for * information about reading these files. Call stopMethodTracing() to stop * tracing. */ @@ -297,7 +299,7 @@ href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Progra * Start method tracing, specifying the trace log file name. The trace * file will be put under "/sdcard" unless an absolute path is given. * See Running the Traceview Debugging Program for + href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer for * information about reading trace files. * * @param traceName Name for the trace log file to create. @@ -313,7 +315,7 @@ href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Progra * Start method tracing, specifying the trace log file name and the * buffer size. The trace files will be put under "/sdcard" unless an * absolute path is given. See Running the Traceview Debugging Program for + href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer for * information about reading trace files. * @param traceName Name for the trace log file to create. * If no name argument is given, this value defaults to "/sdcard/dmtrace.trace". @@ -330,7 +332,7 @@ href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Progra * Start method tracing, specifying the trace log file name and the * buffer size. The trace files will be put under "/sdcard" unless an * absolute path is given. See Running the Traceview Debugging Program for + href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer for * information about reading trace files. * *

          @@ -580,6 +582,18 @@ href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Progra return VMDebug.getLoadedClassCount(); } + /** + * Dump "hprof" data to the specified file. This will cause a GC. + * + * @param fileName Full pathname of output file (e.g. "/sdcard/dump.hprof"). + * @throws UnsupportedOperationException if the VM was built without + * HPROF support. + * @throws IOException if an error occurs while opening or writing files. + */ + public static void dumpHprofData(String fileName) throws IOException { + VMDebug.dumpHprofData(fileName); + } + /** * Returns the number of sent transactions from this process. * @return The number of sent transactions or -1 if it could not read t. diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java index e37b551903adc420ab7d2f9508e959f651880f52..f761e8e3d7138c65e5972a27d2c4ba561ea6bdbf 100644 --- a/core/java/android/os/Environment.java +++ b/core/java/android/os/Environment.java @@ -74,6 +74,18 @@ public class Environment { */ public static final String MEDIA_UNMOUNTED = "unmounted"; + /** + * getExternalStorageState() returns MEDIA_CHECKING if the media is present + * and being disk-checked + */ + public static final String MEDIA_CHECKING = "checking"; + + /** + * getExternalStorageState() returns MEDIA_NOFS if the media is present + * but is blank or is using an unsupported filesystem + */ + public static final String MEDIA_NOFS = "nofs"; + /** * getExternalStorageState() returns MEDIA_MOUNTED if the media is present * and mounted at its mount point with read/write access. diff --git a/core/java/android/os/IBinder.java b/core/java/android/os/IBinder.java index 3ec0e9b4db675eb6613e695e27ca7e95bf658d57..5c40c9a041ad8554c0101ebc4942305e387db6b6 100644 --- a/core/java/android/os/IBinder.java +++ b/core/java/android/os/IBinder.java @@ -16,6 +16,9 @@ package android.os; +import java.io.FileDescriptor; +import java.io.PrintWriter; + /** * Base interface for a remotable object, the core part of a lightweight * remote procedure call mechanism designed for high performance when @@ -144,6 +147,14 @@ public interface IBinder { */ public IInterface queryLocalInterface(String descriptor); + /** + * Print the object's state into the given stream. + * + * @param fd The raw file descriptor that the dump is being sent to. + * @param args additional arguments to the dump request. + */ + public void dump(FileDescriptor fd, String[] args) throws RemoteException; + /** * Perform a generic operation with the object. * diff --git a/core/java/android/os/ICheckinService.aidl b/core/java/android/os/ICheckinService.aidl index 70ad28e4e469888de8d96cc7548e8ac6d684cf8a..e56b55d78cd518b0152ffa937d8faa44aa78009a 100644 --- a/core/java/android/os/ICheckinService.aidl +++ b/core/java/android/os/ICheckinService.aidl @@ -26,6 +26,15 @@ import android.os.IParentalControlCallback; * {@hide} */ interface ICheckinService { + /** Synchronously attempt a checkin with the server, return true + * on success. + * @throws IllegalStateException whenever an error occurs. The + * cause of the exception will be the real exception: + * IOException for network errors, JSONException for invalid + * server responses, etc. + */ + boolean checkin(); + /** Direct submission of crash data; returns after writing the crash. */ void reportCrashSync(in byte[] crashData); diff --git a/core/java/android/os/IMountService.aidl b/core/java/android/os/IMountService.aidl index 0397446155bb1553043f43ebb61dbc0f32d95a28..96d44b6441dd87d0bfb714d65362b71ae807a3c0 100644 --- a/core/java/android/os/IMountService.aidl +++ b/core/java/android/os/IMountService.aidl @@ -48,4 +48,31 @@ interface IMountService * Safely unmount external storage at given mount point. */ void unmountMedia(String mountPoint); + + /** + * Format external storage given a mount point. + */ + void formatMedia(String mountPoint); + + /** + * Returns true if media notification sounds are enabled. + */ + boolean getPlayNotificationSounds(); + + /** + * Sets whether or not media notification sounds are played. + */ + void setPlayNotificationSounds(boolean value); + + /** + * Returns true if USB Mass Storage is automatically started + * when a UMS host is detected. + */ + boolean getAutoStartUms(); + + /** + * Sets whether or not USB Mass Storage is automatically started + * when a UMS host is detected. + */ + void setAutoStartUms(boolean value); } diff --git a/core/java/android/os/INetStatService.aidl b/core/java/android/os/INetStatService.aidl index fb840d84fab34bab52655d03c7859870f18e747e..a8f3de0e044c6eb352b5e071bdf4f2d039471951 100644 --- a/core/java/android/os/INetStatService.aidl +++ b/core/java/android/os/INetStatService.aidl @@ -17,14 +17,19 @@ package android.os; /** - * Retrieves packet and byte counts for the phone data interface. + * Retrieves packet and byte counts for the phone data interface, + * and for all interfaces. * Used for the data activity icon and the phone status in Settings. * * {@hide} */ interface INetStatService { - int getTxPackets(); - int getRxPackets(); - int getTxBytes(); - int getRxBytes(); + long getMobileTxPackets(); + long getMobileRxPackets(); + long getMobileTxBytes(); + long getMobileRxBytes(); + long getTotalTxPackets(); + long getTotalRxPackets(); + long getTotalTxBytes(); + long getTotalRxBytes(); } diff --git a/core/java/android/os/IPowerManager.aidl b/core/java/android/os/IPowerManager.aidl index e48f1523a6beb529cdb9c82343fb351d0877ff48..5486920249cfad61bb70257e9022b49eec3930ce 100644 --- a/core/java/android/os/IPowerManager.aidl +++ b/core/java/android/os/IPowerManager.aidl @@ -29,4 +29,5 @@ interface IPowerManager void setStayOnSetting(int val); long getScreenOnTime(); void preventScreenOn(boolean prevent); + void setScreenBrightnessOverride(int brightness); } diff --git a/core/java/android/os/NetStat.java b/core/java/android/os/NetStat.java index 7312236d743eb7cc875d17c6838cf942327653a0..e294cdf11c50d560b5c1f6ddf34f5c57cd49f75e 100644 --- a/core/java/android/os/NetStat.java +++ b/core/java/android/os/NetStat.java @@ -16,36 +16,232 @@ package android.os; +import android.util.Log; + +import java.io.File; +import java.io.RandomAccessFile; +import java.io.IOException; + /** @hide */ -public class NetStat{ +public class NetStat { + + // Logging tag. + private final static String TAG = "netstat"; + + // We pre-create all the File objects so we don't spend a lot of + // CPU at runtime converting from Java Strings to byte[] for the + // kernel calls. + private final static File[] MOBILE_TX_PACKETS = mobileFiles("tx_packets"); + private final static File[] MOBILE_RX_PACKETS = mobileFiles("rx_packets"); + private final static File[] MOBILE_TX_BYTES = mobileFiles("tx_bytes"); + private final static File[] MOBILE_RX_BYTES = mobileFiles("rx_bytes"); + private final static File SYS_CLASS_NET_DIR = new File("/sys/class/net"); /** - * Get total number of tx packets sent through ppp0 + * Get total number of tx packets sent through rmnet0 or ppp0 * - * @return number of Tx packets through ppp0 + * @return number of Tx packets through rmnet0 or ppp0 */ + public static long getMobileTxPkts() { + return getMobileStat(MOBILE_TX_PACKETS); + } - public native static int netStatGetTxPkts(); + /** + * Get total number of rx packets received through rmnet0 or ppp0 + * + * @return number of Rx packets through rmnet0 or ppp0 + */ + public static long getMobileRxPkts() { + return getMobileStat(MOBILE_RX_PACKETS); + } /** - * Get total number of rx packets received through ppp0 + * Get total number of tx bytes received through rmnet0 or ppp0 * - * @return number of Rx packets through ppp0 + * @return number of Tx bytes through rmnet0 or ppp0 */ - public native static int netStatGetRxPkts(); + public static long getMobileTxBytes() { + return getMobileStat(MOBILE_TX_BYTES); + } - /** - * Get total number of tx bytes received through ppp0 + /** + * Get total number of rx bytes received through rmnet0 or ppp0 * - * @return number of Tx bytes through ppp0 + * @return number of Rx bytes through rmnet0 or ppp0 */ - public native static int netStatGetTxBytes(); + public static long getMobileRxBytes() { + return getMobileStat(MOBILE_RX_BYTES); + } /** - * Get total number of rx bytes received through ppp0 + * Get the total number of packets sent through all network interfaces. * - * @return number of Rx bytes through ppp0 + * @return the number of packets sent through all network interfaces */ - public native static int netStatGetRxBytes(); + public static long getTotalTxPkts() { + return getTotalStat("tx_packets"); + } + + /** + * Get the total number of packets received through all network interfaces. + * + * @return the number of packets received through all network interfaces + */ + public static long getTotalRxPkts() { + return getTotalStat("rx_packets"); + } + + /** + * Get the total number of bytes sent through all network interfaces. + * + * @return the number of bytes sent through all network interfaces + */ + public static long getTotalTxBytes() { + return getTotalStat("tx_bytes"); + } + + /** + * Get the total number of bytes received through all network interfaces. + * + * @return the number of bytes received through all network interfaces + */ + public static long getTotalRxBytes() { + return getTotalStat("rx_bytes"); + } + + /** + * Gets network bytes sent for this UID. + * The statistics are across all interfaces. + * The statistics come from /proc/uid_stat. + * + * {@see android.os.Process#myUid()}. + * + * @param uid + * @return byte count + */ + public static long getUidTxBytes(int uid) { + return getNumberFromFilePath("/proc/uid_stat/" + uid + "/tcp_snd"); + } + + /** + * Gets network bytes received for this UID. + * The statistics are across all interfaces. + * The statistics come from /proc/uid_stat. + * + * {@see android.os.Process#myUid()}. + * + * @param uid + * @return byte count + */ + public static long getUidRxBytes(int uid) { + return getNumberFromFilePath("/proc/uid_stat/" + uid + "/tcp_rcv"); + } + + /** + * Returns the array of two possible File locations for a given + * statistic. + */ + private static File[] mobileFiles(String whatStat) { + // Note that we stat them at runtime to see which is + // available, rather than here, to guard against the files + // coming & going later as modules shut down (e.g. airplane + // mode) and whatnot. The runtime stat() isn't expensive compared + // to the previous charset conversion that happened before we + // were reusing File instances. + File[] files = new File[2]; + files[0] = new File("/sys/class/net/rmnet0/statistics/" + whatStat); + files[1] = new File("/sys/class/net/ppp0/statistics/" + whatStat); + return files; + } + + private static long getTotalStat(String whatStat) { + File netdir = new File("/sys/class/net"); + + File[] nets = SYS_CLASS_NET_DIR.listFiles(); + if (nets == null) { + return 0; + } + long total = 0; + StringBuffer strbuf = new StringBuffer(); + for (File net : nets) { + strbuf.append(net.getPath()).append(File.separator).append("statistics") + .append(File.separator).append(whatStat); + total += getNumberFromFilePath(strbuf.toString()); + strbuf.setLength(0); + } + return total; + } + + private static long getMobileStat(File[] files) { + for (int i = 0; i < files.length; i++) { + File file = files[i]; + if (!file.exists()) { + continue; + } + try { + RandomAccessFile raf = new RandomAccessFile(file, "r"); + return getNumberFromFile(raf, file.getAbsolutePath()); + } catch (IOException e) { + Log.w(TAG, + "Exception opening TCP statistics file " + file.getAbsolutePath(), + e); + } + } + return 0L; + } + + // File will have format + private static long getNumberFromFilePath(String filename) { + RandomAccessFile raf = getFile(filename); + if (raf == null) { + return 0L; + } + return getNumberFromFile(raf, filename); + } + + // Private buffer for getNumberFromFile. Safe for re-use because + // getNumberFromFile is synchronized. + private final static byte[] buf = new byte[16]; + + private static synchronized long getNumberFromFile(RandomAccessFile raf, String filename) { + try { + raf.read(buf); + raf.close(); + } catch (IOException e) { + Log.w(TAG, "Exception getting TCP bytes from " + filename, e); + return 0L; + } finally { + if (raf != null) { + try { + raf.close(); + } catch (IOException e) { + Log.w(TAG, "Exception closing " + filename, e); + } + } + } + + long num = 0L; + for (int i = 0; i < buf.length; i++) { + if (buf[i] < '0' || buf[i] > '9') { + break; + } + num *= 10; + num += buf[i] - '0'; + } + return num; + } + + private static RandomAccessFile getFile(String filename) { + File f = new File(filename); + if (!f.canRead()) { + return null; + } + try { + return new RandomAccessFile(f, "r"); + } catch (IOException e) { + Log.w(TAG, "Exception opening TCP statistics file " + filename, e); + return null; + } + } } diff --git a/core/java/android/os/ParcelFileDescriptor.java b/core/java/android/os/ParcelFileDescriptor.java index ed138cb6788f67cb22d9fed9b08367c5bb0fcfeb..3fcb18e4a5330d2d05c6c84452e8b4c6526d58d6 100644 --- a/core/java/android/os/ParcelFileDescriptor.java +++ b/core/java/android/os/ParcelFileDescriptor.java @@ -75,6 +75,11 @@ public class ParcelFileDescriptor implements Parcelable { */ public static final int MODE_TRUNCATE = 0x04000000; + /** + * For use with {@link #open}: append to end of file while writing. + */ + public static final int MODE_APPEND = 0x02000000; + /** * Create a new ParcelFileDescriptor accessing a given file. * @@ -137,6 +142,19 @@ public class ParcelFileDescriptor implements Parcelable { return mFileDescriptor; } + /** + * Return the total size of the file representing this fd, as determined + * by stat(). Returns -1 if the fd is not a file. + */ + public native long getStatSize(); + + /** + * This is needed for implementing AssetFileDescriptor.AutoCloseOutputStream, + * and I really don't think we want it to be public. + * @hide + */ + public native long seekTo(long pos); + /** * Close the ParcelFileDescriptor. This implementation closes the underlying * OS resources allocated to represent this stream. diff --git a/core/res/res/drawable/checkbox_background.xml b/core/java/android/os/ResultReceiver.aidl similarity index 70% rename from core/res/res/drawable/checkbox_background.xml rename to core/java/android/os/ResultReceiver.aidl index 68bb17871eb7640ff94482127dcf488341aed087..28ce6d5f15b038c972f2722af6e33197206100a2 100644 --- a/core/res/res/drawable/checkbox_background.xml +++ b/core/java/android/os/ResultReceiver.aidl @@ -1,6 +1,4 @@ - - - - - +package android.os; + +parcelable ResultReceiver; diff --git a/core/java/android/os/ResultReceiver.java b/core/java/android/os/ResultReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..711d4d9e924482e6a3dcd9caf7310d121770bad8 --- /dev/null +++ b/core/java/android/os/ResultReceiver.java @@ -0,0 +1,130 @@ +/* + * 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. + */ + +package android.os; + +import com.android.internal.os.IResultReceiver; + +/** + * Generic interface for receiving a callback result from someone. Use this + * by creating a subclass and implement {@link #onReceiveResult}, which you can + * then pass to others and send through IPC, and receive results they + * supply with {@link #send}. + */ +public class ResultReceiver implements Parcelable { + final boolean mLocal; + final Handler mHandler; + + IResultReceiver mReceiver; + + class MyRunnable implements Runnable { + final int mResultCode; + final Bundle mResultData; + + MyRunnable(int resultCode, Bundle resultData) { + mResultCode = resultCode; + mResultData = resultData; + } + + public void run() { + onReceiveResult(mResultCode, mResultData); + } + } + + class MyResultReceiver extends IResultReceiver.Stub { + public void send(int resultCode, Bundle resultData) { + if (mHandler != null) { + mHandler.post(new MyRunnable(resultCode, resultData)); + } else { + onReceiveResult(resultCode, resultData); + } + } + } + + /** + * Create a new ResultReceive to receive results. Your + * {@link #onReceiveResult} method will be called from the thread running + * handler if given, or from an arbitrary thread if null. + */ + public ResultReceiver(Handler handler) { + mLocal = true; + mHandler = handler; + } + + /** + * Deliver a result to this receiver. Will call {@link #onReceiveResult}, + * always asynchronously if the receiver has supplied a Handler in which + * to dispatch the result. + * @param resultCode Arbitrary result code to deliver, as defined by you. + * @param resultData Any additional data provided by you. + */ + public void send(int resultCode, Bundle resultData) { + if (mLocal) { + if (mHandler != null) { + mHandler.post(new MyRunnable(resultCode, resultData)); + } else { + onReceiveResult(resultCode, resultData); + } + return; + } + + if (mReceiver != null) { + try { + mReceiver.send(resultCode, resultData); + } catch (RemoteException e) { + } + } + } + + /** + * Override to receive results delivered to this object. + * + * @param resultCode Arbitrary result code delivered by the sender, as + * defined by the sender. + * @param resultData Any additional data provided by the sender. + */ + protected void onReceiveResult(int resultCode, Bundle resultData) { + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel out, int flags) { + synchronized (this) { + if (mReceiver == null) { + mReceiver = new MyResultReceiver(); + } + out.writeStrongBinder(mReceiver.asBinder()); + } + } + + ResultReceiver(Parcel in) { + mLocal = false; + mHandler = null; + mReceiver = IResultReceiver.Stub.asInterface(in.readStrongBinder()); + } + + public static final Parcelable.Creator CREATOR + = new Parcelable.Creator() { + public ResultReceiver createFromParcel(Parcel in) { + return new ResultReceiver(in); + } + public ResultReceiver[] newArray(int size) { + return new ResultReceiver[size]; + } + }; +} diff --git a/core/java/android/package.html b/core/java/android/package.html index b6d2999189de4251b0d0ee5a1fceac48c137d70e..1f1be2d97e4dbbe8154e779d279fc3d15a0af1e6 100644 --- a/core/java/android/package.html +++ b/core/java/android/package.html @@ -5,6 +5,6 @@ Contains the resource classes used by standard Android applications. This package contains the resource classes that Android defines to be used in Android applications. Third party developers can use many of them also for their applications. To learn more about how to use these classes, and what a -resource is, see Resources. +resource is, see Resources and Assets. diff --git a/core/java/android/pim/ICalendar.java b/core/java/android/pim/ICalendar.java index 4a5d7e487f58da9ef62e8dd81a0468d7ac64cdd7..cc0f45ee240215befa7134b10571f735b66d726a 100644 --- a/core/java/android/pim/ICalendar.java +++ b/core/java/android/pim/ICalendar.java @@ -405,13 +405,15 @@ public class ICalendar { // TODO: get rid of this -- handle all of the parsing in one pass through // the text. private static String normalizeText(String text) { - // first we deal with line folding, by replacing all "\r\n " strings - // with nothing - text = text.replaceAll("\r\n ", ""); - // it's supposed to be \r\n, but not everyone does that text = text.replaceAll("\r\n", "\n"); text = text.replaceAll("\r", "\n"); + + // we deal with line folding, by replacing all "\n " strings + // with nothing. The RFC specifies "\r\n " to be folded, but + // we handle "\n " and "\r " too because we can get those. + text = text.replaceAll("\n ", ""); + return text; } @@ -440,7 +442,7 @@ public class ICalendar { current = parseLine(line, state, current); // if the provided component was null, we will return the root // NOTE: in this case, if the first line is not a BEGIN, a - // FormatException will get thrown. + // FormatException will get thrown. if (component == null) { component = current; } @@ -524,8 +526,7 @@ public class ICalendar { private static String extractValue(ParserState state) throws FormatException { String line = state.line; - char c = line.charAt(state.index); - if (c != ':') { + if (state.index >= line.length() || line.charAt(state.index) != ':') { throw new FormatException("Expected ':' before end of line in " + line); } diff --git a/core/java/android/pim/RecurrenceSet.java b/core/java/android/pim/RecurrenceSet.java index c6615da03eef8c600b84fd33bed7ac9e4870a643..1a287c814dcac068e60f451306c689718d1a3cfe 100644 --- a/core/java/android/pim/RecurrenceSet.java +++ b/core/java/android/pim/RecurrenceSet.java @@ -140,7 +140,6 @@ public class RecurrenceSet { recurrence = recurrence.substring(tzidx + 1); } Time time = new Time(tz); - boolean rdateNotInUtc = !tz.equals(Time.TIMEZONE_UTC); String[] rawDates = recurrence.split(","); int n = rawDates.length; long[] dates = new long[n]; diff --git a/core/java/android/preference/Preference.java b/core/java/android/preference/Preference.java index 3820f28563262fd6842ca8b3732400dd084bb703..a2554388651ada12e9e8db20efd74083ed0854b7 100644 --- a/core/java/android/preference/Preference.java +++ b/core/java/android/preference/Preference.java @@ -667,7 +667,6 @@ public class Preference implements Comparable, OnDependencyChangeLis * {@link SharedPreferences}. This should be unique for the package. * * @param key The key for the preference. - * @see #getId() */ public void setKey(String key) { mKey = key; @@ -1460,7 +1459,6 @@ public class Preference implements Comparable, OnDependencyChangeLis * @param container The Bundle in which to save the instance of this Preference. * * @see #restoreHierarchyState - * @see #dispatchSaveInstanceState * @see #onSaveInstanceState */ public void saveHierarchyState(Bundle container) { @@ -1474,7 +1472,6 @@ public class Preference implements Comparable, OnDependencyChangeLis * * @param container The Bundle in which to save the instance of this Preference. * - * @see #dispatchRestoreInstanceState * @see #saveHierarchyState * @see #onSaveInstanceState */ @@ -1503,7 +1500,6 @@ public class Preference implements Comparable, OnDependencyChangeLis * The default implementation returns null. * @see #onRestoreInstanceState * @see #saveHierarchyState - * @see #dispatchSaveInstanceState */ protected Parcelable onSaveInstanceState() { mBaseMethodCalled = true; @@ -1516,7 +1512,6 @@ public class Preference implements Comparable, OnDependencyChangeLis * @param container The Bundle that holds the previously saved state. * * @see #saveHierarchyState - * @see #dispatchRestoreInstanceState * @see #onRestoreInstanceState */ public void restoreHierarchyState(Bundle container) { @@ -1530,7 +1525,6 @@ public class Preference implements Comparable, OnDependencyChangeLis * not want to save state for their children. * * @param container The Bundle that holds the previously saved state. - * @see #dispatchSaveInstanceState * @see #restoreHierarchyState * @see #onRestoreInstanceState */ @@ -1557,7 +1551,6 @@ public class Preference implements Comparable, OnDependencyChangeLis * {@link #onSaveInstanceState}. * @see #onSaveInstanceState * @see #restoreHierarchyState - * @see #dispatchRestoreInstanceState */ protected void onRestoreInstanceState(Parcelable state) { mBaseMethodCalled = true; diff --git a/core/java/android/preference/PreferenceActivity.java b/core/java/android/preference/PreferenceActivity.java index 95970eae0276fc184d10ef52b91833feb29ef8bb..837ce916171e423e932d54b17f283b8d4dcd4656 100644 --- a/core/java/android/preference/PreferenceActivity.java +++ b/core/java/android/preference/PreferenceActivity.java @@ -103,8 +103,6 @@ public abstract class PreferenceActivity extends ListActivity implements protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - requestWindowFeature(Window.FEATURE_NO_TITLE); - setContentView(com.android.internal.R.layout.preference_list_content); mPreferenceManager = onCreatePreferenceManager(); @@ -214,6 +212,11 @@ public abstract class PreferenceActivity extends ListActivity implements public void setPreferenceScreen(PreferenceScreen preferenceScreen) { if (mPreferenceManager.setPreferences(preferenceScreen) && preferenceScreen != null) { postBindPreferences(); + CharSequence title = getPreferenceScreen().getTitle(); + // Set the title of the activity + if (title != null) { + setTitle(title); + } } } diff --git a/core/java/android/preference/PreferenceGroup.java b/core/java/android/preference/PreferenceGroup.java index 4258b4123f9c4cf57c4f483bea8e467b6047e1ed..d008fd699ed96ac264c99a071c252006c6ff9954 100644 --- a/core/java/android/preference/PreferenceGroup.java +++ b/core/java/android/preference/PreferenceGroup.java @@ -25,6 +25,7 @@ import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcelable; +import android.text.TextUtils; import android.util.AttributeSet; /** @@ -223,6 +224,9 @@ public abstract class PreferenceGroup extends Preference implements GenericInfla * @return The {@link Preference} with the key, or null. */ public Preference findPreference(CharSequence key) { + if (TextUtils.equals(getKey(), key)) { + return this; + } final int preferenceCount = getPreferenceCount(); for (int i = 0; i < preferenceCount; i++) { final Preference preference = getPreference(i); diff --git a/core/java/android/preference/PreferenceGroupAdapter.java b/core/java/android/preference/PreferenceGroupAdapter.java index 05c2952243746f9a1b8a56d72f2a0d8be563d7bf..14c0054b868befeeb0f6013651b513789b356ef7 100644 --- a/core/java/android/preference/PreferenceGroupAdapter.java +++ b/core/java/android/preference/PreferenceGroupAdapter.java @@ -88,6 +88,9 @@ class PreferenceGroupAdapter extends BaseAdapter implements OnPreferenceChangeIn public PreferenceGroupAdapter(PreferenceGroup preferenceGroup) { mPreferenceGroup = preferenceGroup; + // If this group gets or loses any children, let us know + mPreferenceGroup.setOnPreferenceChangeInternalListener(this); + mPreferenceList = new ArrayList(); mPreferenceClassNames = new ArrayList(); @@ -239,7 +242,7 @@ class PreferenceGroupAdapter extends BaseAdapter implements OnPreferenceChangeIn mHasReturnedViewTypeCount = true; } - return mPreferenceClassNames.size(); + return Math.max(1, mPreferenceClassNames.size()); } } diff --git a/core/java/android/preference/PreferenceScreen.java b/core/java/android/preference/PreferenceScreen.java index 9929b963755e03609c37822b01fe101f3ce575a2..5353b531dd068645d20b63b7b2a267ea2d412cc0 100644 --- a/core/java/android/preference/PreferenceScreen.java +++ b/core/java/android/preference/PreferenceScreen.java @@ -100,7 +100,6 @@ public final class PreferenceScreen extends PreferenceGroup implements AdapterVi * * @return An adapter that provides the {@link Preference} contained in this * {@link PreferenceScreen}. - * @see PreferenceGroupAdapter */ public ListAdapter getRootAdapter() { if (mRootAdapter == null) { diff --git a/core/java/android/preference/VolumePreference.java b/core/java/android/preference/VolumePreference.java index 6e215dcd74910e089b777e823be63d04bb336678..20702a1de4138a27e87a854e835e3fd49b9626a5 100644 --- a/core/java/android/preference/VolumePreference.java +++ b/core/java/android/preference/VolumePreference.java @@ -194,13 +194,6 @@ public class VolumePreference extends SeekBarPreference implements } private void sample() { - - // Only play a preview sample when controlling the ringer stream - if (mStreamType != AudioManager.STREAM_RING - && mStreamType != AudioManager.STREAM_NOTIFICATION) { - return; - } - onSampleStarting(this); mRingtone.play(); } diff --git a/core/java/android/provider/Browser.java b/core/java/android/provider/Browser.java index 76aa51d175c8e6ec3e50c2ea19b99fd5da6a4441..c597b3c62125dcbe8455b032e89f469ad043b91a 100644 --- a/core/java/android/provider/Browser.java +++ b/core/java/android/provider/Browser.java @@ -43,6 +43,18 @@ public class Browser { */ public static final String INITIAL_ZOOM_LEVEL = "browser.initialZoomLevel"; + /** + * The name of the extra data when starting the Browser from another + * application. + *

          + * The value is a unique identification string that will be used to + * indentify the calling application. The Browser will attempt to reuse the + * same window each time the application launches the Browser with the same + * identifier. + */ + public static final String EXTRA_APPLICATION_ID = + "com.android.browser.application_id"; + /* if you change column order you must also change indices below */ public static final String[] HISTORY_PROJECTION = new String[] { diff --git a/core/java/android/provider/Checkin.java b/core/java/android/provider/Checkin.java index ef5ededc24b11b817e4ffbe4e155cd024d01a0f5..d11a9c52f86dd40789eeafd33d146c30c7a3fb5f 100644 --- a/core/java/android/provider/Checkin.java +++ b/core/java/android/provider/Checkin.java @@ -30,10 +30,13 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; /** - * Contract class for {@link android.server.checkin.CheckinProvider}. + * Contract class for the checkin provider, used to store events and + * statistics that will be uploaded to a checkin server eventually. * Describes the exposed database schema, and offers methods to add * events and statistics to be uploaded. * + * TODO: Move this to vendor/google when we have a home for it. + * * @hide */ public final class Checkin { @@ -56,6 +59,15 @@ public final class Checkin { /** Valid tag values. Extend as necessary for your needs. */ public enum Tag { + AUTOTEST_FAILURE, + AUTOTEST_SEQUENCE_BEGIN, + AUTOTEST_SUITE_BEGIN, + AUTOTEST_TCPDUMP_BEGIN, + AUTOTEST_TCPDUMP_DATA, + AUTOTEST_TCPDUMP_END, + AUTOTEST_TEST_BEGIN, + AUTOTEST_TEST_FAILURE, + AUTOTEST_TEST_SUCCESS, BROWSER_BUG_REPORT, CARRIER_BUG_REPORT, CHECKIN_FAILURE, @@ -88,14 +100,15 @@ public final class Checkin { SETUP_RETRIES_EXHAUSTED, SETUP_SERVER_ERROR, SETUP_SERVER_TIMEOUT, - SYSTEM_APP_NOT_RESPONDING, + SETUP_NO_DATA_NETWORK, SYSTEM_BOOT, SYSTEM_LAST_KMSG, SYSTEM_RECOVERY_LOG, SYSTEM_RESTART, SYSTEM_SERVICE_LOOPING, SYSTEM_TOMBSTONE, - TEST, + TEST, + BATTERY_DISCHARGE_INFO, } } @@ -116,6 +129,9 @@ public final class Checkin { /** Valid tag values. Extend as necessary for your needs. */ public enum Tag { + BROWSER_SNAP_CENTER, + BROWSER_TEXT_SIZE_CHANGE, + BROWSER_ZOOM_OVERVIEW, CRASHES_REPORTED, CRASHES_TRUNCATED, ELAPSED_REALTIME_SEC, @@ -175,6 +191,9 @@ public final class Checkin { // The category is used for GTalk service messages public static final String CATEGORY = "android.server.checkin.CHECKIN"; + + // If true indicates that the checkin should only transfer market related data + public static final String EXTRA_MARKET_ONLY = "market_only"; } private static final String TAG = "Checkin"; @@ -195,8 +214,11 @@ public final class Checkin { values.put(Events.TAG, tag.toString()); if (value != null) values.put(Events.VALUE, value); return resolver.insert(Events.CONTENT_URI, values); + } catch (IllegalArgumentException e) { // thrown when provider is unavailable. + Log.w(TAG, "Can't log event " + tag + ": " + e); + return null; } catch (SQLException e) { - Log.e(TAG, "Can't log event: " + tag, e); // Database errors are not fatal. + Log.e(TAG, "Can't log event " + tag, e); // Database errors are not fatal. return null; } } @@ -218,8 +240,11 @@ public final class Checkin { if (count != 0) values.put(Stats.COUNT, count); if (sum != 0.0) values.put(Stats.SUM, sum); return resolver.insert(Stats.CONTENT_URI, values); + } catch (IllegalArgumentException e) { // thrown when provider is unavailable. + Log.w(TAG, "Can't update stat " + tag + ": " + e); + return null; } catch (SQLException e) { - Log.e(TAG, "Can't update stat: " + tag, e); // Database errors are not fatal. + Log.e(TAG, "Can't update stat " + tag, e); // Database errors are not fatal. return null; } } @@ -285,4 +310,3 @@ public final class Checkin { } } } - diff --git a/core/java/android/provider/Contacts.java b/core/java/android/provider/Contacts.java index e006d8cdac5fc5bd1af67a9488bbbe9921d93f0a..e132beeb0ead0bbca46944230adee5fd13d3ad59 100644 --- a/core/java/android/provider/Contacts.java +++ b/core/java/android/provider/Contacts.java @@ -182,7 +182,7 @@ public class Contacts { *

          Type: TEXT

          */ public static final String PHONETIC_NAME = "phonetic_name"; - + /** * The display name. If name is not null name, else if number is not null number, * else if email is not null email. @@ -190,6 +190,14 @@ public class Contacts { */ public static final String DISPLAY_NAME = "display_name"; + /** + * The field for sorting list phonetically. The content of this field + * may not be human readable but phonetically sortable. + *

          Type: TEXT

          + * @hide Used only in Contacts application for now. + */ + public static final String SORT_STRING = "sort_string"; + /** * Notes about the person. *

          Type: TEXT

          @@ -231,7 +239,7 @@ public class Contacts { * The server version of the photo *

          Type: TEXT (the version number portion of the photo URI)

          */ - public static final String PHOTO_VERSION = "photo_version"; + public static final String PHOTO_VERSION = "photo_version"; } /** @@ -932,27 +940,33 @@ public class Contacts { } /** - * This looks up the provider category defined in - * {@link android.provider.Im.ProviderCategories} from the predefined IM protocol id. + * This looks up the provider name defined in + * {@link android.provider.Im.ProviderNames} from the predefined IM protocol id. * This is used for interacting with the IM application. - * + * * @param protocol the protocol ID - * @return the provider category the IM app uses for the given protocol, or null if no + * @return the provider name the IM app uses for the given protocol, or null if no * provider is defined for the given protocol * @hide */ - public static String lookupProviderCategoryFromId(int protocol) { + public static String lookupProviderNameFromId(int protocol) { switch (protocol) { case PROTOCOL_GOOGLE_TALK: - return Im.ProviderCategories.GTALK; + return Im.ProviderNames.GTALK; case PROTOCOL_AIM: - return Im.ProviderCategories.AIM; + return Im.ProviderNames.AIM; case PROTOCOL_MSN: - return Im.ProviderCategories.MSN; + return Im.ProviderNames.MSN; case PROTOCOL_YAHOO: - return Im.ProviderCategories.YAHOO; + return Im.ProviderNames.YAHOO; case PROTOCOL_ICQ: - return Im.ProviderCategories.ICQ; + return Im.ProviderNames.ICQ; + case PROTOCOL_JABBER: + return Im.ProviderNames.JABBER; + case PROTOCOL_SKYPE: + return Im.ProviderNames.SKYPE; + case PROTOCOL_QQ: + return Im.ProviderNames.QQ; } return null; } @@ -1417,7 +1431,42 @@ public class Contacts { */ public static final String ATTACH_IMAGE = "com.android.contacts.action.ATTACH_IMAGE"; - + + /** + * Takes as input a data URI with a mailto: or tel: scheme. If a single + * contact exists with the given data it will be shown. If no contact + * exists, a dialog will ask the user if they want to create a new + * contact with the provided details filled in. If multiple contacts + * share the data the user will be prompted to pick which contact they + * want to view. + *

          + * For mailto: URIs, the scheme specific portion must be a + * raw email address, such as one built using + * {@link Uri#fromParts(String, String, String)}. + *

          + * For tel: URIs, the scheme specific portion is compared + * to existing numbers using the standard caller ID lookup algorithm. + * The number must be properly encoded, for example using + * {@link Uri#fromParts(String, String, String)}. + *

          + * Any extras from the {@link Insert} class will be passed along to the + * create activity if there are no contacts to show. + *

          + * Passing true for the {@link #EXTRA_FORCE_CREATE} extra will skip + * prompting the user when the contact doesn't exist. + */ + public static final String SHOW_OR_CREATE_CONTACT = + "com.android.contacts.action.SHOW_OR_CREATE_CONTACT"; + + /** + * Used with {@link #SHOW_OR_CREATE_CONTACT} to force creating a new contact if no matching + * contact found. Otherwise, default behavior is to prompt user with dialog before creating. + * + *

          Type: BOOLEAN

          + */ + public static final String EXTRA_FORCE_CREATE = + "com.android.contacts.action.FORCE_CREATE"; + /** * Intents related to the Contacts app UI. */ diff --git a/core/java/android/provider/Gmail.java b/core/java/android/provider/Gmail.java index 325f19db98a9924c41915bde961d3755b277d1f1..cc039686249dc9a34bd3b45da463cb4800dccfe8 100644 --- a/core/java/android/provider/Gmail.java +++ b/core/java/android/provider/Gmail.java @@ -370,6 +370,25 @@ public final class Gmail { "maxAttachmentSize"; } + /** + * These flags can be included as Selection Arguments when + * querying the provider. + */ + public static class SelectionArguments { + private SelectionArguments() { + // forbid instantiation + } + + /** + * Specifies that you do NOT wish the returned cursor to + * become the Active Network Cursor. If you do not include + * this flag as a selectionArg, the new cursor will become the + * Active Network Cursor by default. + */ + public static final String DO_NOT_BECOME_ACTIVE_NETWORK_CURSOR = + "SELECTION_ARGUMENT_DO_NOT_BECOME_ACTIVE_NETWORK_CURSOR"; + } + // These are the projections that we need when getting cursors from the // content provider. private static String[] CONVERSATION_PROJECTION = { @@ -435,6 +454,28 @@ public final class Gmail { } } + /** + * Behavior for a new cursor: should it become the Active Network + * Cursor? This could potentially lead to bad behavior if someone + * else is using the Active Network Cursor, since theirs will stop + * being the Active Network Cursor. + */ + public static enum BecomeActiveNetworkCursor { + /** + * The new cursor should become the one and only Active + * Network Cursor. Any other cursor that might already be the + * Active Network Cursor will cease to be so. + */ + YES, + + /** + * The new cursor should not become the Active Network + * Cursor. Any other cursor that might already be the Active + * Network Cursor will continue to be so. + */ + NO + } + /** * Wraps a Cursor in a ConversationCursor * @@ -449,6 +490,20 @@ public final class Gmail { return new ConversationCursor(this, account, cursor); } + /** + * Creates an array of SelectionArguments suitable for passing to the provider's query. + * Currently this only handles one flag, but it could be expanded in the future. + */ + private static String[] getSelectionArguments( + BecomeActiveNetworkCursor becomeActiveNetworkCursor) { + if (BecomeActiveNetworkCursor.NO == becomeActiveNetworkCursor) { + return new String[] {SelectionArguments.DO_NOT_BECOME_ACTIVE_NETWORK_CURSOR}; + } else { + // Default behavior; no args required. + return null; + } + } + /** * Asynchronously gets a cursor over all conversations matching a query. The * query is in Gmail's query syntax. When the operation is complete the handler's @@ -458,14 +513,17 @@ public final class Gmail { * @param handler An AsyncQueryHanlder that will be used to run the query * @param token The token to pass to startQuery, which will be passed back to onQueryComplete * @param query a query in Gmail's query syntax + * @param becomeActiveNetworkCursor whether or not the returned + * cursor should become the Active Network Cursor */ public void runQueryForConversations(String account, AsyncQueryHandler handler, int token, - String query) { + String query, BecomeActiveNetworkCursor becomeActiveNetworkCursor) { if (TextUtils.isEmpty(account)) { throw new IllegalArgumentException("account is empty"); } + String[] selectionArgs = getSelectionArguments(becomeActiveNetworkCursor); handler.startQuery(token, null, Uri.withAppendedPath(CONVERSATIONS_URI, account), - CONVERSATION_PROJECTION, query, null, null); + CONVERSATION_PROJECTION, query, selectionArgs, null); } /** @@ -474,11 +532,15 @@ public final class Gmail { * * @param account run the query on this account * @param query a query in Gmail's query syntax + * @param becomeActiveNetworkCursor whether or not the returned + * cursor should become the Active Network Cursor */ - public ConversationCursor getConversationCursorForQuery(String account, String query) { + public ConversationCursor getConversationCursorForQuery( + String account, String query, BecomeActiveNetworkCursor becomeActiveNetworkCursor) { + String[] selectionArgs = getSelectionArguments(becomeActiveNetworkCursor); Cursor cursor = mContentResolver.query( Uri.withAppendedPath(CONVERSATIONS_URI, account), CONVERSATION_PROJECTION, - query, null, null); + query, selectionArgs, null); return new ConversationCursor(this, account, cursor); } @@ -559,12 +621,10 @@ public final class Gmail { * server message id. * @param label the label to add or remove * @param add true to add the label, false to remove it - * @throws NonexistentLabelException thrown if the label does not exist */ public void addOrRemoveLabelOnConversation( String account, long conversationId, long maxServerMessageId, String label, - boolean add) - throws NonexistentLabelException { + boolean add) { if (TextUtils.isEmpty(account)) { throw new IllegalArgumentException("account is empty"); } @@ -599,7 +659,6 @@ public final class Gmail { * @param messageId the id of the message to whose labels should be changed * @param label the label to add or remove * @param add true to add the label, false to remove it - * @throws NonexistentLabelException thrown if the label does not exist */ public static void addOrRemoveLabelOnMessage(ContentResolver contentResolver, String account, long conversationId, long messageId, String label, boolean add) { @@ -1174,19 +1233,6 @@ public final class Gmail { void onCursorChanged(MailCursor cursor); } - /** - * Thrown when an operation is requested with a label that does not exist. - * - * TODO: this is here because I wanted a checked exception. However, I don't - * think that that is appropriate. In fact, I don't think that we should - * throw an exception at all because the label might have been valid when - * the caller presented it to the user but removed as a result of a sync. - * Maybe we should kill this and eat the errors. - */ - public static class NonexistentLabelException extends Exception { - // TODO: Add label name? - } - /** * A cursor over labels. */ @@ -1431,10 +1477,20 @@ public final class Gmail { LABEL_OUTBOX, LABEL_DRAFT, LABEL_ALL, LABEL_SPAM, LABEL_TRASH); + + private static final Set USER_MEANINGFUL_SYSTEM_LABELS_SET = + Sets.newHashSet( + SORTED_USER_MEANINGFUL_SYSTEM_LABELS.toArray( + new String[]{})); + public static List getSortedUserMeaningfulSystemLabels() { return SORTED_USER_MEANINGFUL_SYSTEM_LABELS; } + public static Set getUserMeaningfulSystemLabelsSet() { + return USER_MEANINGFUL_SYSTEM_LABELS_SET; + } + /** * If you are ever tempted to remove outbox or draft from this set make sure you have a * way to stop draft and outbox messages from getting purged before they are sent to the @@ -1484,7 +1540,15 @@ public final class Gmail { /** Returns the number of unread conversation with a given label. */ public int getNumUnreadConversations(long labelId) { - return getLabelIdValues(labelId).getAsInteger(LabelColumns.NUM_UNREAD_CONVERSATIONS); + Integer unreadConversations = + getLabelIdValues(labelId).getAsInteger(LabelColumns.NUM_UNREAD_CONVERSATIONS); + // There seems to be a race condition here that can get the label maps into a bad + // state and lose state on a particular label. + if (unreadConversations == null) { + return 0; + } else { + return unreadConversations; + } } /** @@ -2021,10 +2085,8 @@ public final class Gmail { * * @param label the label to add or remove * @param add whether to add or remove the label - * @throws NonexistentLabelException thrown if the named label does not - * exist */ - public void addOrRemoveLabel(String label, boolean add) throws NonexistentLabelException { + public void addOrRemoveLabel(String label, boolean add) { addOrRemoveLabelOnMessage(mContentResolver, mAccount, getConversationId(), getMessageId(), label, add); } diff --git a/core/java/android/provider/Im.java b/core/java/android/provider/Im.java index 68b2acdfaf53f09663072d8009063cd46017d2a0..19ad15874dcffd16a273ac1ca62e06e2db8e93f8 100644 --- a/core/java/android/provider/Im.java +++ b/core/java/android/provider/Im.java @@ -78,21 +78,10 @@ public class Im { String MSN = "MSN"; String ICQ = "ICQ"; String AIM = "AIM"; - } - - /** - * The ProviderCategories definitions are used for the Intent category for the Intent - * - * Intent intent = new Intent(Intent.ACTION_SENDTO, - * Uri.fromParts("im", data, null)). - * addCategory(category); - */ - public interface ProviderCategories { - String GTALK = "com.android.im.category.GTALK"; - String AIM = "com.android.im.category.AIM"; - String MSN = "com.android.im.category.MSN"; - String YAHOO = "com.android.im.category.YAHOO"; - String ICQ = "com.android.im.category.ICQ"; + String XMPP = "XMPP"; + String JABBER = "JABBER"; + String SKYPE = "SKYPE"; + String QQ = "QQ"; } /** @@ -140,54 +129,6 @@ public class Im { return retVal; } - /** - * This returns the provider name given a provider category. - * - * @param providerCategory the provider category defined in {@link ProviderCategories}. - * @return the corresponding provider name defined in {@link ProviderNames}. - */ - public static String getProviderNameForCategory(String providerCategory) { - if (providerCategory != null) { - if (providerCategory.equalsIgnoreCase(ProviderCategories.GTALK)) { - return ProviderNames.GTALK; - } else if (providerCategory.equalsIgnoreCase(ProviderCategories.AIM)) { - return ProviderNames.AIM; - } else if (providerCategory.equalsIgnoreCase(ProviderCategories.MSN)) { - return ProviderNames.MSN; - } else if (providerCategory.equalsIgnoreCase(ProviderCategories.YAHOO)) { - return ProviderNames.YAHOO; - } else if (providerCategory.equalsIgnoreCase(ProviderCategories.ICQ)) { - return ProviderNames.ICQ; - } - } - - return null; - } - - /** - * This returns the provider category given a provider name. - * - * @param providername the provider name defined in {@link ProviderNames}. - * @return the provider category defined in {@link ProviderCategories}. - */ - public static String getProviderCategoryFromName(String providername) { - if (providername != null) { - if (providername.equalsIgnoreCase(Im.ProviderNames.GTALK)) { - return Im.ProviderCategories.GTALK; - } else if (providername.equalsIgnoreCase(Im.ProviderNames.AIM)) { - return Im.ProviderCategories.AIM; - } else if (providername.equalsIgnoreCase(Im.ProviderNames.MSN)) { - return Im.ProviderCategories.MSN; - } else if (providername.equalsIgnoreCase(Im.ProviderNames.YAHOO)) { - return Im.ProviderCategories.YAHOO; - } else if (providername.equalsIgnoreCase(Im.ProviderNames.ICQ)) { - return Im.ProviderCategories.ICQ; - } - } - - return null; - } - private static final String[] PROVIDER_PROJECTION = new String[] { _ID, NAME @@ -796,6 +737,13 @@ public class Im { */ String ETAG = "etag"; + /** + * The OTR etag, computed by the server, stored on the client. There is one OTR etag + * per account roster. + *

          Type: TEXT

          + */ + String OTR_ETAG = "otr_etag"; + /** * The account id for the etag. *

          Type: INTEGER

          @@ -837,12 +785,38 @@ public class Im { return retVal; } + public static final String getOtrEtag(ContentResolver resolver, long accountId) { + String retVal = null; + + Cursor c = resolver.query(CONTENT_URI, + CONTACT_OTR_ETAG_PROJECTION, + ACCOUNT + "=" + accountId, + null /* selection args */, + null /* sort order */); + + try { + if (c.moveToFirst()) { + retVal = c.getString(COLUMN_OTR_ETAG); + } + } finally { + c.close(); + } + + return retVal; + } + private static final String[] CONTACT_ETAG_PROJECTION = new String[] { Im.ContactsEtag.ETAG // 0 }; private static int COLUMN_ETAG = 0; + private static final String[] CONTACT_OTR_ETAG_PROJECTION = new String[] { + Im.ContactsEtag.OTR_ETAG // 0 + }; + + private static int COLUMN_OTR_ETAG = 0; + /** * The content:// style URL for this table */ @@ -1271,9 +1245,9 @@ public class Im { } /** - * Columns shared between the IM and contacts presence tables + * Common presence columns shared between the IM and contacts presence tables */ - interface CommonPresenceColumns { + public interface CommonPresenceColumns { /** * The priority, an integer, used by XMPP presence *

          Type: INTEGER

          @@ -2070,4 +2044,37 @@ public class Im { */ public static final Uri CONTENT_URI = Uri.parse("content://im/lastRmqId"); } + + /** + * Columns for IM branding resource map cache table. This table caches the result of + * loading the branding resources to speed up IM landing page start. + */ + public interface BrandingResourceMapCacheColumns { + /** + * The provider ID + *

          Type: INTEGER

          + */ + String PROVIDER_ID = "provider_id"; + /** + * The application resource ID + *

          Type: INTEGER

          + */ + String APP_RES_ID = "app_res_id"; + /** + * The plugin resource ID + *

          Type: INTEGER

          + */ + String PLUGIN_RES_ID = "plugin_res_id"; + } + + /** + * The table for caching the result of loading IM branding resources. + */ + public static final class BrandingResourceMapCache + implements BaseColumns, BrandingResourceMapCacheColumns { + /** + * The content:// style URL for this table. + */ + public static final Uri CONTENT_URI = Uri.parse("content://im/brandingResMapCache"); + } } diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java index 87a02e6c2ae255f228fc84b82512d02da787f511..b91bc9d56f2af04a2ecbc1e6a7955dab2ab064e3 100644 --- a/core/java/android/provider/MediaStore.java +++ b/core/java/android/provider/MediaStore.java @@ -91,14 +91,14 @@ public final class MediaStore public static final String EXTRA_SCREEN_ORIENTATION = "android.intent.extra.screenOrientation"; /** - * The name of the Intent-extra used to control the orientation of a ViewImage. + * The name of an Intent-extra used to control the UI of a ViewImage. * This is a boolean property that overrides the activity's default fullscreen state. * @hide */ public static final String EXTRA_FULL_SCREEN = "android.intent.extra.fullScreen"; /** - * The name of the Intent-extra used to control the orientation of a ViewImage. + * The name of an Intent-extra used to control the UI of a ViewImage. * This is a boolean property that specifies whether or not to show action icons. * @hide */ @@ -117,25 +117,36 @@ public final class MediaStore */ public static final String INTENT_ACTION_STILL_IMAGE_CAMERA = "android.media.action.STILL_IMAGE_CAMERA"; - /** * The name of the Intent action used to launch a camera in video mode. */ public static final String INTENT_ACTION_VIDEO_CAMERA = "android.media.action.VIDEO_CAMERA"; /** - * Standard Intent action that can be sent to have the media application - * capture an image and return it. The image is returned as a Bitmap - * object in the extra field. - * @hide + * Standard Intent action that can be sent to have the camera application + * capture an image and return it. + *

          + * The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. + * If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap + * object in the extra field. This is useful for applications that only need a small image. + * If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri + * value of EXTRA_OUTPUT. + * @see #EXTRA_OUTPUT + * @see #EXTRA_VIDEO_QUALITY */ public final static String ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE"; /** - * Standard Intent action that can be sent to have the media application - * capture an video and return it. The caller may pass in an extra EXTRA_VIDEO_QUALITY - * control the video quality. - * @hide + * Standard Intent action that can be sent to have the camera application + * capture an video and return it. + *

          + * The caller may pass in an extra EXTRA_VIDEO_QUALITY to control the video quality. + *

          + * The caller may pass in an extra EXTRA_OUTPUT to control + * where the video is written. If EXTRA_OUTPUT is not present the video will be + * written to the standard location for videos, and the Uri of that location will be + * returned in the data field of the Uri. + * @see #EXTRA_OUTPUT */ public final static String ACTION_VIDEO_CAPTURE = "android.media.action.VIDEO_CAPTURE"; @@ -143,15 +154,19 @@ public final class MediaStore * The name of the Intent-extra used to control the quality of a recorded video. This is an * integer property. Currently value 0 means low quality, suitable for MMS messages, and * value 1 means high quality. In the future other quality levels may be added. - * @hide */ public final static String EXTRA_VIDEO_QUALITY = "android.intent.extra.videoQuality"; /** - * The name of the Intent-extra used to indicate a Uri to be used to - * store the requested image or video. + * Specify the maximum allowed size. * @hide */ + public final static String EXTRA_SIZE_LIMIT = "android.intent.extra.sizeLimit"; + + /** + * The name of the Intent-extra used to indicate a content resolver Uri to be used to + * store the requested image or video. + */ public final static String EXTRA_OUTPUT = "output"; /** @@ -471,7 +486,7 @@ public final class MediaStore /** * The default sort order for this table */ - public static final String DEFAULT_SORT_ORDER = "name ASC"; + public static final String DEFAULT_SORT_ORDER = ImageColumns.BUCKET_DISPLAY_NAME; } public static class Thumbnails implements BaseColumns @@ -581,6 +596,14 @@ public final class MediaStore */ public static final String DURATION = "duration"; + /** + * The position, in ms, playback was at when playback for this file + * was last stopped. + *

          Type: INTEGER (long)

          + * @hide + */ + public static final String BOOKMARK = "bookmark"; + /** * The id of the artist who created the audio file, if any *

          Type: INTEGER (long)

          @@ -653,6 +676,13 @@ public final class MediaStore */ public static final String IS_MUSIC = "is_music"; + /** + * Non-zero if the audio file is a podcast + *

          Type: INTEGER (boolean)

          + * @hide + */ + public static final String IS_PODCAST = "is_podcast"; + /** * Non-zero id the audio file may be a ringtone *

          Type: INTEGER (boolean)

          @@ -1198,22 +1228,15 @@ public final class MediaStore } public static final class Video { - /** - * deprecated Replaced by DEFAULT_SORT_ORDER2 - * This variable is a mistake that is retained for backwards compatibility. - * (There is no "name" column in the Video table.) - */ - public static final String DEFAULT_SORT_ORDER = "name ASC"; /** - * The default sort order for this table - * @hide + * The default sort order for this table. */ - public static final String DEFAULT_SORT_ORDER2 = MediaColumns.DISPLAY_NAME; + public static final String DEFAULT_SORT_ORDER = MediaColumns.DISPLAY_NAME; public static final Cursor query(ContentResolver cr, Uri uri, String[] projection) { - return cr.query(uri, projection, null, null, DEFAULT_SORT_ORDER2); + return cr.query(uri, projection, null, null, DEFAULT_SORT_ORDER); } public interface VideoColumns extends MediaColumns { @@ -1316,7 +1339,6 @@ public final class MediaStore * video should start playing at the next time it is opened. If the value is null or * out of the range 0..DURATION-1 then the video should start playing from the * beginning. - * @hide *

          Type: INTEGER

          */ public static final String BOOKMARK = "bookmark"; diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java index abbfd5bdb8e1b817298ad95e28a226b903d98209..b0ee479fcddbee46bb25fce548e7e93a392d89b7 100644 --- a/core/java/android/provider/Settings.java +++ b/core/java/android/provider/Settings.java @@ -234,6 +234,35 @@ public final class Settings { public static final String ACTION_LOCALE_SETTINGS = "android.settings.LOCALE_SETTINGS"; + /** + * Activity Action: Show settings to configure input methods, in particular + * allowing the user to enable input methods. + *

          + * In some cases, a matching Activity may not exist, so ensure you + * safeguard against this. + *

          + * Input: Nothing. + *

          + * Output: Nothing. + */ + @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) + public static final String ACTION_INPUT_METHOD_SETTINGS = + "android.settings.INPUT_METHOD_SETTINGS"; + + /** + * Activity Action: Show settings to manage the user input dictionary. + *

          + * In some cases, a matching Activity may not exist, so ensure you + * safeguard against this. + *

          + * Input: Nothing. + *

          + * Output: Nothing. + */ + @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) + public static final String ACTION_USER_DICTIONARY_SETTINGS = + "android.settings.USER_DICTIONARY_SETTINGS"; + /** * Activity Action: Show settings to allow configuration of application-related settings. *

          @@ -849,15 +878,6 @@ public final class Settings { */ public static final String AIRPLANE_MODE_RADIOS = "airplane_mode_radios"; - /** - * The interval in milliseconds after which Wi-Fi is considered idle. - * When idle, it is possible for the device to be switched from Wi-Fi to - * the mobile data network. - * - * @hide pending API Council approval - */ - public static final String WIFI_IDLE_MS = "wifi_idle_ms"; - /** * The policy for deciding when Wi-Fi should go to sleep (which will in * turn switch to using the mobile data as an Internet connection). @@ -1232,6 +1252,13 @@ public final class Settings { */ public static final String TRANSITION_ANIMATION_SCALE = "transition_animation_scale"; + /** + * Scaling factor for normal window animations. Setting to 0 will disable window + * animations. + * @hide + */ + public static final String FANCY_IME_ANIMATIONS = "fancy_ime_animations"; + /** * Control whether the accelerometer will be used to change screen * orientation. If 0, it will not be used unless explicitly requested @@ -1252,6 +1279,12 @@ public final class Settings { */ public static final String SOUND_EFFECTS_ENABLED = "sound_effects_enabled"; + /** + * Whether the haptic feedback (long presses, ...) are enabled. The value is + * boolean (1 or 0). + */ + public static final String HAPTIC_FEEDBACK_ENABLED = "haptic_feedback_enabled"; + // Settings moved to Settings.Secure /** @@ -2008,6 +2041,14 @@ public final class Settings { */ public static final String WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS = "wifi_mobile_data_transition_wakelock_timeout_ms"; + + /** + * Whether background data usage is allowed by the user. See + * ConnectivityManager for more info. + * + * @hide pending API council + */ + public static final String BACKGROUND_DATA = "background_data"; } /** @@ -2130,12 +2171,23 @@ public final class Settings { * Event tags from the kernel event log to upload during checkin. */ public static final String CHECKIN_EVENTS = "checkin_events"; + + /** + * Event tags for list of services to upload during checkin. + */ + public static final String CHECKIN_DUMPSYS_LIST = "checkin_dumpsys_list"; /** * The interval (in seconds) between periodic checkin attempts. */ public static final String CHECKIN_INTERVAL = "checkin_interval"; + /** + * Boolean indicating if the market app should force market only checkins on + * install/uninstall. Any non-0 value is considered true. + */ + public static final String MARKET_FORCE_CHECKIN = "market_force_checkin"; + /** * How frequently (in seconds) to check the memory status of the * device. @@ -2274,6 +2326,13 @@ public final class Settings { */ public static final String GMAIL_SEND_IMMEDIATELY = "gmail_send_immediately"; + /** + * Controls whether gmail buffers server responses. Possible values are "memory", for a + * memory-based buffer, or "file", for a temp-file-based buffer. All other values + * (including not set) disable buffering. + */ + public static final String GMAIL_BUFFER_SERVER_RESPONSE = "gmail_buffer_server_response"; + /** * Hostname of the GTalk server. */ @@ -2401,6 +2460,14 @@ public final class Settings { public static final String GTALK_SSL_HANDSHAKE_TIMEOUT_MS = "gtalk_ssl_handshake_timeout_ms"; + /** + * Enable use of ssl session caching. + * 'db' - save each session in a (per process) database + * 'file' - save each session in a (per process) file + * not set or any other value - normal java in-memory caching + */ + public static final String SSL_SESSION_CACHE = "ssl_session_cache"; + /** * How many bytes long a message has to be, in order to be gzipped. */ @@ -2496,28 +2563,28 @@ public final class Settings { */ public static final String SETTINGS_CONTRIBUTORS_PRETTY_URL = "settings_contributors_pretty_url"; - + /** * URL that points to the Terms Of Service for the device. *

          - * This should be a pretty http URL. + * This should be a pretty http URL. */ public static final String SETUP_GOOGLE_TOS_URL = "setup_google_tos_url"; - + /** * URL that points to the Android privacy policy for the device. *

          * This should be a pretty http URL. */ public static final String SETUP_ANDROID_PRIVACY_URL = "setup_android_privacy_url"; - + /** * URL that points to the Google privacy policy for the device. *

          - * This should be a pretty http URL. + * This should be a pretty http URL. */ public static final String SETUP_GOOGLE_PRIVACY_URL = "setup_google_privacy_url"; - + /** * Request an MSISDN token for various Google services. */ @@ -2682,6 +2749,13 @@ public final class Settings { public static final String GPRS_REGISTER_CHECK_PERIOD_MS = "gprs_register_check_period_ms"; + /** + * The interval in milliseconds after which Wi-Fi is considered idle. + * When idle, it is possible for the device to be switched from Wi-Fi to + * the mobile data network. + */ + public static final String WIFI_IDLE_MS = "wifi_idle_ms"; + /** * Screen timeout in milliseconds corresponding to the * PowerManager's POKE_LOCK_SHORT_TIMEOUT flag (i.e. the fastest @@ -2704,8 +2778,59 @@ public final class Settings { * Speech encoding used with voice search on WIFI networks. To be factored out of this class. */ public static final String VOICE_SEARCH_ENCODING_WIFI = "voice_search_encoding_wifi"; + + /** + * Whether to use automatic gain control in voice search (0 = disable, 1 = enable). + * To be factored out of this class. + */ + public static final String VOICE_SEARCH_ENABLE_AGC = "voice_search_enable_agc"; + + /** + * Whether to use noise suppression in voice search (0 = disable, 1 = enable). + * To be factored out of this class. + */ + public static final String VOICE_SEARCH_ENABLE_NS = "voice_search_enable_ns"; + + /** + * Whether to use the IIR filter in voice search (0 = disable, 1 = enable). + * To be factored out of this class. + */ + public static final String VOICE_SEARCH_ENABLE_IIR = "voice_search_enable_iir"; + + /** + * List of test suites (local disk filename) for the automatic instrumentation test runner. + * The file format is similar to automated_suites.xml, see AutoTesterService. + * If this setting is missing or empty, the automatic test runner will not start. + */ + public static final String AUTOTEST_SUITES_FILE = "autotest_suites_file"; + + /** + * Interval between synchronous checkins forced by the automatic test runner. + * If you set this to a value smaller than CHECKIN_INTERVAL, then the test runner's + * frequent checkins will prevent asynchronous background checkins from interfering + * with any performance measurements. + */ + public static final String AUTOTEST_CHECKIN_SECONDS = "autotest_checkin_seconds"; + + /** + * Interval between reboots forced by the automatic test runner. + */ + public static final String AUTOTEST_REBOOT_SECONDS = "autotest_reboot_seconds"; + + + /** + * Threshold values for the duration and level of a discharge cycle, under + * which we log discharge cycle info. + */ + public static final String BATTERY_DISCHARGE_DURATION_THRESHOLD = + "battery_discharge_duration_threshold"; + public static final String BATTERY_DISCHARGE_THRESHOLD = "battery_discharge_threshold"; - + /** + * An email address that anr bugreports should be sent to. + */ + public static final String ANR_BUGREPORT_RECIPIENT = "anr_bugreport_recipient"; + /** * @deprecated * @hide @@ -2772,7 +2897,7 @@ public final class Settings { * Arbitrary string (displayed to the user) that allows bookmarks to be * organized into categories. There are some special names for * standard folders, which all start with '@'. The label displayed for - * the folder changes with the locale (via {@link #labelForFolder}) but + * the folder changes with the locale (via {@link #getLabelForFolder}) but * the folder name does not change so you can consistently query for * the folder regardless of the current locale. * @@ -2912,9 +3037,10 @@ public final class Settings { * * @param context A context. * @param cursor A cursor pointing to the row whose title should be - * returned. The cursor must contain at least the - * {@link #TITLE} and {@link #INTENT} columns. - * @return A title that is localized and can be displayed to the user. + * returned. The cursor must contain at least the {@link #TITLE} + * and {@link #INTENT} columns. + * @return A title that is localized and can be displayed to the user, + * or the empty string if one could not be found. */ public static CharSequence getTitle(Context context, Cursor cursor) { int titleColumn = cursor.getColumnIndex(TITLE); @@ -2943,7 +3069,7 @@ public final class Settings { PackageManager packageManager = context.getPackageManager(); ResolveInfo info = packageManager.resolveActivity(intent, 0); - return info.loadLabel(packageManager); + return info != null ? info.loadLabel(packageManager) : ""; } } diff --git a/core/java/android/provider/Sync.java b/core/java/android/provider/Sync.java index 94bf80777d0f0899d86b0fac9e87d0074d1a386d..628852f4c37cf1fc93e3b89da509d994d59f57a1 100644 --- a/core/java/android/provider/Sync.java +++ b/core/java/android/provider/Sync.java @@ -273,6 +273,7 @@ public final class Sync { public static final int ERROR_CONFLICT = 5; public static final int ERROR_TOO_MANY_DELETIONS = 6; public static final int ERROR_TOO_MANY_RETRIES = 7; + public static final int ERROR_INTERNAL = 8; // The MESG column will contain one of these or one of the Error types. public static final String MESG_SUCCESS = "success"; @@ -292,6 +293,7 @@ public final class Sync { case ERROR_CONFLICT: return "conflict detected"; case ERROR_TOO_MANY_DELETIONS: return "too many deletions"; case ERROR_TOO_MANY_RETRIES: return "too many retries"; + case ERROR_INTERNAL: return "internal error"; default: return "unknown error"; } } @@ -491,11 +493,6 @@ public final class Sync { /** controls whether or not the device listens for sync tickles */ public static final String SETTING_LISTEN_FOR_TICKLES = "listen_for_tickles"; - /** controls whether or not the device connect to Google in background for various - * stuff, including GTalk, checkin, Market and data sync ... - */ - public static final String SETTING_BACKGROUND_DATA = "background_data"; - /** controls whether or not the individual provider is synced when tickles are received */ public static final String SETTING_SYNC_PROVIDER_PREFIX = "sync_provider_"; @@ -572,18 +569,6 @@ public final class Sync { putBoolean(contentResolver, SETTING_LISTEN_FOR_TICKLES, flag); } - /** - * A convenience method to set whether or not the device should connect to Google - * in background. - * - * @param contentResolver the ContentResolver to use to access the settings table - * @param flag true if it should connect. - */ - static public void setBackgroundData(ContentResolver contentResolver, - boolean flag) { - putBoolean(contentResolver, SETTING_BACKGROUND_DATA, flag); - } - public static class QueryMap extends ContentQueryMap { private ContentResolver mContentResolver; @@ -631,24 +616,6 @@ public final class Sync { return getBoolean(SETTING_LISTEN_FOR_TICKLES, true); } - /** - * Set whether or not the device should connect to Google in background - * - * @param flag true if it should - */ - public void setBackgroundData(boolean flag) { - Settings.setBackgroundData(mContentResolver, flag); - } - - /** - * Check if the device should connect to Google in background. - - * @return true if it should - */ - public boolean getBackgroundData() { - return getBoolean(SETTING_BACKGROUND_DATA, true); - } - /** * Convenience function for retrieving a single settings value * as a boolean. diff --git a/core/java/android/provider/Telephony.java b/core/java/android/provider/Telephony.java index 18c64ed182030f49af02163bb89976d8382a79d6..d802c14dfcab37043c000a91c1f112f020bd57e2 100644 --- a/core/java/android/provider/Telephony.java +++ b/core/java/android/provider/Telephony.java @@ -1023,6 +1023,11 @@ public final class Telephony { *

          Type: INTEGER

          */ public static final String ERROR = "error"; + /** + * Indicates whether this thread contains any attachments. + *

          Type: INTEGER

          + */ + public static final String HAS_ATTACHMENT = "has_attachment"; } /** diff --git a/core/java/android/provider/UserDictionary.java b/core/java/android/provider/UserDictionary.java index 58e5731f4cc76d24cfe6263fe45a18f77a27ddf6..5a7ef85315b4140fa2d69aea7fa11f77440888f4 100644 --- a/core/java/android/provider/UserDictionary.java +++ b/core/java/android/provider/UserDictionary.java @@ -25,10 +25,13 @@ import android.net.Uri; import android.text.TextUtils; /** - * - * @hide Pending API council approval + * A provider of user defined words for input methods to use for predictive text input. + * Applications and input methods may add words into the dictionary. Words can have associated + * frequency information and locale information. */ public class UserDictionary { + + /** Authority string for this provider. */ public static final String AUTHORITY = "user_dictionary"; /** @@ -39,7 +42,6 @@ public class UserDictionary { /** * Contains the user defined words. - * @hide Pending API council approval */ public static class Words implements BaseColumns { /** @@ -67,14 +69,14 @@ public class UserDictionary { public static final String WORD = "word"; /** - * The frequency column. A value between 1 and 255. + * The frequency column. A value between 1 and 255. Higher values imply higher frequency. *

          TYPE: INTEGER

          */ public static final String FREQUENCY = "frequency"; /** * The locale that this word belongs to. Null if it pertains to all - * locales. Locale is a 5 letter string such as
          en_US
          . + * locales. Locale is as defined by the string returned by Locale.toString(). *

          TYPE: TEXT

          */ public static final String LOCALE = "locale"; @@ -85,8 +87,10 @@ public class UserDictionary { */ public static final String APP_ID = "appid"; + /** The locale type to specify that the word is common to all locales. */ public static final int LOCALE_TYPE_ALL = 0; + /** The locale type to specify that the word is for the current locale. */ public static final int LOCALE_TYPE_CURRENT = 1; /** @@ -94,7 +98,14 @@ public class UserDictionary { */ public static final String DEFAULT_SORT_ORDER = FREQUENCY + " DESC"; - + /** Adds a word to the dictionary, with the given frequency and the specified + * specified locale type. + * @param context the current application context + * @param word the word to add to the dictionary. This should not be null or + * empty. + * @param localeType the locale type for this word. It should be one of + * {@link #LOCALE_TYPE_ALL} or {@link #LOCALE_TYPE_CURRENT}. + */ public static void addWord(Context context, String word, int frequency, int localeType) { final ContentResolver resolver = context.getContentResolver(); diff --git a/core/java/android/provider/package.html b/core/java/android/provider/package.html index a5535920f9cac474fed0594d36a899151dbc67d5..055b037b5d2626c81cd7baf135e341c0b7a09b86 100644 --- a/core/java/android/provider/package.html +++ b/core/java/android/provider/package.html @@ -6,6 +6,6 @@ Android. as contact informations, calendar information, and media files. These classes provide simplified methods of adding or retrieving data from these content providers. For information about how to use a content provider, see Reading and Writing Persistent Data. +href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers. diff --git a/core/java/android/server/BluetoothA2dpService.java b/core/java/android/server/BluetoothA2dpService.java index 8486e4b5acd1c4fae06da2951419c529c940e70c..3aa407858100c26b4526a599afc33634f00bcfd5 100644 --- a/core/java/android/server/BluetoothA2dpService.java +++ b/core/java/android/server/BluetoothA2dpService.java @@ -15,8 +15,7 @@ */ /** - * TODO: Move this to - * java/services/com/android/server/BluetoothA2dpService.java + * TODO: Move this to services.jar * and make the contructor package private again. * @hide */ @@ -35,15 +34,16 @@ import android.content.IntentFilter; import android.content.pm.PackageManager; import android.media.AudioManager; import android.os.Binder; +import android.os.Handler; +import android.os.Message; import android.provider.Settings; import android.util.Log; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; -import java.util.List; import java.util.HashMap; -import java.util.Iterator; +import java.util.List; public class BluetoothA2dpService extends IBluetoothA2dp.Stub { private static final String TAG = "BluetoothA2dpService"; @@ -55,6 +55,9 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH; private static final String A2DP_SINK_ADDRESS = "a2dp_sink_address"; + private static final String BLUETOOTH_ENABLED = "bluetooth_enabled"; + + private static final int MESSAGE_CONNECT_TO = 1; private final Context mContext; private final IntentFilter mIntentFilter; @@ -85,6 +88,7 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { mIntentFilter = new IntentFilter(BluetoothIntent.ENABLED_ACTION); mIntentFilter.addAction(BluetoothIntent.DISABLED_ACTION); mIntentFilter.addAction(BluetoothIntent.BOND_STATE_CHANGED_ACTION); + mIntentFilter.addAction(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION); mContext.registerReceiver(mReceiver, mIntentFilter); if (device.isEnabled()) { @@ -122,6 +126,37 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { setSinkPriority(address, BluetoothA2dp.PRIORITY_OFF); break; } + } else if (action.equals(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION)) { + if (getSinkPriority(address) > BluetoothA2dp.PRIORITY_OFF) { + // This device is a preferred sink. Make an A2DP connection + // after a delay. We delay to avoid connection collisions, + // and to give other profiles such as HFP a chance to + // connect first. + Message msg = Message.obtain(mHandler, MESSAGE_CONNECT_TO, address); + mHandler.sendMessageDelayed(msg, 6000); + } + } + } + }; + + private final Handler mHandler = new Handler() { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MESSAGE_CONNECT_TO: + String address = (String)msg.obj; + // check device is still preferred, and nothing is currently + // connected + if (getSinkPriority(address) > BluetoothA2dp.PRIORITY_OFF && + lookupSinksMatchingStates(new int[] { + BluetoothA2dp.STATE_CONNECTING, + BluetoothA2dp.STATE_CONNECTED, + BluetoothA2dp.STATE_PLAYING, + BluetoothA2dp.STATE_DISCONNECTING}).size() == 0) { + log("Auto-connecting A2DP to sink " + address); + connectSink(address); + } + break; } } }; @@ -136,10 +171,31 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { BluetoothA2dp.STATE_DISCONNECTED)); } } + mAudioManager.setParameter(BLUETOOTH_ENABLED, "true"); } private synchronized void onBluetoothDisable() { - mAudioDevices = null; + if (mAudioDevices != null) { + // copy to allow modification during iteration + String[] paths = new String[mAudioDevices.size()]; + paths = mAudioDevices.keySet().toArray(paths); + for (String path : paths) { + switch (mAudioDevices.get(path).state) { + case BluetoothA2dp.STATE_CONNECTING: + case BluetoothA2dp.STATE_CONNECTED: + case BluetoothA2dp.STATE_PLAYING: + disconnectSinkNative(path); + updateState(path, BluetoothA2dp.STATE_DISCONNECTED); + break; + case BluetoothA2dp.STATE_DISCONNECTING: + updateState(path, BluetoothA2dp.STATE_DISCONNECTED); + break; + } + } + mAudioDevices = null; + } + mAudioManager.setBluetoothA2dpOn(false); + mAudioManager.setParameter(BLUETOOTH_ENABLED, "false"); } public synchronized int connectSink(String address) { @@ -152,6 +208,15 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { if (mAudioDevices == null) { return BluetoothError.ERROR; } + // ignore if there are any active sinks + if (lookupSinksMatchingStates(new int[] { + BluetoothA2dp.STATE_CONNECTING, + BluetoothA2dp.STATE_CONNECTED, + BluetoothA2dp.STATE_PLAYING, + BluetoothA2dp.STATE_DISCONNECTING}).size() != 0) { + return BluetoothError.ERROR; + } + String path = lookupPath(address); if (path == null) { path = createHeadsetNative(address); @@ -215,17 +280,8 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { public synchronized List listConnectedSinks() { mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - List connectedSinks = new ArrayList(); - if (mAudioDevices == null) { - return connectedSinks; - } - for (SinkState sink : mAudioDevices.values()) { - if (sink.state == BluetoothA2dp.STATE_CONNECTED || - sink.state == BluetoothA2dp.STATE_PLAYING) { - connectedSinks.add(sink.address); - } - } - return connectedSinks; + return lookupSinksMatchingStates(new int[] {BluetoothA2dp.STATE_CONNECTED, + BluetoothA2dp.STATE_PLAYING}); } public synchronized int getSinkState(String address) { @@ -279,7 +335,11 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { // bluez 3.36 quietly disconnects the previous sink when a new sink // is connected, so we need to mark all previously connected sinks as // disconnected - for (String oldPath : mAudioDevices.keySet()) { + + // copy to allow modification during iteration + String[] paths = new String[mAudioDevices.size()]; + paths = mAudioDevices.keySet().toArray(paths); + for (String oldPath : paths) { if (path.equals(oldPath)) { continue; } @@ -289,6 +349,7 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { } } + updateState(path, BluetoothA2dp.STATE_CONNECTING); mAudioManager.setParameter(A2DP_SINK_ADDRESS, lookupAddress(path)); mAudioManager.setBluetoothA2dpOn(true); updateState(path, BluetoothA2dp.STATE_CONNECTED); @@ -309,6 +370,11 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { private synchronized final String lookupAddress(String path) { if (mAudioDevices == null) return null; + SinkState sink = mAudioDevices.get(path); + if (sink == null) { + Log.w(TAG, "lookupAddress() called for unknown device " + path); + updateState(path, BluetoothA2dp.STATE_DISCONNECTED); + } String address = mAudioDevices.get(path).address; if (address == null) Log.e(TAG, "Can't find address for " + path); return address; @@ -325,6 +391,22 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { return null; } + private synchronized List lookupSinksMatchingStates(int[] states) { + List sinks = new ArrayList(); + if (mAudioDevices == null) { + return sinks; + } + for (SinkState sink : mAudioDevices.values()) { + for (int state : states) { + if (sink.state == state) { + sinks.add(sink.address); + break; + } + } + } + return sinks; + } + private synchronized void updateState(String path, int state) { if (mAudioDevices == null) return; @@ -349,6 +431,15 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { intent.putExtra(BluetoothA2dp.SINK_PREVIOUS_STATE, prevState); intent.putExtra(BluetoothA2dp.SINK_STATE, state); mContext.sendBroadcast(intent, BLUETOOTH_PERM); + + if ((prevState == BluetoothA2dp.STATE_CONNECTED || + prevState == BluetoothA2dp.STATE_PLAYING) && + (state != BluetoothA2dp.STATE_CONNECTED && + state != BluetoothA2dp.STATE_PLAYING)) { + // disconnected + intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY); + mContext.sendBroadcast(intent); + } } } diff --git a/core/java/android/server/BluetoothDeviceService.java b/core/java/android/server/BluetoothDeviceService.java index 3ce34c30a198b1ec1944d20c7c92cb93cbf3c2cc..9e9ba6237613ab4090108399e54cc7da3589d3d5 100644 --- a/core/java/android/server/BluetoothDeviceService.java +++ b/core/java/android/server/BluetoothDeviceService.java @@ -25,8 +25,8 @@ package android.server; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothHeadset; // just for dump() import android.bluetooth.BluetoothError; +import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothIntent; import android.bluetooth.IBluetoothDevice; import android.bluetooth.IBluetoothDeviceCallback; @@ -35,22 +35,19 @@ import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; -import android.content.pm.PackageManager; -import android.os.RemoteException; -import android.provider.Settings; -import android.util.Log; import android.os.Binder; import android.os.Handler; import android.os.Message; +import android.os.RemoteException; import android.os.SystemService; +import android.provider.Settings; +import android.util.Log; -import java.io.IOException; import java.io.FileDescriptor; -import java.io.FileNotFoundException; -import java.io.FileWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -84,15 +81,16 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { */ public synchronized void init() { initializeNativeDataNative(); - mIsEnabled = (isEnabledNative() == 1); - if (mIsEnabled) { - mBondState.loadBondState(); + + if (isEnabledNative() == 1) { + Log.w(TAG, "Bluetooth daemons already running - runtime restart? "); + disableNative(); } + + mIsEnabled = false; mIsDiscovering = false; mEventLoop = new BluetoothEventLoop(mContext, this); registerForAirplaneMode(); - - disableEsco(); // TODO: enable eSCO support once its fully supported } private native void initializeNativeDataNative(); @@ -116,12 +114,22 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { private native int isEnabledNative(); /** - * Disable bluetooth. Returns true on success. + * Bring down bluetooth and disable BT in settings. Returns true on success. */ - public synchronized boolean disable() { + public boolean disable() { + return disable(true); + } + + /** + * Bring down bluetooth. Returns true on success. + * + * @param saveSetting If true, disable BT in settings + * + */ + public synchronized boolean disable(boolean saveSetting) { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); - + if (mEnableThread != null && mEnableThread.isAlive()) { return false; } @@ -130,22 +138,63 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } mEventLoop.stop(); disableNative(); + + // mark in progress bondings as cancelled + for (String address : mBondState.listInState(BluetoothDevice.BOND_BONDING)) { + mBondState.setBondState(address, BluetoothDevice.BOND_NOT_BONDED, + BluetoothDevice.UNBOND_REASON_AUTH_CANCELED); + } + + // Remove remoteServiceChannelCallbacks + HashMap callbacksMap = + mEventLoop.getRemoteServiceChannelCallbacks(); + IBluetoothDeviceCallback callback; + + for (String address : callbacksMap.keySet()) { + callback = callbacksMap.get(address); + try { + callback.onGetRemoteServiceChannelResult(address, BluetoothError.ERROR_DISABLED); + } catch (RemoteException e) {} + callbacksMap.remove(address); + } + + // update mode + Intent intent = new Intent(BluetoothIntent.SCAN_MODE_CHANGED_ACTION); + intent.putExtra(BluetoothIntent.SCAN_MODE, BluetoothDevice.SCAN_MODE_NONE); + mContext.sendBroadcast(intent, BLUETOOTH_PERM); + mIsEnabled = false; - Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.BLUETOOTH_ON, 0); + if (saveSetting) { + persistBluetoothOnSetting(false); + } mIsDiscovering = false; - Intent intent = new Intent(BluetoothIntent.DISABLED_ACTION); + intent = new Intent(BluetoothIntent.DISABLED_ACTION); mContext.sendBroadcast(intent, BLUETOOTH_PERM); return true; } + /** + * Bring up bluetooth, asynchronously, and enable BT in settings. + * This turns on/off the underlying hardware. + * + * @return True on success (so far), guaranteeing the callback with be + * notified when complete. + */ + public boolean enable(IBluetoothDeviceCallback callback) { + return enable(callback, true); + } + /** * Enable this Bluetooth device, asynchronously. * This turns on/off the underlying hardware. * - * @return True on success (so far), guarenteeing the callback with be + * @param saveSetting If true, enable BT in settings + * + * @return True on success (so far), guaranteeing the callback with be * notified when complete. */ - public synchronized boolean enable(IBluetoothDeviceCallback callback) { + public synchronized boolean enable(IBluetoothDeviceCallback callback, + boolean saveSetting) { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); @@ -159,7 +208,7 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { if (mEnableThread != null && mEnableThread.isAlive()) { return false; } - mEnableThread = new EnableThread(callback); + mEnableThread = new EnableThread(callback, saveSetting); mEnableThread.start(); return true; } @@ -183,13 +232,36 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { private class EnableThread extends Thread { private final IBluetoothDeviceCallback mEnableCallback; - public EnableThread(IBluetoothDeviceCallback callback) { + private final boolean mSaveSetting; + public EnableThread(IBluetoothDeviceCallback callback, boolean saveSetting) { mEnableCallback = callback; + mSaveSetting = saveSetting; } public void run() { boolean res = (enableNative() == 0); if (res) { - mEventLoop.start(); + int retryCount = 2; + boolean running = false; + while ((retryCount-- > 0) && !running) { + mEventLoop.start(); + // it may take a momement for the other thread to do its + // thing. Check periodically for a while. + int pollCount = 5; + while ((pollCount-- > 0) && !running) { + if (mEventLoop.isEventLoopRunning()) { + running = true; + break; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) {} + } + } + if (!running) { + log("bt EnableThread giving up"); + res = false; + disableNative(); + } } if (mEnableCallback != null) { @@ -202,17 +274,35 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { if (res) { mIsEnabled = true; - Settings.Secure.putInt(mContext.getContentResolver(), - Settings.Secure.BLUETOOTH_ON, 1); + if (mSaveSetting) { + persistBluetoothOnSetting(true); + } mIsDiscovering = false; - Intent intent = new Intent(BluetoothIntent.ENABLED_ACTION); mBondState.loadBondState(); - mContext.sendBroadcast(intent, BLUETOOTH_PERM); mHandler.sendMessageDelayed(mHandler.obtainMessage(REGISTER_SDP_RECORDS), 3000); + + // Update mode + mEventLoop.onModeChanged(getModeNative()); + } + Intent intent = null; + if (res) { + intent = new Intent(BluetoothIntent.ENABLED_ACTION); + } else { + intent = new Intent(BluetoothIntent.DISABLED_ACTION); } + intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); + mContext.sendBroadcast(intent, BLUETOOTH_PERM); + mEnableThread = null; } - }; + } + + private void persistBluetoothOnSetting(boolean bluetoothOn) { + long origCallerIdentityToken = Binder.clearCallingIdentity(); + Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.BLUETOOTH_ON, + bluetoothOn ? 1 : 0); + Binder.restoreCallingIdentity(origCallerIdentityToken); + } private native int enableNative(); private native int disableNative(); @@ -229,6 +319,16 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { public class BondState { private final HashMap mState = new HashMap(); private final HashMap mPinAttempt = new HashMap(); + private final ArrayList mAutoPairingFailures = new ArrayList(); + // List of all the vendor_id prefix of Bluetooth addresses for which + // auto pairing is not attempted + private final ArrayList mAutoPairingBlacklisted = + new ArrayList(Arrays.asList( + "00:02:C7", "00:16:FE", "00:19:C1", "00:1B:FB", "00:1E:3D", //ALPS + "00:21:4F", "00:23:06", "00:24:33", "00:A0:79", // ALPS + "00:0E:6D", "00:13:E0", "00:21:E8", "00:60:57",// Murata for Prius 2007 + "00:0E:9F" // TEMIC SDS for Porsche + )); public synchronized void loadBondState() { if (!mIsEnabled) { @@ -263,8 +363,8 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { intent.putExtra(BluetoothIntent.BOND_PREVIOUS_STATE, oldState); if (state == BluetoothDevice.BOND_NOT_BONDED) { if (reason <= 0) { - Log.w(TAG, "setBondState() called to unbond device with invalid reason code " + - "Setting reason = BOND_RESULT_REMOVED"); + Log.w(TAG, "setBondState() called to unbond device, but reason code is " + + "invalid. Overriding reason code with BOND_RESULT_REMOVED"); reason = BluetoothDevice.UNBOND_REASON_REMOVED; } intent.putExtra(BluetoothIntent.REASON, reason); @@ -272,14 +372,17 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } else { mState.put(address, state); } - if (state == BluetoothDevice.BOND_BONDING) { - mPinAttempt.put(address, Integer.valueOf(0)); - } else { - mPinAttempt.remove(address); - } + mContext.sendBroadcast(intent, BLUETOOTH_PERM); } + public boolean isAutoPairingBlacklisted(String address) { + for (String blacklistAddress : mAutoPairingBlacklisted) { + if (address.startsWith(blacklistAddress)) return true; + } + return false; + } + public synchronized int getBondState(String address) { Integer state = mState.get(address); if (state == null) { @@ -288,16 +391,34 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { return state.intValue(); } - public synchronized String[] listBonds() { + private synchronized String[] listInState(int state) { ArrayList result = new ArrayList(mState.size()); for (Map.Entry e : mState.entrySet()) { - if (e.getValue().intValue() == BluetoothDevice.BOND_BONDED) { + if (e.getValue().intValue() == state) { result.add(e.getKey()); } } return result.toArray(new String[result.size()]); } + public synchronized void addAutoPairingFailure(String address) { + if (!mAutoPairingFailures.contains(address)) { + mAutoPairingFailures.add(address); + } + } + + public synchronized boolean isAutoPairingAttemptsInProgress(String address) { + return getAttempt(address) != 0; + } + + public synchronized void clearPinAttempts(String address) { + mPinAttempt.remove(address); + } + + public synchronized boolean hasAutoPairingFailed(String address) { + return mAutoPairingFailures.contains(address); + } + public synchronized int getAttempt(String address) { Integer attempt = mPinAttempt.get(address); if (attempt == null) { @@ -308,10 +429,13 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { public synchronized void attempt(String address) { Integer attempt = mPinAttempt.get(address); + int newAttempt; if (attempt == null) { - return; + newAttempt = 1; + } else { + newAttempt = attempt.intValue() + 1; } - mPinAttempt.put(address, new Integer(attempt.intValue() + 1)); + mPinAttempt.put(address, new Integer(newAttempt)); } } @@ -353,18 +477,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } private native boolean setNameNative(String name); - public synchronized String getMajorClass() { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return getMajorClassNative(); - } - private native String getMajorClassNative(); - - public synchronized String getMinorClass() { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return getMinorClassNative(); - } - private native String getMinorClassNative(); - /** * Returns the user-friendly name of a remote device. This value is * retrned from our local cache, which is updated during device discovery. @@ -386,24 +498,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { /* pacakge */ native String getAdapterPathNative(); - /** - * Initiate a remote-device-discovery procedure. This procedure may be - * canceled by calling {@link #stopDiscovery}. Remote-device discoveries - * are returned as intents - *

          - * Typically, when a remote device is found, your - * android.bluetooth.DiscoveryEventNotifier#notifyRemoteDeviceFound - * method will be invoked, and subsequently, your - * android.bluetooth.RemoteDeviceEventNotifier#notifyRemoteNameUpdated - * will tell you the user-friendly name of the remote device. However, - * it is possible that the name update may fail for various reasons, so you - * should display the device's Bluetooth address as soon as you get a - * notifyRemoteDeviceFound event, and update the name when you get the - * remote name. - * - * @return true if discovery has started, - * false otherwise. - */ public synchronized boolean startDiscovery(boolean resolveNames) { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); @@ -411,12 +505,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } private native boolean startDiscoveryNative(boolean resolveNames); - /** - * Cancel a remote-device discovery. - * - * Note: you may safely call this method even when discovery has not been - * started. - */ public synchronized boolean cancelDiscovery() { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); @@ -492,171 +580,23 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } private native boolean isConnectedNative(String address); - /** - * Detetermines whether this device is connectable (that is, whether remote - * devices can connect to it.) - *

          - * Note: A Bluetooth adapter has separate connectable and discoverable - * states, and you could have any combination of those. Although - * any combination is possible (such as discoverable but not - * connectable), we restrict the possible combinations to one of - * three possibilities: discoverable and connectable, connectable - * but not discoverable, and neither connectable nor discoverable. - * - * @return true if this adapter is connectable - * false otherwise - * - * @see #isDiscoverable - * @see #getMode - * @see #setMode - */ - public synchronized boolean isConnectable() { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return isConnectableNative(); - } - private native boolean isConnectableNative(); - - /** - * Detetermines whether this device is discoverable. - * - * Note: a Bluetooth adapter has separate connectable and discoverable - * states, and you could have any combination of those. Although - * any combination is possible (such as discoverable but not - * connectable), we restrict the possible combinations to one of - * three possibilities: discoverable and connectable, connectable - * but not discoverable, and neither connectable nor discoverable. - * - * @return true if this adapter is discoverable - * false otherwise - * - * @see #isConnectable - * @see #getMode - * @see #setMode - */ - public synchronized boolean isDiscoverable() { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return isDiscoverableNative(); - } - private native boolean isDiscoverableNative(); - - /** - * Determines which one of three modes this adapter is in: discoverable and - * connectable, not discoverable but connectable, or neither. - * - * @return Mode enumeration containing the current mode. - * - * @see #setMode - */ - public synchronized int getMode() { + public synchronized int getScanMode() { mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - String mode = getModeNative(); - if (mode == null) { - return BluetoothDevice.MODE_UNKNOWN; - } - if (mode.equalsIgnoreCase("off")) { - return BluetoothDevice.MODE_OFF; - } - else if (mode.equalsIgnoreCase("connectable")) { - return BluetoothDevice.MODE_CONNECTABLE; - } - else if (mode.equalsIgnoreCase("discoverable")) { - return BluetoothDevice.MODE_DISCOVERABLE; - } - else { - return BluetoothDevice.MODE_UNKNOWN; - } + return bluezStringToScanMode(getModeNative()); } private native String getModeNative(); - /** - * Set the discoverability and connectability mode of this adapter. The - * possibilities are discoverable and connectable (MODE_DISCOVERABLE), - * connectable but not discoverable (MODE_CONNECTABLE), and neither - * (MODE_OFF). - * - * Note: MODE_OFF does not mean that the adapter is physically off. It - * may be neither discoverable nor connectable, but it could still - * initiate outgoing connections, or could participate in a - * connection initiated by a remote device before its mode was set - * to MODE_OFF. - * - * @param mode the new mode - * @see #getMode - */ - public synchronized boolean setMode(int mode) { + public synchronized boolean setScanMode(int mode) { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); - switch (mode) { - case BluetoothDevice.MODE_OFF: - return setModeNative("off"); - case BluetoothDevice.MODE_CONNECTABLE: - return setModeNative("connectable"); - case BluetoothDevice.MODE_DISCOVERABLE: - return setModeNative("discoverable"); + String bluezMode = scanModeToBluezString(mode); + if (bluezMode != null) { + return setModeNative(bluezMode); } return false; } private native boolean setModeNative(String mode); - /** - * Retrieves the alias of a remote device. The alias is a local feature, - * and allows us to associate a name with a remote device that is different - * from that remote device's user-friendly name. The remote device knows - * nothing about this. The alias can be changed with - * {@link #setRemoteAlias}, and it may be removed with - * {@link #clearRemoteAlias} - * - * @param address Bluetooth address of remote device. - * - * @return The alias of the remote device. - */ - public synchronized String getRemoteAlias(String address) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - if (!BluetoothDevice.checkBluetoothAddress(address)) { - return null; - } - return getRemoteAliasNative(address); - } - private native String getRemoteAliasNative(String address); - - /** - * Changes the alias of a remote device. The alias is a local feature, - * from that remote device's user-friendly name. The remote device knows - * nothing about this. The alias can be retrieved with - * {@link #getRemoteAlias}, and it may be removed with - * {@link #clearRemoteAlias}. - * - * @param address Bluetooth address of remote device - * @param alias Alias for the remote device - */ - public synchronized boolean setRemoteAlias(String address, String alias) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, - "Need BLUETOOTH_ADMIN permission"); - if (alias == null || !BluetoothDevice.checkBluetoothAddress(address)) { - return false; - } - return setRemoteAliasNative(address, alias); - } - private native boolean setRemoteAliasNative(String address, String alias); - - /** - * Removes the alias of a remote device. The alias is a local feature, - * from that remote device's user-friendly name. The remote device knows - * nothing about this. The alias can be retrieved with - * {@link #getRemoteAlias}. - * - * @param address Bluetooth address of remote device - */ - public synchronized boolean clearRemoteAlias(String address) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, - "Need BLUETOOTH_ADMIN permission"); - if (!BluetoothDevice.checkBluetoothAddress(address)) { - return false; - } - return clearRemoteAliasNative(address); - } - private native boolean clearRemoteAliasNative(String address); - public synchronized boolean disconnectRemoteDeviceAcl(String address) { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); @@ -674,7 +614,19 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { return false; } address = address.toUpperCase(); - if (mBondState.getBondState(address) != BluetoothDevice.BOND_NOT_BONDED) { + + String[] bonding = mBondState.listInState(BluetoothDevice.BOND_BONDING); + if (bonding.length > 0 && !bonding[0].equals(address)) { + log("Ignoring createBond(): another device is bonding"); + // a different device is currently bonding, fail + return false; + } + + // Check for bond state only if we are not performing auto + // pairing exponential back-off attempts. + if (!mBondState.isAutoPairingAttemptsInProgress(address) && + mBondState.getBondState(address) != BluetoothDevice.BOND_NOT_BONDED) { + log("Ignoring createBond(): this device is already bonding or bonded"); return false; } @@ -699,7 +651,7 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } mBondState.setBondState(address, BluetoothDevice.BOND_NOT_BONDED, - BluetoothDevice.UNBOND_REASON_CANCELLED); + BluetoothDevice.UNBOND_REASON_AUTH_CANCELED); cancelBondingProcessNative(address); return true; } @@ -717,7 +669,7 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { public synchronized String[] listBonds() { mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return mBondState.listBonds(); + return mBondState.listInState(BluetoothDevice.BOND_BONDED); } public synchronized int getBondState(String address) { @@ -918,69 +870,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } private native String lastUsedNative(String address); - /** - * Gets the major device class of the specified device. - * Example: "computer" - * - * Note: This is simply a string desciption of the major class of the - * device-class information, which is returned as a 32-bit value - * during device discovery. - * - * @param address The Bluetooth address of the remote device. - * - * @return remote-device major class - * - * @see #getRemoteClass - */ - public synchronized String getRemoteMajorClass(String address) { - if (!BluetoothDevice.checkBluetoothAddress(address)) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return null; - } - return getRemoteMajorClassNative(address); - } - private native String getRemoteMajorClassNative(String address); - - /** - * Gets the minor device class of the specified device. - * Example: "laptop" - * - * Note: This is simply a string desciption of the minor class of the - * device-class information, which is returned as a 32-bit value - * during device discovery. - * - * @param address The Bluetooth address of the remote device. - * - * @return remote-device minor class - * - * @see #getRemoteClass - */ - public synchronized String getRemoteMinorClass(String address) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - if (!BluetoothDevice.checkBluetoothAddress(address)) { - return null; - } - return getRemoteMinorClassNative(address); - } - private native String getRemoteMinorClassNative(String address); - - /** - * Gets the service classes of the specified device. - * Example: ["networking", "object transfer"] - * - * @return a String array with the descriptions of the service classes. - * - * @see #getRemoteClass - */ - public synchronized String[] getRemoteServiceClasses(String address) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - if (!BluetoothDevice.checkBluetoothAddress(address)) { - return null; - } - return getRemoteServiceClassesNative(address); - } - private native String[] getRemoteServiceClassesNative(String address); - /** * Gets the remote major, minor, and service classes encoded as a 32-bit * integer. @@ -1162,9 +1051,9 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { // If bluetooth is currently expected to be on, then enable or disable bluetooth if (Settings.Secure.getInt(resolver, Settings.Secure.BLUETOOTH_ON, 0) > 0) { if (enabled) { - enable(null); + enable(null, false); } else { - disable(); + disable(false); } } } @@ -1188,16 +1077,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { Settings.System.AIRPLANE_MODE_ON, 0) == 1; } - private static final String DISABLE_ESCO_PATH = "/sys/module/sco/parameters/disable_esco"; - private static void disableEsco() { - try { - FileWriter file = new FileWriter(DISABLE_ESCO_PATH); - file.write("Y"); - file.close(); - } catch (FileNotFoundException e) { - } catch (IOException e) {} - } - @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { if (mIsEnabled) { @@ -1248,6 +1127,34 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { pw.println("\nmIsAirplaneSensitive = " + mIsAirplaneSensitive); } + /* package */ static int bluezStringToScanMode(String mode) { + if (mode == null) { + return BluetoothError.ERROR; + } + mode = mode.toLowerCase(); + if (mode.equals("off")) { + return BluetoothDevice.SCAN_MODE_NONE; + } else if (mode.equals("connectable")) { + return BluetoothDevice.SCAN_MODE_CONNECTABLE; + } else if (mode.equals("discoverable")) { + return BluetoothDevice.SCAN_MODE_CONNECTABLE_DISCOVERABLE; + } else { + return BluetoothError.ERROR; + } + } + + /* package */ static String scanModeToBluezString(int mode) { + switch (mode) { + case BluetoothDevice.SCAN_MODE_NONE: + return "off"; + case BluetoothDevice.SCAN_MODE_CONNECTABLE: + return "connectable"; + case BluetoothDevice.SCAN_MODE_CONNECTABLE_DISCOVERABLE: + return "discoverable"; + } + return null; + } + private static void log(String msg) { Log.d(TAG, msg); } diff --git a/core/java/android/server/BluetoothEventLoop.java b/core/java/android/server/BluetoothEventLoop.java index 4f63f9835033e83f07349f56aa9746862ecc75e5..8e77eed9c067c4f22b6673d734a2bb048210f5a7 100644 --- a/core/java/android/server/BluetoothEventLoop.java +++ b/core/java/android/server/BluetoothEventLoop.java @@ -16,6 +16,7 @@ package android.server; +import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothError; @@ -23,6 +24,8 @@ import android.bluetooth.BluetoothIntent; import android.bluetooth.IBluetoothDeviceCallback; import android.content.Context; import android.content.Intent; +import android.os.Handler; +import android.os.Message; import android.os.RemoteException; import android.util.Log; @@ -41,15 +44,45 @@ class BluetoothEventLoop { private int mNativeData; private Thread mThread; + private boolean mStarted; private boolean mInterrupted; private HashMap mPasskeyAgentRequestData; private HashMap mGetRemoteServiceChannelCallbacks; private BluetoothDeviceService mBluetoothService; private Context mContext; + private static final int EVENT_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY = 1; + private static final int EVENT_RESTART_BLUETOOTH = 2; + + // The time (in millisecs) to delay the pairing attempt after the first + // auto pairing attempt fails. We use an exponential delay with + // INIT_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY as the initial value and + // MAX_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY as the max value. + private static final long INIT_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY = 3000; + private static final long MAX_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY = 12000; + private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN; private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH; + private final Handler mHandler = new Handler() { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case EVENT_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY: + String address = (String)msg.obj; + if (address != null) { + mBluetoothService.createBond(address); + return; + } + break; + case EVENT_RESTART_BLUETOOTH: + mBluetoothService.disable(); + mBluetoothService.enable(null); + break; + } + } + }; + static { classInitNative(); } private static native void classInitNative(); @@ -95,14 +128,18 @@ class BluetoothEventLoop { public void run() { try { if (setUpEventLoopNative()) { + mStarted = true; while (!mInterrupted) { waitForAndDispatchEvent(0); sleep(500); } - tearDownEventLoopNative(); } + // tear down even in the error case to clean + // up anything we started to setup + tearDownEventLoopNative(); } catch (InterruptedException e) { } if (DBG) log("Event Loop thread finished"); + mThread = null; } }; if (DBG) log("Starting Event Loop thread"); @@ -114,9 +151,7 @@ class BluetoothEventLoop { public synchronized void stop() { if (mThread != null) { - mInterrupted = true; - try { mThread.join(); mThread = null; @@ -127,135 +162,150 @@ class BluetoothEventLoop { } public synchronized boolean isEventLoopRunning() { - return mThread != null; + return mThread != null && mStarted; } - public void onModeChanged(String mode) { - Intent intent = new Intent(BluetoothIntent.MODE_CHANGED_ACTION); - int intMode = BluetoothDevice.MODE_UNKNOWN; - if (mode.equalsIgnoreCase("off")) { - intMode = BluetoothDevice.MODE_OFF; + /*package*/ void onModeChanged(String bluezMode) { + int mode = BluetoothDeviceService.bluezStringToScanMode(bluezMode); + if (mode >= 0) { + Intent intent = new Intent(BluetoothIntent.SCAN_MODE_CHANGED_ACTION); + intent.putExtra(BluetoothIntent.SCAN_MODE, mode); + mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - else if (mode.equalsIgnoreCase("connectable")) { - intMode = BluetoothDevice.MODE_CONNECTABLE; - } - else if (mode.equalsIgnoreCase("discoverable")) { - intMode = BluetoothDevice.MODE_DISCOVERABLE; - } - intent.putExtra(BluetoothIntent.MODE, intMode); - mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onDiscoveryStarted() { + private void onDiscoveryStarted() { mBluetoothService.setIsDiscovering(true); Intent intent = new Intent(BluetoothIntent.DISCOVERY_STARTED_ACTION); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onDiscoveryCompleted() { + private void onDiscoveryCompleted() { mBluetoothService.setIsDiscovering(false); Intent intent = new Intent(BluetoothIntent.DISCOVERY_COMPLETED_ACTION); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onPairingRequest() { - Intent intent = new Intent(BluetoothIntent.PAIRING_REQUEST_ACTION); - mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM); - } - - public void onPairingCancel() { - Intent intent = new Intent(BluetoothIntent.PAIRING_CANCEL_ACTION); - mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM); - } - - public void onRemoteDeviceFound(String address, int deviceClass, short rssi) { + private void onRemoteDeviceFound(String address, int deviceClass, short rssi) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_FOUND_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); intent.putExtra(BluetoothIntent.CLASS, deviceClass); intent.putExtra(BluetoothIntent.RSSI, rssi); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteDeviceDisappeared(String address) { + private void onRemoteDeviceDisappeared(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISAPPEARED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteClassUpdated(String address, int deviceClass) { + private void onRemoteClassUpdated(String address, int deviceClass) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_CLASS_UPDATED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); intent.putExtra(BluetoothIntent.CLASS, deviceClass); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteDeviceConnected(String address) { + private void onRemoteDeviceConnected(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteDeviceDisconnectRequested(String address) { + private void onRemoteDeviceDisconnectRequested(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISCONNECT_REQUESTED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteDeviceDisconnected(String address) { + private void onRemoteDeviceDisconnected(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISCONNECTED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteNameUpdated(String address, String name) { + private void onRemoteNameUpdated(String address, String name) { Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_UPDATED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); intent.putExtra(BluetoothIntent.NAME, name); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteNameFailed(String address) { + private void onRemoteNameFailed(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_FAILED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteNameChanged(String address, String name) { + private void onRemoteNameChanged(String address, String name) { Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_UPDATED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); intent.putExtra(BluetoothIntent.NAME, name); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteAliasChanged(String address, String alias) { - Intent intent = new Intent(BluetoothIntent.REMOTE_ALIAS_CHANGED_ACTION); - intent.putExtra(BluetoothIntent.ADDRESS, address); - intent.putExtra(BluetoothIntent.ALIAS, alias); - mContext.sendBroadcast(intent, BLUETOOTH_PERM); - } - public void onRemoteAliasCleared(String address) { - Intent intent = new Intent(BluetoothIntent.REMOTE_ALIAS_CLEARED_ACTION); - intent.putExtra(BluetoothIntent.ADDRESS, address); - mContext.sendBroadcast(intent, BLUETOOTH_PERM); - } private void onCreateBondingResult(String address, int result) { address = address.toUpperCase(); if (result == BluetoothError.SUCCESS) { mBluetoothService.getBondState().setBondState(address, BluetoothDevice.BOND_BONDED); + if (mBluetoothService.getBondState().isAutoPairingAttemptsInProgress(address)) { + mBluetoothService.getBondState().clearPinAttempts(address); + } + } else if (result == BluetoothDevice.UNBOND_REASON_AUTH_FAILED && + mBluetoothService.getBondState().getAttempt(address) == 1) { + mBluetoothService.getBondState().addAutoPairingFailure(address); + pairingAttempt(address, result); + } else if (result == BluetoothDevice.UNBOND_REASON_REMOTE_DEVICE_DOWN && + mBluetoothService.getBondState().isAutoPairingAttemptsInProgress(address)) { + pairingAttempt(address, result); } else { mBluetoothService.getBondState().setBondState(address, BluetoothDevice.BOND_NOT_BONDED, result); + if (mBluetoothService.getBondState().isAutoPairingAttemptsInProgress(address)) { + mBluetoothService.getBondState().clearPinAttempts(address); + } + } + } + + private void pairingAttempt(String address, int result) { + // This happens when our initial guess of "0000" as the pass key + // fails. Try to create the bond again and display the pin dialog + // to the user. Use back-off while posting the delayed + // message. The initial value is + // INIT_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY and the max value is + // MAX_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY. If the max value is + // reached, display an error to the user. + int attempt = mBluetoothService.getBondState().getAttempt(address); + if (attempt * INIT_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY > + MAX_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY) { + mBluetoothService.getBondState().clearPinAttempts(address); + mBluetoothService.getBondState().setBondState(address, + BluetoothDevice.BOND_NOT_BONDED, result); + return; + } + + Message message = mHandler.obtainMessage(EVENT_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY); + message.obj = address; + boolean postResult = mHandler.sendMessageDelayed(message, + attempt * INIT_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY); + if (!postResult) { + mBluetoothService.getBondState().clearPinAttempts(address); + mBluetoothService.getBondState().setBondState(address, + BluetoothDevice.BOND_NOT_BONDED, result); + return; } + mBluetoothService.getBondState().attempt(address); } - public void onBondingCreated(String address) { + private void onBondingCreated(String address) { mBluetoothService.getBondState().setBondState(address.toUpperCase(), BluetoothDevice.BOND_BONDED); } - public void onBondingRemoved(String address) { + private void onBondingRemoved(String address) { mBluetoothService.getBondState().setBondState(address.toUpperCase(), BluetoothDevice.BOND_NOT_BONDED, BluetoothDevice.UNBOND_REASON_REMOVED); } - public void onNameChanged(String name) { + private void onNameChanged(String name) { Intent intent = new Intent(BluetoothIntent.NAME_CHANGED_ACTION); intent.putExtra(BluetoothIntent.NAME, name); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onPasskeyAgentRequest(String address, int nativeData) { + private void onPasskeyAgentRequest(String address, int nativeData) { address = address.toUpperCase(); mPasskeyAgentRequestData.put(address, new Integer(nativeData)); @@ -272,35 +322,65 @@ class BluetoothEventLoop { case BluetoothClass.Device.AUDIO_VIDEO_PORTABLE_AUDIO: case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO: case BluetoothClass.Device.AUDIO_VIDEO_HIFI_AUDIO: - if (mBluetoothService.getBondState().getAttempt(address) < 1) { + if (!mBluetoothService.getBondState().hasAutoPairingFailed(address) && + !mBluetoothService.getBondState().isAutoPairingBlacklisted(address)) { mBluetoothService.getBondState().attempt(address); mBluetoothService.setPin(address, BluetoothDevice.convertPinToBytes("0000")); return; } - } + } } Intent intent = new Intent(BluetoothIntent.PAIRING_REQUEST_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM); } - public void onPasskeyAgentCancel(String address) { + private void onPasskeyAgentCancel(String address) { address = address.toUpperCase(); mPasskeyAgentRequestData.remove(address); Intent intent = new Intent(BluetoothIntent.PAIRING_CANCEL_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM); mBluetoothService.getBondState().setBondState(address, BluetoothDevice.BOND_NOT_BONDED, - BluetoothDevice.UNBOND_REASON_CANCELLED); + BluetoothDevice.UNBOND_REASON_AUTH_CANCELED); + } + + private boolean onAuthAgentAuthorize(String address, String service, String uuid) { + boolean authorized = false; + if (service.endsWith("service_audio")) { + BluetoothA2dp a2dp = new BluetoothA2dp(mContext); + authorized = a2dp.getSinkPriority(address) > BluetoothA2dp.PRIORITY_OFF; + if (authorized) { + Log.i(TAG, "Allowing incoming A2DP connection from " + address); + } else { + Log.i(TAG, "Rejecting incoming A2DP connection from " + address); + } + } else { + Log.i(TAG, "Rejecting incoming " + service + " connection from " + address); + } + return authorized; + } + + private void onAuthAgentCancel(String address, String service, String uuid) { + // We immediately response to DBUS Authorize() so this should not + // usually happen + log("onAuthAgentCancel(" + address + ", " + service + ", " + uuid + ")"); } private void onGetRemoteServiceChannelResult(String address, int channel) { IBluetoothDeviceCallback callback = mGetRemoteServiceChannelCallbacks.get(address); if (callback != null) { + mGetRemoteServiceChannelCallbacks.remove(address); try { callback.onGetRemoteServiceChannelResult(address, channel); } catch (RemoteException e) {} - mGetRemoteServiceChannelCallbacks.remove(address); + } + } + + private void onRestartRequired() { + if (mBluetoothService.isEnabled()) { + Log.e(TAG, "*** A serious error occured (did hcid crash?) - restarting Bluetooth ***"); + mHandler.sendEmptyMessage(EVENT_RESTART_BLUETOOTH); } } diff --git a/core/java/android/server/checkin/CheckinProvider.java b/core/java/android/server/checkin/CheckinProvider.java deleted file mode 100644 index 86ece4ac1c2a38f39e8f182edbc5603a36a22eec..0000000000000000000000000000000000000000 --- a/core/java/android/server/checkin/CheckinProvider.java +++ /dev/null @@ -1,388 +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. - */ - -package android.server.checkin; - -import android.content.ContentProvider; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.pm.PackageManager; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; -import android.database.sqlite.SQLiteQueryBuilder; -import android.net.Uri; -import android.os.Environment; -import android.provider.BaseColumns; -import android.provider.Checkin; -import android.util.Log; - -import java.io.File; - -/** - * Content provider for the database used to store events and statistics - * while they wait to be uploaded by the checkin service. - */ -public class CheckinProvider extends ContentProvider { - /** Class identifier for logging. */ - private static final String TAG = "CheckinProvider"; - - /** Filename of database (in /data directory). */ - private static final String DATABASE_FILENAME = "checkin.db"; - - /** Version of database schema. */ - private static final int DATABASE_VERSION = 1; - - /** Maximum number of events recorded. */ - private static final int EVENT_LIMIT = 1000; - - /** Maximum size of individual event data. */ - private static final int EVENT_SIZE = 8192; - - /** Maximum number of crashes recorded. */ - private static final int CRASH_LIMIT = 25; - - /** Maximum size of individual crashes recorded. */ - private static final int CRASH_SIZE = 16384; - - /** Permission required for access to the 'properties' database. */ - private static final String PROPERTIES_PERMISSION = - "android.permission.ACCESS_CHECKIN_PROPERTIES"; - - /** Lock for stats read-modify-write update cycle (see {@link #insert}). */ - private final Object mStatsLock = new Object(); - - /** The underlying SQLite database. */ - private SQLiteOpenHelper mOpenHelper; - - private static class OpenHelper extends SQLiteOpenHelper { - public OpenHelper(Context context) { - super(context, DATABASE_FILENAME, null, DATABASE_VERSION); - - // The database used to live in /data/checkin.db. - File oldLocation = Environment.getDataDirectory(); - File old = new File(oldLocation, DATABASE_FILENAME); - File file = context.getDatabasePath(DATABASE_FILENAME); - - // Try to move the file to the new location. - // TODO: Remove this code before shipping. - if (old.exists() && !file.exists() && !old.renameTo(file)) { - Log.e(TAG, "Can't rename " + old + " to " + file); - } - if (old.exists() && !old.delete()) { - // Clean up the old data file in any case. - Log.e(TAG, "Can't remove " + old); - } - } - - @Override - public void onCreate(SQLiteDatabase db) { - db.execSQL("CREATE TABLE " + Checkin.Events.TABLE_NAME + " (" + - BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Checkin.Events.TAG + " TEXT NOT NULL," + - Checkin.Events.VALUE + " TEXT DEFAULT \"\"," + - Checkin.Events.DATE + " INTEGER NOT NULL)"); - - db.execSQL("CREATE INDEX events_index ON " + - Checkin.Events.TABLE_NAME + " (" + - Checkin.Events.TAG + ")"); - - db.execSQL("CREATE TABLE " + Checkin.Stats.TABLE_NAME + " (" + - BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Checkin.Stats.TAG + " TEXT UNIQUE," + - Checkin.Stats.COUNT + " INTEGER DEFAULT 0," + - Checkin.Stats.SUM + " REAL DEFAULT 0.0)"); - - db.execSQL("CREATE TABLE " + Checkin.Crashes.TABLE_NAME + " (" + - BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Checkin.Crashes.DATA + " TEXT NOT NULL," + - Checkin.Crashes.LOGS + " TEXT)"); - - db.execSQL("CREATE TABLE " + Checkin.Properties.TABLE_NAME + " (" + - BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Checkin.Properties.TAG + " TEXT UNIQUE ON CONFLICT REPLACE," - + Checkin.Properties.VALUE + " TEXT DEFAULT \"\")"); - } - - @Override - public void onUpgrade(SQLiteDatabase db, int old, int version) { - db.execSQL("DROP TABLE IF EXISTS " + Checkin.Events.TABLE_NAME); - db.execSQL("DROP TABLE IF EXISTS " + Checkin.Stats.TABLE_NAME); - db.execSQL("DROP TABLE IF EXISTS " + Checkin.Crashes.TABLE_NAME); - db.execSQL("DROP TABLE IF EXISTS " + Checkin.Properties.TABLE_NAME); - onCreate(db); - } - } - - @Override public boolean onCreate() { - mOpenHelper = new OpenHelper(getContext()); - return true; - } - - @Override - public Cursor query(Uri uri, String[] select, - String where, String[] args, String sort) { - checkPermissions(uri); - SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); - qb.setTables(uri.getPathSegments().get(0)); - if (uri.getPathSegments().size() == 2) { - qb.appendWhere("_id=" + ContentUris.parseId(uri)); - } else if (uri.getPathSegments().size() != 1) { - throw new IllegalArgumentException("Invalid query URI: " + uri); - } - - SQLiteDatabase db = mOpenHelper.getReadableDatabase(); - Cursor cursor = qb.query(db, select, where, args, null, null, sort); - cursor.setNotificationUri(getContext().getContentResolver(), uri); - return cursor; - } - - @Override - public Uri insert(Uri uri, ContentValues values) { - checkPermissions(uri); - if (uri.getPathSegments().size() != 1) { - throw new IllegalArgumentException("Invalid insert URI: " + uri); - } - - long id; - String table = uri.getPathSegments().get(0); - if (Checkin.Events.TABLE_NAME.equals(table)) { - id = insertEvent(values); - } else if (Checkin.Stats.TABLE_NAME.equals(table)) { - id = insertStats(values); - } else if (Checkin.Crashes.TABLE_NAME.equals(table)) { - id = insertCrash(values); - } else { - id = mOpenHelper.getWritableDatabase().insert(table, null, values); - } - - if (id < 0) { - return null; - } else { - uri = ContentUris.withAppendedId(uri, id); - getContext().getContentResolver().notifyChange(uri, null); - return uri; - } - } - - /** - * Insert an entry into the events table. - * Trims old events from the table to keep the size bounded. - * @param values to insert - * @return the row ID of the new entry - */ - private long insertEvent(ContentValues values) { - String value = values.getAsString(Checkin.Events.VALUE); - if (value != null && value.length() > EVENT_SIZE) { - // Event values are readable text, so they can be truncated. - value = value.substring(0, EVENT_SIZE - 3) + "..."; - values.put(Checkin.Events.VALUE, value); - } - - if (!values.containsKey(Checkin.Events.DATE)) { - values.put(Checkin.Events.DATE, System.currentTimeMillis()); - } - - // TODO: Make this more efficient; don't do it on every insert. - // Also, consider keeping the most recent instance of every tag, - // and possibly update a counter when events are deleted. - - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - db.execSQL("DELETE FROM " + - Checkin.Events.TABLE_NAME + " WHERE " + - Checkin.Events._ID + " IN (SELECT " + - Checkin.Events._ID + " FROM " + - Checkin.Events.TABLE_NAME + " ORDER BY " + - Checkin.Events.DATE + " DESC LIMIT -1 OFFSET " + - (EVENT_LIMIT - 1) + ")"); - return db.insert(Checkin.Events.TABLE_NAME, null, values); - } - - /** - * Add an entry into the stats table. - * For statistics, instead of just inserting a row into the database, - * we add the count and sum values to the existing values (if any) - * for the specified tag. This must be done with a lock held, - * to avoid a race condition during the read-modify-write update. - * @param values to insert - * @return the row ID of the modified entry - */ - private long insertStats(ContentValues values) { - synchronized (mStatsLock) { - String tag = values.getAsString(Checkin.Stats.TAG); - if (tag == null) { - throw new IllegalArgumentException("Tag required:" + values); - } - - // Look for existing values with this tag. - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - Cursor cursor = db.query(false, - Checkin.Stats.TABLE_NAME, - new String[] { - Checkin.Stats._ID, - Checkin.Stats.COUNT, - Checkin.Stats.SUM - }, - Checkin.Stats.TAG + "=?", - new String[] { tag }, - null, null, null, null /* limit */); - - try { - if (cursor == null || !cursor.moveToNext()) { - // This is a new statistic, insert it directly. - return db.insert(Checkin.Stats.TABLE_NAME, null, values); - } else { - // Depend on SELECT column order to avoid getColumnIndex() - long id = cursor.getLong(0); - int count = cursor.getInt(1); - double sum = cursor.getDouble(2); - - Integer countAdd = values.getAsInteger(Checkin.Stats.COUNT); - if (countAdd != null) count += countAdd.intValue(); - - Double sumAdd = values.getAsDouble(Checkin.Stats.SUM); - if (sumAdd != null) sum += sumAdd.doubleValue(); - - if (count <= 0 && sum == 0.0) { - // Updated to nothing: delete the row! - cursor.deleteRow(); - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Checkin.Stats.CONTENT_URI, id), null); - return -1; - } else { - if (countAdd != null) cursor.updateInt(1, count); - if (sumAdd != null) cursor.updateDouble(2, sum); - cursor.commitUpdates(); - return id; - } - } - } finally { - // Always clean up the cursor. - if (cursor != null) cursor.close(); - } - } - } - - /** - * Add an entry into the crashes table. - * @param values to insert - * @return the row ID of the modified entry - */ - private long insertCrash(ContentValues values) { - try { - int crashSize = values.getAsString(Checkin.Crashes.DATA).length(); - if (crashSize > CRASH_SIZE) { - // The crash is too big. Don't report it, but do log a stat. - Checkin.updateStats(getContext().getContentResolver(), - Checkin.Stats.Tag.CRASHES_TRUNCATED, 1, 0.0); - throw new IllegalArgumentException("Too big: " + crashSize); - } - - // Count the number of crashes reported, even if they roll over. - Checkin.updateStats(getContext().getContentResolver(), - Checkin.Stats.Tag.CRASHES_REPORTED, 1, 0.0); - - // Trim the crashes database, if needed. - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - db.execSQL("DELETE FROM " + - Checkin.Crashes.TABLE_NAME + " WHERE " + - Checkin.Crashes._ID + " IN (SELECT " + - Checkin.Crashes._ID + " FROM " + - Checkin.Crashes.TABLE_NAME + " ORDER BY " + - Checkin.Crashes._ID + " DESC LIMIT -1 OFFSET " + - (CRASH_LIMIT - 1) + ")"); - - return db.insert(Checkin.Crashes.TABLE_NAME, null, values); - } catch (Throwable t) { - // To avoid an infinite crash-reporting loop, swallow the error. - Log.e("CheckinProvider", "Error inserting crash: " + t); - return -1; - } - } - - // TODO: optimize bulkInsert, especially for stats? - - @Override - public int update(Uri uri, ContentValues values, - String where, String[] args) { - checkPermissions(uri); - if (uri.getPathSegments().size() == 2) { - if (where != null && where.length() > 0) { - throw new UnsupportedOperationException( - "WHERE clause not supported for update: " + uri); - } - where = "_id=" + ContentUris.parseId(uri); - args = null; - } else if (uri.getPathSegments().size() != 1) { - throw new IllegalArgumentException("Invalid update URI: " + uri); - } - - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - int count = db.update(uri.getPathSegments().get(0), values, where, args); - getContext().getContentResolver().notifyChange(uri, null); - return count; - } - - @Override - public int delete(Uri uri, String where, String[] args) { - checkPermissions(uri); - if (uri.getPathSegments().size() == 2) { - if (where != null && where.length() > 0) { - throw new UnsupportedOperationException( - "WHERE clause not supported for delete: " + uri); - } - where = "_id=" + ContentUris.parseId(uri); - args = null; - } else if (uri.getPathSegments().size() != 1) { - throw new IllegalArgumentException("Invalid delete URI: " + uri); - } - - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - int count = db.delete(uri.getPathSegments().get(0), where, args); - getContext().getContentResolver().notifyChange(uri, null); - return count; - } - - @Override - public String getType(Uri uri) { - if (uri.getPathSegments().size() == 1) { - return "vnd.android.cursor.dir/" + uri.getPathSegments().get(0); - } else if (uri.getPathSegments().size() == 2) { - return "vnd.android.cursor.item/" + uri.getPathSegments().get(0); - } else { - throw new IllegalArgumentException("Invalid URI: " + uri); - } - } - - /** - * Make sure the caller has permission to the database. - * @param uri the caller is requesting access to - * @throws SecurityException if the caller is forbidden. - */ - private void checkPermissions(Uri uri) { - if (uri.getPathSegments().size() < 1) { - throw new IllegalArgumentException("Invalid query URI: " + uri); - } - - String table = uri.getPathSegments().get(0); - if (table.equals(Checkin.Properties.TABLE_NAME) && - getContext().checkCallingOrSelfPermission(PROPERTIES_PERMISSION) != - PackageManager.PERMISSION_GRANTED) { - throw new SecurityException("Cannot access checkin properties"); - } - } -} diff --git a/core/java/android/server/checkin/FallbackCheckinService.java b/core/java/android/server/checkin/FallbackCheckinService.java deleted file mode 100644 index 65921af5038b5cad19f59582eeea6b98b63b683c..0000000000000000000000000000000000000000 --- a/core/java/android/server/checkin/FallbackCheckinService.java +++ /dev/null @@ -1,49 +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. - */ - -package android.server.checkin; - -import android.os.ICheckinService; -import android.os.RemoteException; -import android.os.IParentalControlCallback; -import com.google.android.net.ParentalControlState; - -/** - * @hide - */ -public final class FallbackCheckinService extends ICheckinService.Stub { - public FallbackCheckinService() { - } - - public void reportCrashSync(byte[] crashData) throws RemoteException { - } - - public void reportCrashAsync(byte[] crashData) throws RemoteException { - } - - public void masterClear() throws RemoteException { - } - - public void getParentalControlState(IParentalControlCallback p) throws RemoteException { - ParentalControlState state = new ParentalControlState(); - state.isEnabled = false; - p.onResult(state); - } - - public void getParentalControlState(IParentalControlCallback p, String requestingApp) - throws android.os.RemoteException { - } -} diff --git a/core/java/android/server/checkin/package.html b/core/java/android/server/checkin/package.html deleted file mode 100644 index 1c9bf9dad8350012996a920f64cbd577fdf72bb7..0000000000000000000000000000000000000000 --- a/core/java/android/server/checkin/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - - {@hide} - - diff --git a/core/java/android/server/search/SearchableInfo.java b/core/java/android/server/search/SearchableInfo.java index c8f395e8a03c70eab8c3b2967dd70df019454e87..0c04839a4472b7d169d6d76411e1221e728f38de 100644 --- a/core/java/android/server/search/SearchableInfo.java +++ b/core/java/android/server/search/SearchableInfo.java @@ -35,6 +35,7 @@ import android.text.InputType; import android.util.AttributeSet; import android.util.Log; import android.util.Xml; +import android.view.inputmethod.EditorInfo; import java.io.IOException; import java.util.ArrayList; @@ -77,6 +78,7 @@ public final class SearchableInfo implements Parcelable { private int mIconId = 0; private int mSearchButtonText = 0; private int mSearchInputType = 0; + private int mSearchImeOptions = 0; private String mSuggestAuthority = null; private String mSuggestPath = null; private String mSuggestSelection = null; @@ -86,6 +88,16 @@ public final class SearchableInfo implements Parcelable { private String mSuggestProviderPackage = null; private Context mCacheActivityContext = null; // use during setup only - don't hold memory! + // Flag values for Searchable_voiceSearchMode + private static int VOICE_SEARCH_SHOW_BUTTON = 1; + private static int VOICE_SEARCH_LAUNCH_WEB_SEARCH = 2; + private static int VOICE_SEARCH_LAUNCH_RECOGNIZER = 4; + private int mVoiceSearchMode = 0; + private int mVoiceLanguageModeId; // voiceLanguageModel + private int mVoicePromptTextId; // voicePromptText + private int mVoiceLanguageId; // voiceLanguage + private int mVoiceMaxResults; // voiceMaxResults + /** * Set the default searchable activity (when none is specified). */ @@ -419,8 +431,9 @@ public final class SearchableInfo implements Parcelable { com.android.internal.R.styleable.Searchable_searchButtonText, 0); mSearchInputType = a.getInt(com.android.internal.R.styleable.Searchable_inputType, InputType.TYPE_CLASS_TEXT | - InputType.TYPE_TEXT_FLAG_SEARCH | - InputType.TYPE_TEXT_VARIATION_SEARCH_STRING); + InputType.TYPE_TEXT_VARIATION_NORMAL); + mSearchImeOptions = a.getInt(com.android.internal.R.styleable.Searchable_imeOptions, + EditorInfo.IME_ACTION_SEARCH); setSearchModeFlags(); if (DBG_INHIBIT_SUGGESTIONS == 0) { @@ -435,6 +448,18 @@ public final class SearchableInfo implements Parcelable { mSuggestIntentData = a.getString( com.android.internal.R.styleable.Searchable_searchSuggestIntentData); } + mVoiceSearchMode = + a.getInt(com.android.internal.R.styleable.Searchable_voiceSearchMode, 0); + // TODO this didn't work - came back zero from YouTube + mVoiceLanguageModeId = + a.getResourceId(com.android.internal.R.styleable.Searchable_voiceLanguageModel, 0); + mVoicePromptTextId = + a.getResourceId(com.android.internal.R.styleable.Searchable_voicePromptText, 0); + mVoiceLanguageId = + a.getResourceId(com.android.internal.R.styleable.Searchable_voiceLanguage, 0); + mVoiceMaxResults = + a.getInt(com.android.internal.R.styleable.Searchable_voiceMaxResults, 0); + a.recycle(); // get package info for suggestions provider (if any) @@ -462,11 +487,6 @@ public final class SearchableInfo implements Parcelable { * Convert searchmode to flags. */ private void setSearchModeFlags() { - // decompose searchMode attribute - // TODO How do I reconcile these hardcoded values with the flag bits defined in - // in attrs.xml? e.g. android.R.id.filterMode = 0x010200a4 instead of just "1" - /* mFilterMode = (0 != (mSearchMode & 1)); */ - /* mQuickStart = (0 != (mSearchMode & 2)); */ mBadgeLabel = (0 != (mSearchMode & 4)); mBadgeIcon = (0 != (mSearchMode & 8)) && (mIconId != 0); mQueryRewriteFromData = (0 != (mSearchMode & 0x10)); @@ -653,6 +673,59 @@ public final class SearchableInfo implements Parcelable { return mIconId; } + /** + * @return true if android:voiceSearchMode="showVoiceSearchButton" + */ + public boolean getVoiceSearchEnabled() { + return 0 != (mVoiceSearchMode & VOICE_SEARCH_SHOW_BUTTON); + } + + /** + * @return true if android:voiceSearchMode="launchWebSearch" + */ + public boolean getVoiceSearchLaunchWebSearch() { + return 0 != (mVoiceSearchMode & VOICE_SEARCH_LAUNCH_WEB_SEARCH); + } + + /** + * @return true if android:voiceSearchMode="launchRecognizer" + */ + public boolean getVoiceSearchLaunchRecognizer() { + return 0 != (mVoiceSearchMode & VOICE_SEARCH_LAUNCH_RECOGNIZER); + } + + /** + * @return the resource Id of the language model string, if specified in the searchable + * activity's metadata, or 0 if not specified. + */ + public int getVoiceLanguageModeId() { + return mVoiceLanguageModeId; + } + + /** + * @return the resource Id of the voice prompt text string, if specified in the searchable + * activity's metadata, or 0 if not specified. + */ + public int getVoicePromptTextId() { + return mVoicePromptTextId; + } + + /** + * @return the resource Id of the spoken langauge, if specified in the searchable + * activity's metadata, or 0 if not specified. + */ + public int getVoiceLanguageId() { + return mVoiceLanguageId; + } + + /** + * @return the max results count, if specified in the searchable + * activity's metadata, or 0 if not specified. + */ + public int getVoiceMaxResults() { + return mVoiceMaxResults; + } + /** * Return the resource Id of replacement text for the "Search" button. * @@ -672,6 +745,17 @@ public final class SearchableInfo implements Parcelable { return mSearchInputType; } + /** + * Return the input method options specified in the searchable attributes. + * This will default to EditorInfo.ACTION_SEARCH if not specified (which is + * appropriate for a search box). + * + * @return the input type + */ + public int getImeOptions() { + return mSearchImeOptions; + } + /** * Return the list of searchable activities, for use in the drop-down. */ @@ -712,6 +796,7 @@ public final class SearchableInfo implements Parcelable { mIconId = in.readInt(); mSearchButtonText = in.readInt(); mSearchInputType = in.readInt(); + mSearchImeOptions = in.readInt(); setSearchModeFlags(); mSuggestAuthority = in.readString(); @@ -727,6 +812,12 @@ public final class SearchableInfo implements Parcelable { } mSuggestProviderPackage = in.readString(); + + mVoiceSearchMode = in.readInt(); + mVoiceLanguageModeId = in.readInt(); + mVoicePromptTextId = in.readInt(); + mVoiceLanguageId = in.readInt(); + mVoiceMaxResults = in.readInt(); } public int describeContents() { @@ -742,6 +833,7 @@ public final class SearchableInfo implements Parcelable { dest.writeInt(mIconId); dest.writeInt(mSearchButtonText); dest.writeInt(mSearchInputType); + dest.writeInt(mSearchImeOptions); dest.writeString(mSuggestAuthority); dest.writeString(mSuggestPath); @@ -764,5 +856,11 @@ public final class SearchableInfo implements Parcelable { } dest.writeString(mSuggestProviderPackage); + + dest.writeInt(mVoiceSearchMode); + dest.writeInt(mVoiceLanguageModeId); + dest.writeInt(mVoicePromptTextId); + dest.writeInt(mVoiceLanguageId); + dest.writeInt(mVoiceMaxResults); } } diff --git a/core/java/android/speech/RecognizerIntent.java b/core/java/android/speech/RecognizerIntent.java index abbf8a77c31aa316a8d427626058e6445fef210f..987e763160de39ab2511d609e6dee30a4d366dc5 100644 --- a/core/java/android/speech/RecognizerIntent.java +++ b/core/java/android/speech/RecognizerIntent.java @@ -22,8 +22,6 @@ import android.content.Intent; /** * Constants for supporting speech recognition through starting an {@link Intent} - * - * @hide {pending API council review} */ public class RecognizerIntent { private RecognizerIntent() { @@ -32,7 +30,8 @@ public class RecognizerIntent { /** * Starts an activity that will prompt the user for speech and sends it through a - * speech recognizer. + * speech recognizer. The results will be returned via activity results, or forwarded + * via a PendingIntent if one is provided. * *

          Required extras: *

            @@ -41,9 +40,11 @@ public class RecognizerIntent { * *

            Optional extras: *

              - *
            • {@link Intent#EXTRA_PROMPT} + *
            • {@link #EXTRA_PROMPT} *
            • {@link #EXTRA_LANGUAGE} *
            • {@link #EXTRA_MAX_RESULTS} + *
            • {@link #EXTRA_RESULTS_PENDINGINTENT} + *
            • {@link #EXTRA_RESULTS_PENDINGINTENT_BUNDLE} *
            * *

            Result extras: @@ -56,6 +57,32 @@ public class RecognizerIntent { */ public static final String ACTION_RECOGNIZE_SPEECH = "android.speech.action.RECOGNIZE_SPEECH"; + /** + * Starts an activity that will prompt the user for speech, sends it through a + * speech recognizer, and invokes and displays a web search result. + * + *

            Required extras: + *

              + *
            • {@link #EXTRA_LANGUAGE_MODEL} + *
            + * + *

            Optional extras: + *

              + *
            • {@link #EXTRA_PROMPT} + *
            • {@link #EXTRA_LANGUAGE} + *
            • {@link #EXTRA_MAX_RESULTS} + *
            + * + *

            Result extras: + *

              + *
            • {@link #EXTRA_RESULTS} + *
            + * + *

            NOTE: There may not be any applications installed to handle this action, so you should + * make sure to catch {@link ActivityNotFoundException}. + */ + public static final String ACTION_WEB_SEARCH = "android.speech.action.WEB_SEARCH"; + /** * Informs the recognizer which speech model to prefer when performing * {@link #ACTION_RECOGNIZE_SPEECH}. The recognizer uses this @@ -65,27 +92,51 @@ public class RecognizerIntent { * @see #LANGUAGE_MODEL_FREE_FORM * @see #LANGUAGE_MODEL_WEB_SEARCH */ - public static final String EXTRA_LANGUAGE_MODEL = "language_model"; + public static final String EXTRA_LANGUAGE_MODEL = "android.speech.extra.LANGUAGE_MODEL"; - /** Free form speech recognition */ + /** + * Use a language model based on free-form speech recognition. This is a value to use for + * {@link #EXTRA_LANGUAGE_MODEL}. + * @see #EXTRA_LANGUAGE_MODEL + */ public static final String LANGUAGE_MODEL_FREE_FORM = "free_form"; - /** Use a language model based on web search terms */ + /** + * Use a language model based on web search terms. This is a value to use for + * {@link #EXTRA_LANGUAGE_MODEL}. + * @see #EXTRA_LANGUAGE_MODEL + */ public static final String LANGUAGE_MODEL_WEB_SEARCH = "web_search"; /** Optional text prompt to show to the user when asking them to speak. */ - public static final String EXTRA_PROMPT = "prompt"; + public static final String EXTRA_PROMPT = "android.speech.extra.PROMPT"; /** * Optional language override to inform the recognizer that it should expect speech in * a language different than the one set in the {@link java.util.Locale#getDefault()}. */ - public static final String EXTRA_LANGUAGE = "lang"; + public static final String EXTRA_LANGUAGE = "android.speech.extra.LANGUAGE"; /** * Optional limit on the maximum number of results to return. If omitted the recognizer * will choose how many results to return. Must be an integer. */ - public static final String EXTRA_MAX_RESULTS = "max_results"; + public static final String EXTRA_MAX_RESULTS = "android.speech.extra.MAX_RESULTS"; + + /** + * When the intent is {@link #ACTION_RECOGNIZE_SPEECH}, the speech input activity will + * return results to you via the activity results mechanism. Alternatively, if you use this + * extra to supply a PendingIntent, the results will be added to its bundle and the + * PendingIntent will be sent to its target. + */ + public static final String EXTRA_RESULTS_PENDINGINTENT = + "android.speech.extra.RESULTS_PENDINGINTENT"; + /** + * If you use {@link #EXTRA_RESULTS_PENDINGINTENT} to supply a forwarding intent, you can + * also use this extra to supply additional extras for the final intent. The search results + * will be added to this bundle, and the combined bundle will be sent to the target. + */ + public static final String EXTRA_RESULTS_PENDINGINTENT_BUNDLE = + "android.speech.extra.RESULTS_PENDINGINTENT_BUNDLE"; /** Result code returned when no matches are found for the given speech */ public static final int RESULT_NO_MATCH = Activity.RESULT_FIRST_USER; @@ -102,5 +153,5 @@ public class RecognizerIntent { * An ArrayList of the potential results when performing * {@link #ACTION_RECOGNIZE_SPEECH}. Only present when {@link Activity#RESULT_OK} is returned. */ - public static final String EXTRA_RESULTS = "results"; + public static final String EXTRA_RESULTS = "android.speech.extra.RESULTS"; } diff --git a/core/java/android/speech/srec/MicrophoneInputStream.java b/core/java/android/speech/srec/MicrophoneInputStream.java index 160a0034a5ddacd63c7c8ce0957317314bd48f91..fab77a9b8a0a4b7e4e68978af1eb0a8da6b1baa6 100644 --- a/core/java/android/speech/srec/MicrophoneInputStream.java +++ b/core/java/android/speech/srec/MicrophoneInputStream.java @@ -1,5 +1,5 @@ /*---------------------------------------------------------------------------* - * MicrophoneInputStream.java * + * MicrophoneInputStream.java * * * * Copyright 2007 Nuance Communciations, Inc. * * * @@ -45,8 +45,12 @@ public final class MicrophoneInputStream extends InputStream { */ public MicrophoneInputStream(int sampleRate, int fifoDepth) throws IOException { mAudioRecord = AudioRecordNew(sampleRate, fifoDepth); - if (mAudioRecord == 0) throw new IllegalStateException("not open"); - AudioRecordStart(mAudioRecord); + if (mAudioRecord == 0) throw new IOException("AudioRecord constructor failed - busy?"); + int status = AudioRecordStart(mAudioRecord); + if (status != 0) { + close(); + throw new IOException("AudioRecord start failed: " + status); + } } @Override @@ -99,7 +103,7 @@ public final class MicrophoneInputStream extends InputStream { // AudioRecord JNI interface // private static native int AudioRecordNew(int sampleRate, int fifoDepth); - private static native void AudioRecordStart(int audioRecord); + private static native int AudioRecordStart(int audioRecord); private static native int AudioRecordRead(int audioRecord, byte[] b, int offset, int length) throws IOException; private static native void AudioRecordStop(int audioRecord) throws IOException; private static native void AudioRecordDelete(int audioRecord) throws IOException; diff --git a/core/java/android/speech/srec/package.html b/core/java/android/speech/srec/package.html index 723b30bb6e9e676814aacbaf56bd34dbe7a4a7d9..9a99df85a90640b09c802c8f876b16d6352fd3bf 100644 --- a/core/java/android/speech/srec/package.html +++ b/core/java/android/speech/srec/package.html @@ -1,5 +1,6 @@ Simple, synchronous SREC speech recognition API. +@hide diff --git a/core/java/android/text/Annotation.java b/core/java/android/text/Annotation.java index a3812a80f960aed9586c0c3f118f364ec7f624e4..dbc290b76c035f388b8c0c64c4679bc7826da30f 100644 --- a/core/java/android/text/Annotation.java +++ b/core/java/android/text/Annotation.java @@ -16,20 +16,40 @@ package android.text; +import android.os.Parcel; + /** * Annotations are simple key-value pairs that are preserved across * TextView save/restore cycles and can be used to keep application-specific * data that needs to be maintained for regions of text. */ -public class Annotation { - private String mKey; - private String mValue; +public class Annotation implements ParcelableSpan { + private final String mKey; + private final String mValue; public Annotation(String key, String value) { mKey = key; mValue = value; } + public Annotation(Parcel src) { + mKey = src.readString(); + mValue = src.readString(); + } + + public int getSpanTypeId() { + return TextUtils.ANNOTATION; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mKey); + dest.writeString(mValue); + } + public String getKey() { return mKey; } diff --git a/core/java/android/text/Html.java b/core/java/android/text/Html.java index 90f5e4c683a1769c57757e21a51e2e794ed6fdf7..849571485dc7a85c88e2efd5c78eeecee63913f9 100644 --- a/core/java/android/text/Html.java +++ b/core/java/android/text/Html.java @@ -700,7 +700,41 @@ class HtmlToSpannedConverter implements ContentHandler { } public void characters(char ch[], int start, int length) throws SAXException { - mSpannableStringBuilder.append(CharBuffer.wrap(ch, start, length)); + StringBuilder sb = new StringBuilder(); + + /* + * Ignore whitespace that immediately follows other whitespace; + * newlines count as spaces. + */ + + for (int i = 0; i < length; i++) { + char c = ch[i + start]; + + if (c == ' ' || c == '\n') { + char pred; + int len = sb.length(); + + if (len == 0) { + len = mSpannableStringBuilder.length(); + + if (len == 0) { + pred = '\n'; + } else { + pred = mSpannableStringBuilder.charAt(len - 1); + } + } else { + pred = sb.charAt(len - 1); + } + + if (pred != ' ' && pred != '\n') { + sb.append(' '); + } + } else { + sb.append(c); + } + } + + mSpannableStringBuilder.append(sb); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { diff --git a/core/java/android/text/InputType.java b/core/java/android/text/InputType.java index bd868340dcaff6e792c176ccaceab1baef03127e..d50684af911d54ff53c7825fd3565c7c4222f7a0 100644 --- a/core/java/android/text/InputType.java +++ b/core/java/android/text/InputType.java @@ -116,14 +116,17 @@ public interface InputType { /** * Flag for {@link #TYPE_CLASS_TEXT}: multiple lines of text can be - * entered into the field. + * entered into the field. If this flag is not set, the text field + * will be constrained to a single line. */ public static final int TYPE_TEXT_FLAG_MULTI_LINE = 0x00020000; /** - * Flag for {@link #TYPE_CLASS_TEXT}: flags any text being used as a search string + * Flag for {@link #TYPE_CLASS_TEXT}: the regular text view associated + * with this should not be multi-line, but when a fullscreen input method + * is providing text it should use multiple lines if it can. */ - public static final int TYPE_TEXT_FLAG_SEARCH = 0x00040000; + public static final int TYPE_TEXT_FLAG_IME_MULTI_LINE = 0x00040000; // ---------------------------------------------------------------------- @@ -149,35 +152,54 @@ public interface InputType { public static final int TYPE_TEXT_VARIATION_EMAIL_SUBJECT = 0x00000030; /** - * Variation of {@link #TYPE_CLASS_TEXT}: entering the content of - * an e-mail. + * Variation of {@link #TYPE_CLASS_TEXT}: entering a short, possibly informal + * message such as an instant message or a text message. */ - public static final int TYPE_TEXT_VARIATION_EMAIL_CONTENT = 0x00000040; + public static final int TYPE_TEXT_VARIATION_SHORT_MESSAGE = 0x00000040; + /** + * Variation of {@link #TYPE_CLASS_TEXT}: entering the content of a long, possibly + * formal message such as the body of an e-mail. + */ + public static final int TYPE_TEXT_VARIATION_LONG_MESSAGE = 0x00000050; + /** * Variation of {@link #TYPE_CLASS_TEXT}: entering the name of a person. */ - public static final int TYPE_TEXT_VARIATION_PERSON_NAME = 0x00000050; + public static final int TYPE_TEXT_VARIATION_PERSON_NAME = 0x00000060; /** * Variation of {@link #TYPE_CLASS_TEXT}: entering a postal mailing address. */ - public static final int TYPE_TEXT_VARIATION_POSTAL_ADDRESS = 0x00000060; + public static final int TYPE_TEXT_VARIATION_POSTAL_ADDRESS = 0x00000070; /** * Variation of {@link #TYPE_CLASS_TEXT}: entering a password. */ - public static final int TYPE_TEXT_VARIATION_PASSWORD = 0x00000070; + public static final int TYPE_TEXT_VARIATION_PASSWORD = 0x00000080; /** - * Variation of {@link #TYPE_CLASS_TEXT}: entering a simple text search (e.g. web search) + * Variation of {@link #TYPE_CLASS_TEXT}: entering a password, which should + * be visible to the user. */ - public static final int TYPE_TEXT_VARIATION_SEARCH_STRING = 0x00000080; + public static final int TYPE_TEXT_VARIATION_VISIBLE_PASSWORD = 0x00000090; /** * Variation of {@link #TYPE_CLASS_TEXT}: entering text inside of a web form. */ - public static final int TYPE_TEXT_VARIATION_WEB_EDIT_TEXT = 0x00000090; + public static final int TYPE_TEXT_VARIATION_WEB_EDIT_TEXT = 0x000000a0; + + /** + * Variation of {@link #TYPE_CLASS_TEXT}: entering text to filter contents + * of a list etc. + */ + public static final int TYPE_TEXT_VARIATION_FILTER = 0x000000b0; + + /** + * Variation of {@link #TYPE_CLASS_TEXT}: entering text for phonetic + * pronunciation, such as a phonetic name field in contacts. + */ + public static final int TYPE_TEXT_VARIATION_PHONETIC = 0x000000c0; // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- diff --git a/core/java/android/text/NoCopySpan.java b/core/java/android/text/NoCopySpan.java new file mode 100644 index 0000000000000000000000000000000000000000..0855c0b250c1b1a5a4c8c8b19d1492df498131c4 --- /dev/null +++ b/core/java/android/text/NoCopySpan.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package android.text; + +/** + * This interface should be added to a span object that should not be copied + * into a new Spenned when performing a slice or copy operation on the original + * Spanned it was placed in. + */ +public interface NoCopySpan { + /** + * Convenience equivalent for when you would just want a new Object() for + * a span but want it to be no-copy. Use this instead. + */ + public class Concrete implements NoCopySpan { + } +} diff --git a/location/java/com/android/internal/location/protocol/GAddress.java b/core/java/android/text/ParcelableSpan.java similarity index 53% rename from location/java/com/android/internal/location/protocol/GAddress.java rename to core/java/android/text/ParcelableSpan.java index 86a3912e360682aac1415330f1196612ae962540..224511a7172c2998ff5140a988af7a82bd80a174 100644 --- a/location/java/com/android/internal/location/protocol/GAddress.java +++ b/core/java/android/text/ParcelableSpan.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 The Android Open Source Project + * 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. @@ -14,10 +14,18 @@ * limitations under the License. */ -package com.android.internal.location.protocol; +package android.text; -public interface GAddress { - static final int FORMATTED_ADDRESS_LINE = 1; - static final int COMPONENT = 2; -} +import android.os.Parcelable; +/** + * A special kind of Parcelable for objects that will serve as text spans. + * This can only be used by code in the framework; it is not intended for + * applications to implement their own Parcelable spans. + */ +public interface ParcelableSpan extends Parcelable { + /** + * Return a special type identifier for this span class. + */ + public abstract int getSpanTypeId(); +} diff --git a/core/java/android/text/Selection.java b/core/java/android/text/Selection.java index 44469eced07e96006de7a9ff1e427e9b2742f478..bb98bce67cee8cc75507d7d6ab374403d9c3393e 100644 --- a/core/java/android/text/Selection.java +++ b/core/java/android/text/Selection.java @@ -72,7 +72,7 @@ public class Selection { if (ostart != start || oend != stop) { text.setSpan(SELECTION_START, start, start, - Spanned.SPAN_POINT_POINT); + Spanned.SPAN_POINT_POINT|Spanned.SPAN_INTERMEDIATE); text.setSpan(SELECTION_END, stop, stop, Spanned.SPAN_POINT_POINT); } @@ -417,8 +417,8 @@ public class Selection { } } - private static final class START { }; - private static final class END { }; + private static final class START implements NoCopySpan { }; + private static final class END implements NoCopySpan { }; /* * Public constants diff --git a/core/java/android/text/SpanWatcher.java b/core/java/android/text/SpanWatcher.java index f99882a45226fb1a81460c193242ef239d28d695..01e82c815ac82e42984182c5cbf046350488a8ff 100644 --- a/core/java/android/text/SpanWatcher.java +++ b/core/java/android/text/SpanWatcher.java @@ -21,7 +21,7 @@ package android.text; * will be called to notify it that other markup objects have been * added, changed, or removed. */ -public interface SpanWatcher { +public interface SpanWatcher extends NoCopySpan { /** * This method is called to notify you that the specified object * has been attached to the specified range of the text. diff --git a/core/java/android/text/SpannableStringBuilder.java b/core/java/android/text/SpannableStringBuilder.java index 223ce2fc299270a292a140d5af07a43ef82274c2..caaafa1473976ea153e614e36df24da26b9b81a2 100644 --- a/core/java/android/text/SpannableStringBuilder.java +++ b/core/java/android/text/SpannableStringBuilder.java @@ -70,6 +70,10 @@ implements CharSequence, GetChars, Spannable, Editable, Appendable, Object[] spans = sp.getSpans(start, end, Object.class); for (int i = 0; i < spans.length; i++) { + if (spans[i] instanceof NoCopySpan) { + continue; + } + int st = sp.getSpanStart(spans[i]) - start; int en = sp.getSpanEnd(spans[i]) - start; int fl = sp.getSpanFlags(spans[i]); diff --git a/core/java/android/text/Spanned.java b/core/java/android/text/Spanned.java index bd0a16b7e26fb74e43e5d9156cd45ad1d8240227..154497dc37301100a6aebe338e91f44747d46631 100644 --- a/core/java/android/text/Spanned.java +++ b/core/java/android/text/Spanned.java @@ -105,6 +105,14 @@ extends CharSequence */ public static final int SPAN_COMPOSING = 0x100; + /** + * This flag will be set for intermediate span changes, meaning there + * is guaranteed to be another change following it. Typically it is + * used for {@link Selection} which automatically uses this with the first + * offset it sets when updating the selection. + */ + public static final int SPAN_INTERMEDIATE = 0x200; + /** * The bits numbered SPAN_USER_SHIFT and above are available * for callers to use to store scalar data associated with their diff --git a/core/java/android/text/StaticLayout.java b/core/java/android/text/StaticLayout.java index ceb9f4fab43be89de3da6b134751c006beb0a190..0fef40beb89f9c076aa94a5e2f7575a4b82167a6 100644 --- a/core/java/android/text/StaticLayout.java +++ b/core/java/android/text/StaticLayout.java @@ -576,7 +576,28 @@ extends Layout if (fmbottom > fitbottom) fitbottom = fmbottom; - if (c == ' ' || c == '\t') { + /* + * From the Unicode Line Breaking Algorithm: + * (at least approximately) + * + * .,:; are class IS: breakpoints + * except when adjacent to digits + * / is class SY: a breakpoint + * except when followed by a digit. + * - is class HY: a breakpoint + * except when followed by a digit. + * + * Ideographs are class ID: breakpoints when adjacent. + */ + + if (c == ' ' || c == '\t' || + ((c == '.' || c == ',' || c == ':' || c == ';') && + (j - 1 < here || !Character.isDigit(chs[j - 1 - start])) && + (j + 1 >= next || !Character.isDigit(chs[j + 1 - start]))) || + ((c == '/' || c == '-') && + (j + 1 >= next || !Character.isDigit(chs[j + 1 - start]))) || + (c >= FIRST_CJK && isIdeographic(c) && + j + 1 < next && isIdeographic(chs[j + 1 - start]))) { okwidth = w; ok = j + 1; @@ -592,6 +613,11 @@ extends Layout } else if (breakOnlyAtSpaces) { if (ok != here) { // Log.e("text", "output ok " + here + " to " +ok); + + while (ok < next && chs[ok - start] == ' ') { + ok++; + } + v = out(source, here, ok, okascent, okdescent, oktop, okbottom, @@ -623,6 +649,11 @@ extends Layout } else { if (ok != here) { // Log.e("text", "output ok " + here + " to " +ok); + + while (ok < next && chs[ok - start] == ' ') { + ok++; + } + v = out(source, here, ok, okascent, okdescent, oktop, okbottom, @@ -739,6 +770,51 @@ extends Layout } } + private static final char FIRST_CJK = '\u2E80'; + /** + * Returns true if the specified character is one of those specified + * as being Ideographic (class ID) by the Unicode Line Breaking Algorithm + * (http://www.unicode.org/unicode/reports/tr14/), and is therefore OK + * to break between a pair of. + */ + private static final boolean isIdeographic(char c) { + if (c >= '\u2E80' && c <= '\u2FFF') { + return true; // CJK, KANGXI RADICALS, DESCRIPTION SYMBOLS + } + if (c == '\u3000') { + return true; // IDEOGRAPHIC SPACE + } + if (c >= '\u3040' && c <= '\u309F') { + return true; // Hiragana (except small characters) + } + if (c >= '\u30A0' && c <= '\u30FF') { + return true; // Katakana (except small characters) + } + if (c >= '\u3400' && c <= '\u4DB5') { + return true; // CJK UNIFIED IDEOGRAPHS EXTENSION A + } + if (c >= '\u4E00' && c <= '\u9FBB') { + return true; // CJK UNIFIED IDEOGRAPHS + } + if (c >= '\uF900' && c <= '\uFAD9') { + return true; // CJK COMPATIBILITY IDEOGRAPHS + } + if (c >= '\uA000' && c <= '\uA48F') { + return true; // YI SYLLABLES + } + if (c >= '\uA490' && c <= '\uA4CF') { + return true; // YI RADICALS + } + if (c >= '\uFE62' && c <= '\uFE66') { + return true; // SMALL PLUS SIGN to SMALL EQUALS SIGN + } + if (c >= '\uFF10' && c <= '\uFF19') { + return true; // WIDE DIGITS + } + + return false; + } + /* private static void dump(byte[] data, int count, String label) { if (false) { diff --git a/core/java/android/text/Styled.java b/core/java/android/text/Styled.java index 05c27ea90c5eccf66d60bb6f5a96fec208042467..0aa2004fa258488a64b9442c1a617ce61c14645e 100644 --- a/core/java/android/text/Styled.java +++ b/core/java/android/text/Styled.java @@ -16,25 +16,26 @@ package android.text; -import android.graphics.Paint; import android.graphics.Canvas; -import android.graphics.Path; -import android.graphics.RectF; -import android.graphics.Typeface; -import android.graphics.MaskFilter; -import android.graphics.Rasterizer; -import android.graphics.LayerRasterizer; -import android.text.style.*; - -/* package */ class Styled +import android.graphics.Paint; +import android.text.style.CharacterStyle; +import android.text.style.MetricAffectingSpan; +import android.text.style.ReplacementSpan; + +/** + * This class provides static methods for drawing and measuring styled texts, like + * {@link android.text.Spanned} object with {@link android.text.style.ReplacementSpan}. + * @hide + */ +public class Styled { private static float each(Canvas canvas, Spanned text, int start, int end, int dir, boolean reverse, float x, int top, int y, int bottom, - Paint.FontMetricsInt fm, - TextPaint realPaint, + Paint.FontMetricsInt fmi, TextPaint paint, + TextPaint workPaint, boolean needwid) { boolean havewid = false; @@ -43,9 +44,9 @@ import android.text.style.*; ReplacementSpan replacement = null; - realPaint.bgColor = 0; - realPaint.baselineShift = 0; - paint.set(realPaint); + paint.bgColor = 0; + paint.baselineShift = 0; + workPaint.set(paint); if (spans.length > 0) { for (int i = 0; i < spans.length; i++) { @@ -55,7 +56,7 @@ import android.text.style.*; replacement = (ReplacementSpan)span; } else { - span.updateDrawState(paint); + span.updateDrawState(workPaint); } } } @@ -74,66 +75,66 @@ import android.text.style.*; tmpend = end; } - if (fm != null) { - paint.getFontMetricsInt(fm); + if (fmi != null) { + workPaint.getFontMetricsInt(fmi); } if (canvas != null) { - if (paint.bgColor != 0) { - int c = paint.getColor(); - Paint.Style s = paint.getStyle(); - paint.setColor(paint.bgColor); - paint.setStyle(Paint.Style.FILL); + if (workPaint.bgColor != 0) { + int c = workPaint.getColor(); + Paint.Style s = workPaint.getStyle(); + workPaint.setColor(workPaint.bgColor); + workPaint.setStyle(Paint.Style.FILL); if (!havewid) { - ret = paint.measureText(tmp, tmpstart, tmpend); + ret = workPaint.measureText(tmp, tmpstart, tmpend); havewid = true; } if (dir == Layout.DIR_RIGHT_TO_LEFT) - canvas.drawRect(x - ret, top, x, bottom, paint); + canvas.drawRect(x - ret, top, x, bottom, workPaint); else - canvas.drawRect(x, top, x + ret, bottom, paint); + canvas.drawRect(x, top, x + ret, bottom, workPaint); - paint.setStyle(s); - paint.setColor(c); + workPaint.setStyle(s); + workPaint.setColor(c); } if (dir == Layout.DIR_RIGHT_TO_LEFT) { if (!havewid) { - ret = paint.measureText(tmp, tmpstart, tmpend); + ret = workPaint.measureText(tmp, tmpstart, tmpend); havewid = true; } canvas.drawText(tmp, tmpstart, tmpend, - x - ret, y + paint.baselineShift, paint); + x - ret, y + workPaint.baselineShift, workPaint); } else { if (needwid) { if (!havewid) { - ret = paint.measureText(tmp, tmpstart, tmpend); + ret = workPaint.measureText(tmp, tmpstart, tmpend); havewid = true; } } canvas.drawText(tmp, tmpstart, tmpend, - x, y + paint.baselineShift, paint); + x, y + workPaint.baselineShift, workPaint); } } else { if (needwid && !havewid) { - ret = paint.measureText(tmp, tmpstart, tmpend); + ret = workPaint.measureText(tmp, tmpstart, tmpend); havewid = true; } } } else { - ret = replacement.getSize(paint, text, start, end, fm); + ret = replacement.getSize(workPaint, text, start, end, fmi); if (canvas != null) { if (dir == Layout.DIR_RIGHT_TO_LEFT) replacement.draw(canvas, text, start, end, - x - ret, top, y, bottom, paint); + x - ret, top, y, bottom, workPaint); else replacement.draw(canvas, text, start, end, - x, top, y, bottom, paint); + x, top, y, bottom, workPaint); } } @@ -143,15 +144,29 @@ import android.text.style.*; return ret; } - public static int getTextWidths(TextPaint realPaint, - TextPaint paint, - Spanned text, int start, int end, - float[] widths, Paint.FontMetricsInt fm) { - + /** + * Return the advance widths for the characters in the string. + * See also {@link android.graphics.Paint#getTextWidths(CharSequence, int, int, float[])}. + * + * @param paint The main {@link TextPaint} object. + * @param workPaint The {@link TextPaint} object used for temporal workspace. + * @param text The text to measure + * @param start The index of the first char to to measure + * @param end The end of the text slice to measure + * @param widths Array to receive the advance widths of the characters. + * Must be at least a large as (end - start). + * @param fmi FontMetrics information. Can be null. + * @return The actual number of widths returned. + */ + public static int getTextWidths(TextPaint paint, + TextPaint workPaint, + Spanned text, int start, int end, + float[] widths, Paint.FontMetricsInt fmi) { + // Keep workPaint as is so that developers reuse the workspace. MetricAffectingSpan[] spans = text.getSpans(start, end, MetricAffectingSpan.class); ReplacementSpan replacement = null; - paint.set(realPaint); + workPaint.set(paint); for (int i = 0; i < spans.length; i++) { MetricAffectingSpan span = spans[i]; @@ -159,15 +174,15 @@ import android.text.style.*; replacement = (ReplacementSpan)span; } else { - span.updateMeasureState(paint); + span.updateMeasureState(workPaint); } } if (replacement == null) { - paint.getFontMetricsInt(fm); - paint.getTextWidths(text, start, end, widths); + workPaint.getFontMetricsInt(fmi); + workPaint.getTextWidths(text, start, end, widths); } else { - int wid = replacement.getSize(paint, text, start, end, fm); + int wid = replacement.getSize(workPaint, text, start, end, fmi); if (end > start) { widths[0] = wid; @@ -183,10 +198,10 @@ import android.text.style.*; CharSequence text, int start, int end, int dir, boolean reverse, float x, int top, int y, int bottom, - Paint.FontMetricsInt fm, + Paint.FontMetricsInt fmi, TextPaint paint, TextPaint workPaint, - boolean needwid) { + boolean needWidth) { if (! (text instanceof Spanned)) { float ret = 0; @@ -194,22 +209,22 @@ import android.text.style.*; CharSequence tmp = TextUtils.getReverse(text, start, end); int tmpend = end - start; - if (canvas != null || needwid) + if (canvas != null || needWidth) ret = paint.measureText(tmp, 0, tmpend); if (canvas != null) canvas.drawText(tmp, 0, tmpend, x - ret, y, paint); } else { - if (needwid) + if (needWidth) ret = paint.measureText(text, start, end); if (canvas != null) canvas.drawText(text, start, end, x, y, paint); } - if (fm != null) { - paint.getFontMetricsInt(fm); + if (fmi != null) { + paint.getFontMetricsInt(fmi); } return ret * dir; //Layout.DIR_RIGHT_TO_LEFT == -1 @@ -232,67 +247,129 @@ import android.text.style.*; next = sp.nextSpanTransition(i, end, division); x += each(canvas, sp, i, next, dir, reverse, - x, top, y, bottom, fm, paint, workPaint, - needwid || next != end); - - if (fm != null) { - if (fm.ascent < asc) - asc = fm.ascent; - if (fm.descent > desc) - desc = fm.descent; - - if (fm.top < ftop) - ftop = fm.top; - if (fm.bottom > fbot) - fbot = fm.bottom; + x, top, y, bottom, fmi, paint, workPaint, + needWidth || next != end); + + if (fmi != null) { + if (fmi.ascent < asc) + asc = fmi.ascent; + if (fmi.descent > desc) + desc = fmi.descent; + + if (fmi.top < ftop) + ftop = fmi.top; + if (fmi.bottom > fbot) + fbot = fmi.bottom; } } - if (fm != null) { + if (fmi != null) { if (start == end) { - paint.getFontMetricsInt(fm); + paint.getFontMetricsInt(fmi); } else { - fm.ascent = asc; - fm.descent = desc; - fm.top = ftop; - fm.bottom = fbot; + fmi.ascent = asc; + fmi.descent = desc; + fmi.top = ftop; + fmi.bottom = fbot; } } return x - ox; } - public static float drawText(Canvas canvas, - CharSequence text, int start, int end, - int dir, boolean reverse, - float x, int top, int y, int bottom, - TextPaint paint, - TextPaint workPaint, - boolean needwid) { - if ((dir == Layout.DIR_RIGHT_TO_LEFT && !reverse)||(reverse && dir == Layout.DIR_LEFT_TO_RIGHT)) { + + /* package */ static float drawText(Canvas canvas, + CharSequence text, int start, int end, + int direction, boolean reverse, + float x, int top, int y, int bottom, + TextPaint paint, + TextPaint workPaint, + boolean needWidth) { + if ((direction == Layout.DIR_RIGHT_TO_LEFT && !reverse) || + (reverse && direction == Layout.DIR_LEFT_TO_RIGHT)) { float ch = foreach(null, text, start, end, Layout.DIR_LEFT_TO_RIGHT, false, 0, 0, 0, 0, null, paint, workPaint, true); - ch *= dir; // DIR_RIGHT_TO_LEFT == -1 - foreach(canvas, text, start, end, -dir, + ch *= direction; // DIR_RIGHT_TO_LEFT == -1 + foreach(canvas, text, start, end, -direction, reverse, x + ch, top, y, bottom, null, paint, workPaint, true); return ch; } - return foreach(canvas, text, start, end, dir, reverse, + return foreach(canvas, text, start, end, direction, reverse, x, top, y, bottom, null, paint, workPaint, - needwid); + needWidth); } - + + /** + * Draw the specified range of text, specified by start/end, with its origin at (x,y), + * in the specified Paint. The origin is interpreted based on the Align setting in the + * Paint. + * + * This method considers style information in the text + * (e.g. Even when text is an instance of {@link android.text.Spanned}, this method + * correctly draws the text). + * See also + * {@link android.graphics.Canvas#drawText(CharSequence, int, int, float, float, Paint)} + * and + * {@link android.graphics.Canvas#drawRect(float, float, float, float, Paint)}. + * + * @param canvas The target canvas. + * @param text The text to be drawn + * @param start The index of the first character in text to draw + * @param end (end - 1) is the index of the last character in text to draw + * @param direction The direction of the text. This must be + * {@link android.text.Layout#DIR_LEFT_TO_RIGHT} or + * {@link android.text.Layout#DIR_RIGHT_TO_LEFT}. + * @param x The x-coordinate of origin for where to draw the text + * @param top The top side of the rectangle to be drawn + * @param y The y-coordinate of origin for where to draw the text + * @param bottom The bottom side of the rectangle to be drawn + * @param paint The main {@link TextPaint} object. + * @param workPaint The {@link TextPaint} object used for temporal workspace. + * @param needWidth If true, this method returns the width of drawn text. + * @return Width of the drawn text if needWidth is true. + */ + public static float drawText(Canvas canvas, + CharSequence text, int start, int end, + int direction, + float x, int top, int y, int bottom, + TextPaint paint, + TextPaint workPaint, + boolean needWidth) { + // For safety. + direction = direction >= 0 ? Layout.DIR_LEFT_TO_RIGHT : Layout.DIR_RIGHT_TO_LEFT; + /* + * Hided "reverse" parameter since it is meaningless for external developers. + * Kept workPaint as is so that developers reuse the workspace. + */ + return drawText(canvas, text, start, end, direction, false, + x, top, y, bottom, paint, workPaint, needWidth); + } + + /** + * Return the width of the text, considering style information in the text + * (e.g. Even when text is an instance of {@link android.text.Spanned}, this method + * correctly mesures the width of the text). + * + * @param paint The main {@link TextPaint} object. + * @param workPaint The {@link TextPaint} object used for temporal workspace. + * @param text The text to measure + * @param start The index of the first character to start measuring + * @param end 1 beyond the index of the last character to measure + * @param fmi FontMetrics information. Can be null + * @return The width of the text + */ public static float measureText(TextPaint paint, TextPaint workPaint, CharSequence text, int start, int end, - Paint.FontMetricsInt fm) { + Paint.FontMetricsInt fmi) { + // Keep workPaint as is so that developers reuse the workspace. return foreach(null, text, start, end, Layout.DIR_LEFT_TO_RIGHT, false, - 0, 0, 0, 0, fm, paint, workPaint, true); + 0, 0, 0, 0, fmi, paint, workPaint, true); } } diff --git a/core/java/android/text/TextUtils.java b/core/java/android/text/TextUtils.java index 405d9341181c8e9e9bdc6256007b7f159f2eea8d..5b4c3802b3cebe9e97229736bdb61311b129ce43 100644 --- a/core/java/android/text/TextUtils.java +++ b/core/java/android/text/TextUtils.java @@ -236,6 +236,13 @@ public class TextUtils { return match; } + /** + * Create a new String object containing the given range of characters + * from the source string. This is different than simply calling + * {@link CharSequence#subSequence(int, int) CharSequence.subSequence} + * in that it does not preserve any style runs in the source sequence, + * allowing a more efficient implementation. + */ public static String substring(CharSequence source, int start, int end) { if (source instanceof String) return ((String) source).substring(start, end); @@ -447,13 +454,26 @@ public class TextUtils { /** * Returns true if a and b are equal, including if they are both null. - * + *

            Note: In platform versions 1.1 and earlier, this method only worked well if + * both the arguments were instances of String.

            * @param a first CharSequence to check * @param b second CharSequence to check * @return true if a and b are equal */ public static boolean equals(CharSequence a, CharSequence b) { - return a == b || (a != null && a.equals(b)); + if (a == b) return true; + int length; + if (a != null && b != null && (length = a.length()) == b.length()) { + if (a instanceof String && b instanceof String) { + return a.equals(b); + } else { + for (int i = 0; i < length; i++) { + if (a.charAt(i) != b.charAt(i)) return false; + } + return true; + } + } + return false; } // XXX currently this only reverses chars, not spans @@ -510,24 +530,42 @@ public class TextUtils { private int mEnd; } - private static final int ALIGNMENT_SPAN = 1; - private static final int FOREGROUND_COLOR_SPAN = 2; - private static final int RELATIVE_SIZE_SPAN = 3; - private static final int SCALE_X_SPAN = 4; - private static final int STRIKETHROUGH_SPAN = 5; - private static final int UNDERLINE_SPAN = 6; - private static final int STYLE_SPAN = 7; - private static final int BULLET_SPAN = 8; - private static final int QUOTE_SPAN = 9; - private static final int LEADING_MARGIN_SPAN = 10; - private static final int URL_SPAN = 11; - private static final int BACKGROUND_COLOR_SPAN = 12; - private static final int TYPEFACE_SPAN = 13; - private static final int SUPERSCRIPT_SPAN = 14; - private static final int SUBSCRIPT_SPAN = 15; - private static final int ABSOLUTE_SIZE_SPAN = 16; - private static final int TEXT_APPEARANCE_SPAN = 17; - private static final int ANNOTATION = 18; + /** @hide */ + public static final int ALIGNMENT_SPAN = 1; + /** @hide */ + public static final int FOREGROUND_COLOR_SPAN = 2; + /** @hide */ + public static final int RELATIVE_SIZE_SPAN = 3; + /** @hide */ + public static final int SCALE_X_SPAN = 4; + /** @hide */ + public static final int STRIKETHROUGH_SPAN = 5; + /** @hide */ + public static final int UNDERLINE_SPAN = 6; + /** @hide */ + public static final int STYLE_SPAN = 7; + /** @hide */ + public static final int BULLET_SPAN = 8; + /** @hide */ + public static final int QUOTE_SPAN = 9; + /** @hide */ + public static final int LEADING_MARGIN_SPAN = 10; + /** @hide */ + public static final int URL_SPAN = 11; + /** @hide */ + public static final int BACKGROUND_COLOR_SPAN = 12; + /** @hide */ + public static final int TYPEFACE_SPAN = 13; + /** @hide */ + public static final int SUPERSCRIPT_SPAN = 14; + /** @hide */ + public static final int SUBSCRIPT_SPAN = 15; + /** @hide */ + public static final int ABSOLUTE_SIZE_SPAN = 16; + /** @hide */ + public static final int TEXT_APPEARANCE_SPAN = 17; + /** @hide */ + public static final int ANNOTATION = 18; /** * Flatten a CharSequence and whatever styles can be copied across processes @@ -555,136 +593,10 @@ public class TextUtils { prop = ((CharacterStyle) prop).getUnderlying(); } - if (prop instanceof AlignmentSpan) { - p.writeInt(ALIGNMENT_SPAN); - p.writeString(((AlignmentSpan) prop).getAlignment().name()); - writeWhere(p, sp, o); - } - - if (prop instanceof ForegroundColorSpan) { - p.writeInt(FOREGROUND_COLOR_SPAN); - p.writeInt(((ForegroundColorSpan) prop).getForegroundColor()); - writeWhere(p, sp, o); - } - - if (prop instanceof RelativeSizeSpan) { - p.writeInt(RELATIVE_SIZE_SPAN); - p.writeFloat(((RelativeSizeSpan) prop).getSizeChange()); - writeWhere(p, sp, o); - } - - if (prop instanceof ScaleXSpan) { - p.writeInt(SCALE_X_SPAN); - p.writeFloat(((ScaleXSpan) prop).getScaleX()); - writeWhere(p, sp, o); - } - - if (prop instanceof StrikethroughSpan) { - p.writeInt(STRIKETHROUGH_SPAN); - writeWhere(p, sp, o); - } - - if (prop instanceof UnderlineSpan) { - p.writeInt(UNDERLINE_SPAN); - writeWhere(p, sp, o); - } - - if (prop instanceof StyleSpan) { - p.writeInt(STYLE_SPAN); - p.writeInt(((StyleSpan) prop).getStyle()); - writeWhere(p, sp, o); - } - - if (prop instanceof LeadingMarginSpan) { - if (prop instanceof BulletSpan) { - p.writeInt(BULLET_SPAN); - writeWhere(p, sp, o); - } else if (prop instanceof QuoteSpan) { - p.writeInt(QUOTE_SPAN); - p.writeInt(((QuoteSpan) prop).getColor()); - writeWhere(p, sp, o); - } else { - p.writeInt(LEADING_MARGIN_SPAN); - p.writeInt(((LeadingMarginSpan) prop). - getLeadingMargin(true)); - p.writeInt(((LeadingMarginSpan) prop). - getLeadingMargin(false)); - writeWhere(p, sp, o); - } - } - - if (prop instanceof URLSpan) { - p.writeInt(URL_SPAN); - p.writeString(((URLSpan) prop).getURL()); - writeWhere(p, sp, o); - } - - if (prop instanceof BackgroundColorSpan) { - p.writeInt(BACKGROUND_COLOR_SPAN); - p.writeInt(((BackgroundColorSpan) prop).getBackgroundColor()); - writeWhere(p, sp, o); - } - - if (prop instanceof TypefaceSpan) { - p.writeInt(TYPEFACE_SPAN); - p.writeString(((TypefaceSpan) prop).getFamily()); - writeWhere(p, sp, o); - } - - if (prop instanceof SuperscriptSpan) { - p.writeInt(SUPERSCRIPT_SPAN); - writeWhere(p, sp, o); - } - - if (prop instanceof SubscriptSpan) { - p.writeInt(SUBSCRIPT_SPAN); - writeWhere(p, sp, o); - } - - if (prop instanceof AbsoluteSizeSpan) { - p.writeInt(ABSOLUTE_SIZE_SPAN); - p.writeInt(((AbsoluteSizeSpan) prop).getSize()); - writeWhere(p, sp, o); - } - - if (prop instanceof TextAppearanceSpan) { - TextAppearanceSpan tas = (TextAppearanceSpan) prop; - p.writeInt(TEXT_APPEARANCE_SPAN); - - String tf = tas.getFamily(); - if (tf != null) { - p.writeInt(1); - p.writeString(tf); - } else { - p.writeInt(0); - } - - p.writeInt(tas.getTextStyle()); - p.writeInt(tas.getTextSize()); - - ColorStateList csl = tas.getTextColor(); - if (csl == null) { - p.writeInt(0); - } else { - p.writeInt(1); - csl.writeToParcel(p, parcelableFlags); - } - - csl = tas.getLinkTextColor(); - if (csl == null) { - p.writeInt(0); - } else { - p.writeInt(1); - csl.writeToParcel(p, parcelableFlags); - } - - writeWhere(p, sp, o); - } - - if (prop instanceof Annotation) { - p.writeInt(ANNOTATION); - p.writeString(((Annotation) prop).getKey()); - p.writeString(((Annotation) prop).getValue()); + if (prop instanceof ParcelableSpan) { + ParcelableSpan ps = (ParcelableSpan)prop; + p.writeInt(ps.getSpanTypeId()); + ps.writeToParcel(p, parcelableFlags); writeWhere(p, sp, o); } } @@ -707,8 +619,7 @@ public class TextUtils { } public static final Parcelable.Creator CHAR_SEQUENCE_CREATOR - = new Parcelable.Creator() - { + = new Parcelable.Creator() { /** * Read and return a new CharSequence, possibly with styles, * from the parcel. @@ -729,89 +640,75 @@ public class TextUtils { switch (kind) { case ALIGNMENT_SPAN: - readSpan(p, sp, new AlignmentSpan.Standard( - Layout.Alignment.valueOf(p.readString()))); + readSpan(p, sp, new AlignmentSpan.Standard(p)); break; case FOREGROUND_COLOR_SPAN: - readSpan(p, sp, new ForegroundColorSpan(p.readInt())); + readSpan(p, sp, new ForegroundColorSpan(p)); break; case RELATIVE_SIZE_SPAN: - readSpan(p, sp, new RelativeSizeSpan(p.readFloat())); + readSpan(p, sp, new RelativeSizeSpan(p)); break; case SCALE_X_SPAN: - readSpan(p, sp, new ScaleXSpan(p.readFloat())); + readSpan(p, sp, new ScaleXSpan(p)); break; case STRIKETHROUGH_SPAN: - readSpan(p, sp, new StrikethroughSpan()); + readSpan(p, sp, new StrikethroughSpan(p)); break; case UNDERLINE_SPAN: - readSpan(p, sp, new UnderlineSpan()); + readSpan(p, sp, new UnderlineSpan(p)); break; case STYLE_SPAN: - readSpan(p, sp, new StyleSpan(p.readInt())); + readSpan(p, sp, new StyleSpan(p)); break; case BULLET_SPAN: - readSpan(p, sp, new BulletSpan()); + readSpan(p, sp, new BulletSpan(p)); break; case QUOTE_SPAN: - readSpan(p, sp, new QuoteSpan(p.readInt())); + readSpan(p, sp, new QuoteSpan(p)); break; case LEADING_MARGIN_SPAN: - readSpan(p, sp, new LeadingMarginSpan.Standard(p.readInt(), - p.readInt())); + readSpan(p, sp, new LeadingMarginSpan.Standard(p)); break; case URL_SPAN: - readSpan(p, sp, new URLSpan(p.readString())); + readSpan(p, sp, new URLSpan(p)); break; case BACKGROUND_COLOR_SPAN: - readSpan(p, sp, new BackgroundColorSpan(p.readInt())); + readSpan(p, sp, new BackgroundColorSpan(p)); break; case TYPEFACE_SPAN: - readSpan(p, sp, new TypefaceSpan(p.readString())); + readSpan(p, sp, new TypefaceSpan(p)); break; case SUPERSCRIPT_SPAN: - readSpan(p, sp, new SuperscriptSpan()); + readSpan(p, sp, new SuperscriptSpan(p)); break; case SUBSCRIPT_SPAN: - readSpan(p, sp, new SubscriptSpan()); + readSpan(p, sp, new SubscriptSpan(p)); break; case ABSOLUTE_SIZE_SPAN: - readSpan(p, sp, new AbsoluteSizeSpan(p.readInt())); + readSpan(p, sp, new AbsoluteSizeSpan(p)); break; case TEXT_APPEARANCE_SPAN: - readSpan(p, sp, new TextAppearanceSpan( - p.readInt() != 0 - ? p.readString() - : null, - p.readInt(), // style - p.readInt(), // size - p.readInt() != 0 - ? ColorStateList.CREATOR.createFromParcel(p) - : null, - p.readInt() != 0 - ? ColorStateList.CREATOR.createFromParcel(p) - : null)); + readSpan(p, sp, new TextAppearanceSpan(p)); break; case ANNOTATION: - readSpan(p, sp, - new Annotation(p.readString(), p.readString())); + readSpan(p, sp, new Annotation(p)); break; default: diff --git a/core/java/android/text/TextWatcher.java b/core/java/android/text/TextWatcher.java index 7456b28d6ede59f66d57875128a7bc87d3aa04a4..bad09f2a0f0eed1d4c5e95f164e6cba23c403247 100644 --- a/core/java/android/text/TextWatcher.java +++ b/core/java/android/text/TextWatcher.java @@ -20,7 +20,7 @@ package android.text; * When an object of a type is attached to an Editable, its methods will * be called when the text is changed. */ -public interface TextWatcher { +public interface TextWatcher extends NoCopySpan { /** * This method is called to notify you that, within s, * the count characters beginning at start diff --git a/core/java/android/text/format/DateFormat.java b/core/java/android/text/format/DateFormat.java index 73adedf4229ae3d06ebff78b194345884c51b43c..0dc96c369b7802154d917419e50b1428558bd491 100644 --- a/core/java/android/text/format/DateFormat.java +++ b/core/java/android/text/format/DateFormat.java @@ -27,6 +27,7 @@ import com.android.internal.R; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; +import java.util.Locale; import java.util.TimeZone; import java.text.SimpleDateFormat; @@ -188,6 +189,12 @@ public class DateFormat { */ public static final char YEAR = 'y'; + + private static final Object sLocaleLock = new Object(); + private static Locale sIs24HourLocale; + private static boolean sIs24Hour; + + /** * Returns true if user preference is set to 24-hour format. * @param context the context to use for the content resolver @@ -198,20 +205,34 @@ public class DateFormat { Settings.System.TIME_12_24); if (value == null) { + Locale locale = context.getResources().getConfiguration().locale; + + synchronized (sLocaleLock) { + if (sIs24HourLocale != null && sIs24HourLocale.equals(locale)) { + return sIs24Hour; + } + } + java.text.DateFormat natural = java.text.DateFormat.getTimeInstance( - java.text.DateFormat.LONG, - context.getResources().getConfiguration().locale); + java.text.DateFormat.LONG, locale); if (natural instanceof SimpleDateFormat) { SimpleDateFormat sdf = (SimpleDateFormat) natural; String pattern = sdf.toPattern(); if (pattern.indexOf('H') >= 0) { - return true; + value = "24"; } else { - return false; + value = "12"; } + } else { + value = "12"; + } + + synchronized (sLocaleLock) { + sIs24HourLocale = locale; + sIs24Hour = !value.equals("12"); } } diff --git a/core/java/android/text/format/DateUtils.java b/core/java/android/text/format/DateUtils.java index feae6cf52a6f5d7301b9dae47d117af243a4724c..8a7cdd92950f115d896204ea19a2efb3b35d822a 100644 --- a/core/java/android/text/format/DateUtils.java +++ b/core/java/android/text/format/DateUtils.java @@ -595,6 +595,17 @@ public class DateUtils * @param elapsedSeconds the elapsed time in seconds. */ public static String formatElapsedTime(long elapsedSeconds) { + return formatElapsedTime(null, elapsedSeconds); + } + + /** + * Formats an elapsed time in the form "MM:SS" or "H:MM:SS" + * for display on the call-in-progress screen. + * + * @param recycle {@link StringBuilder} to recycle, if possible + * @param elapsedSeconds the elapsed time in seconds. + */ + public static String formatElapsedTime(StringBuilder recycle, long elapsedSeconds) { initFormatStrings(); long hours = 0; @@ -613,18 +624,24 @@ public class DateUtils String result; if (hours > 0) { - return formatElapsedTime(sElapsedFormatHMMSS, hours, minutes, seconds); + return formatElapsedTime(recycle, sElapsedFormatHMMSS, hours, minutes, seconds); } else { - return formatElapsedTime(sElapsedFormatMMSS, minutes, seconds); + return formatElapsedTime(recycle, sElapsedFormatMMSS, minutes, seconds); } } /** * Fast formatting of h:mm:ss */ - private static String formatElapsedTime(String format, long hours, long minutes, long seconds) { + private static String formatElapsedTime(StringBuilder recycle, String format, long hours, + long minutes, long seconds) { if (FAST_FORMAT_HMMSS.equals(format)) { - StringBuffer sb = new StringBuffer(16); + StringBuilder sb = recycle; + if (sb == null) { + sb = new StringBuilder(8); + } else { + sb.setLength(0); + } sb.append(hours); sb.append(TIME_SEPARATOR); if (minutes < 10) { @@ -649,9 +666,15 @@ public class DateUtils /** * Fast formatting of m:ss */ - private static String formatElapsedTime(String format, long minutes, long seconds) { + private static String formatElapsedTime(StringBuilder recycle, String format, long minutes, + long seconds) { if (FAST_FORMAT_MMSS.equals(format)) { - StringBuffer sb = new StringBuffer(16); + StringBuilder sb = recycle; + if (sb == null) { + sb = new StringBuilder(8); + } else { + sb.setLength(0); + } if (minutes < 10) { sb.append(TIME_PADDING); } else { @@ -1028,8 +1051,9 @@ public class DateUtils * If FORMAT_NO_YEAR is set, then the year is not shown. * If neither FORMAT_SHOW_YEAR nor FORMAT_NO_YEAR are set, then the year * is shown only if it is different from the current year, or if the start - * and end dates fall on different years. - * + * and end dates fall on different years. If both are set, + * FORMAT_SHOW_YEAR takes precedence. + * *

            * Normally the date is shown unless the start and end day are the same. * If FORMAT_SHOW_DATE is set, then the date is always shown, even for @@ -1120,24 +1144,28 @@ public class DateUtils boolean abbrevMonth = (flags & (FORMAT_ABBREV_MONTH | FORMAT_ABBREV_ALL)) != 0; boolean noMonthDay = (flags & FORMAT_NO_MONTH_DAY) != 0; boolean numericDate = (flags & FORMAT_NUMERIC_DATE) != 0; - - Time startDate; + + // If we're getting called with a single instant in time (from + // e.g. formatDateTime(), below), then we can skip a lot of + // computation below that'd otherwise be thrown out. + boolean isInstant = (startMillis == endMillis); + + Time startDate = useUTC ? new Time(Time.TIMEZONE_UTC) : new Time(); + startDate.set(startMillis); + Time endDate; - - if (useUTC) { - startDate = new Time(Time.TIMEZONE_UTC); - endDate = new Time(Time.TIMEZONE_UTC); + int dayDistance; + if (isInstant) { + endDate = startDate; + dayDistance = 0; } else { - startDate = new Time(); - endDate = new Time(); + endDate = useUTC ? new Time(Time.TIMEZONE_UTC) : new Time(); + endDate.set(endMillis); + int startJulianDay = Time.getJulianDay(startMillis, startDate.gmtoff); + int endJulianDay = Time.getJulianDay(endMillis, endDate.gmtoff); + dayDistance = endJulianDay - startJulianDay; } - - startDate.set(startMillis); - endDate.set(endMillis); - int startJulianDay = Time.getJulianDay(startMillis, startDate.gmtoff); - int endJulianDay = Time.getJulianDay(endMillis, endDate.gmtoff); - int dayDistance = endJulianDay - startJulianDay; - + // If the end date ends at 12am at the beginning of a day, // then modify it to make it look like it ends at midnight on // the previous day. This will allow us to display "8pm - midnight", @@ -1152,20 +1180,21 @@ public class DateUtils // and an end date of Nov 12 at 00:00. // If the start and end time are the same, then skip this and don't // adjust the date. - if ((endDate.hour | endDate.minute | endDate.second) == 0 - && (!showTime || dayDistance <= 1) && (startMillis != endMillis)) { + if (!isInstant + && (endDate.hour | endDate.minute | endDate.second) == 0 + && (!showTime || dayDistance <= 1)) { endDate.monthDay -= 1; endDate.normalize(true /* ignore isDst */); } - + int startDay = startDate.monthDay; int startMonthNum = startDate.month; int startYear = startDate.year; - + int endDay = endDate.monthDay; int endMonthNum = endDate.month; int endYear = endDate.year; - + String startWeekDayString = ""; String endWeekDayString = ""; if (showWeekDay) { @@ -1176,9 +1205,9 @@ public class DateUtils weekDayFormat = WEEKDAY_FORMAT; } startWeekDayString = startDate.format(weekDayFormat); - endWeekDayString = endDate.format(weekDayFormat); + endWeekDayString = isInstant ? startWeekDayString : endDate.format(weekDayFormat); } - + String startTimeString = ""; String endTimeString = ""; if (showTime) { @@ -1204,7 +1233,7 @@ public class DateUtils boolean capNoon = (flags & FORMAT_CAP_NOON) != 0; boolean noMidnight = (flags & FORMAT_NO_MIDNIGHT) != 0; boolean capMidnight = (flags & FORMAT_CAP_MIDNIGHT) != 0; - + boolean startOnTheHour = startDate.minute == 0 && startDate.second == 0; boolean endOnTheHour = endDate.minute == 0 && endDate.second == 0; if (abbrevTime && startOnTheHour) { @@ -1220,20 +1249,41 @@ public class DateUtils startTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm); } } - if (abbrevTime && endOnTheHour) { - if (capAMPM) { - endTimeFormat = res.getString(com.android.internal.R.string.hour_cap_ampm); + + // Don't waste time on setting endTimeFormat when + // we're dealing with an instant, where we'll never + // need the end point. (It's the same as the start + // point) + if (!isInstant) { + if (abbrevTime && endOnTheHour) { + if (capAMPM) { + endTimeFormat = res.getString(com.android.internal.R.string.hour_cap_ampm); + } else { + endTimeFormat = res.getString(com.android.internal.R.string.hour_ampm); + } } else { - endTimeFormat = res.getString(com.android.internal.R.string.hour_ampm); + if (capAMPM) { + endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_cap_ampm); + } else { + endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm); + } } - } else { - if (capAMPM) { - endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_cap_ampm); - } else { - endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm); + + if (endDate.hour == 12 && endOnTheHour && !noNoon) { + if (capNoon) { + endTimeFormat = res.getString(com.android.internal.R.string.Noon); + } else { + endTimeFormat = res.getString(com.android.internal.R.string.noon); + } + } else if (endDate.hour == 0 && endOnTheHour && !noMidnight) { + if (capMidnight) { + endTimeFormat = res.getString(com.android.internal.R.string.Midnight); + } else { + endTimeFormat = res.getString(com.android.internal.R.string.midnight); + } } } - + if (startDate.hour == 12 && startOnTheHour && !noNoon) { if (capNoon) { startTimeFormat = res.getString(com.android.internal.R.string.Noon); @@ -1243,37 +1293,32 @@ public class DateUtils // Don't show the start time starting at midnight. Show // 12am instead. } - - if (endDate.hour == 12 && endOnTheHour && !noNoon) { - if (capNoon) { - endTimeFormat = res.getString(com.android.internal.R.string.Noon); - } else { - endTimeFormat = res.getString(com.android.internal.R.string.noon); - } - } else if (endDate.hour == 0 && endOnTheHour && !noMidnight) { - if (capMidnight) { - endTimeFormat = res.getString(com.android.internal.R.string.Midnight); - } else { - endTimeFormat = res.getString(com.android.internal.R.string.midnight); - } - } } + startTimeString = startDate.format(startTimeFormat); - endTimeString = endDate.format(endTimeFormat); + endTimeString = isInstant ? startTimeString : endDate.format(endTimeFormat); } - - // Get the current year - long millis = System.currentTimeMillis(); - Time time = new Time(); - time.set(millis); - int currentYear = time.year; - + // Show the year if the user specified FORMAT_SHOW_YEAR or if // the starting and end years are different from each other // or from the current year. But don't show the year if the - // user specified FORMAT_NO_YEAR; - showYear = showYear || (!noYear && (startYear != endYear || startYear != currentYear)); - + // user specified FORMAT_NO_YEAR. + if (showYear) { + // No code... just a comment for clarity. Keep showYear + // on, as they enabled it with FORMAT_SHOW_YEAR. This + // takes precedence over them setting FORMAT_NO_YEAR. + } else if (noYear) { + // They explicitly didn't want a year. + showYear = false; + } else if (startYear != endYear) { + showYear = true; + } else { + // Show the year if it's not equal to the current year. + Time currentTime = new Time(); + currentTime.setToNow(); + showYear = startYear != currentTime.year; + } + String defaultDateFormat, fullFormat, dateRange; if (numericDate) { defaultDateFormat = res.getString(com.android.internal.R.string.numeric_date); @@ -1306,7 +1351,7 @@ public class DateUtils } } } - + if (showWeekDay) { if (showTime) { fullFormat = res.getString(com.android.internal.R.string.wday1_date1_time1_wday2_date2_time2); @@ -1320,20 +1365,20 @@ public class DateUtils fullFormat = res.getString(com.android.internal.R.string.date1_date2); } } - + if (noMonthDay && startMonthNum == endMonthNum) { // Example: "January, 2008" String startDateString = startDate.format(defaultDateFormat); return startDateString; } - + if (startYear != endYear || noMonthDay) { // Different year or we are not showing the month day number. // Example: "December 31, 2007 - January 1, 2008" // Or: "January - February, 2008" String startDateString = startDate.format(defaultDateFormat); String endDateString = endDate.format(defaultDateFormat); - + // The values that are used in a fullFormat string are specified // by position. dateRange = String.format(fullFormat, @@ -1341,7 +1386,7 @@ public class DateUtils endWeekDayString, endDateString, endTimeString); return dateRange; } - + // Get the month, day, and year strings for the start and end dates String monthFormat; if (numericDate) { @@ -1354,16 +1399,17 @@ public class DateUtils String startMonthString = startDate.format(monthFormat); String startMonthDayString = startDate.format(MONTH_DAY_FORMAT); String startYearString = startDate.format(YEAR_FORMAT); - String endMonthString = endDate.format(monthFormat); - String endMonthDayString = endDate.format(MONTH_DAY_FORMAT); - String endYearString = endDate.format(YEAR_FORMAT); - + + String endMonthString = isInstant ? null : endDate.format(monthFormat); + String endMonthDayString = isInstant ? null : endDate.format(MONTH_DAY_FORMAT); + String endYearString = isInstant ? null : endDate.format(YEAR_FORMAT); + if (startMonthNum != endMonthNum) { // Same year, different month. // Example: "October 28 - November 3" // or: "Wed, Oct 31 - Sat, Nov 3, 2007" // or: "Oct 31, 8am - Sat, Nov 3, 2007, 5pm" - + int index = 0; if (showWeekDay) index = 1; if (showYear) index += 2; @@ -1371,7 +1417,7 @@ public class DateUtils if (numericDate) index += 8; int resId = sameYearTable[index]; fullFormat = res.getString(resId); - + // The values that are used in a fullFormat string are specified // by position. dateRange = String.format(fullFormat, @@ -1381,7 +1427,7 @@ public class DateUtils endYearString, endTimeString); return dateRange; } - + if (startDay != endDay) { // Same month, different day. int index = 0; @@ -1391,7 +1437,7 @@ public class DateUtils if (numericDate) index += 8; int resId = sameMonthTable[index]; fullFormat = res.getString(resId); - + // The values that are used in a fullFormat string are specified // by position. dateRange = String.format(fullFormat, @@ -1401,19 +1447,19 @@ public class DateUtils endYearString, endTimeString); return dateRange; } - + // Same start and end day boolean showDate = (flags & FORMAT_SHOW_DATE) != 0; - + // If nothing was specified, then show the date. if (!showTime && !showDate && !showWeekDay) showDate = true; - + // Compute the time string (example: "10:00 - 11:00 am") String timeString = ""; if (showTime) { // If the start and end time are the same, then just show the // start time. - if (startMillis == endMillis) { + if (isInstant) { // Same start and end time. // Example: "10:15 AM" timeString = startTimeString; @@ -1423,7 +1469,7 @@ public class DateUtils timeString = String.format(timeFormat, startTimeString, endTimeString); } } - + // Figure out which full format to use. fullFormat = ""; String dateString = ""; @@ -1457,7 +1503,7 @@ public class DateUtils } else if (showTime) { return timeString; } - + // The values that are used in a fullFormat string are specified // by position. dateRange = String.format(fullFormat, timeString, startWeekDayString, dateString); diff --git a/core/java/android/text/format/Time.java b/core/java/android/text/format/Time.java index 5bf9b205a6c68580f520bcfc3ad37dc5fbdf68e6..daa99c250bfa413fab762d2470d3d60ffa2ef8d5 100644 --- a/core/java/android/text/format/Time.java +++ b/core/java/android/text/format/Time.java @@ -394,6 +394,7 @@ public class Time { * * @param s the string to parse * @return true if the resulting time value is in UTC time + * @throws android.util.TimeFormatException if s cannot be parsed. */ public boolean parse(String s) { if (nativeParse(s)) { diff --git a/core/java/android/text/method/ArrowKeyMovementMethod.java b/core/java/android/text/method/ArrowKeyMovementMethod.java index 7457439a6a8c6d954d4eb87329683428cdae5d0d..17c7a6cd8c880cc538f2c69afc18d968fb99adcb 100644 --- a/core/java/android/text/method/ArrowKeyMovementMethod.java +++ b/core/java/android/text/method/ArrowKeyMovementMethod.java @@ -16,6 +16,7 @@ package android.text.method; +import android.util.Log; import android.view.KeyEvent; import android.text.*; import android.widget.TextView; @@ -131,6 +132,16 @@ implements MovementMethod } public boolean onKeyDown(TextView widget, Spannable buffer, int keyCode, KeyEvent event) { + if (executeDown(widget, buffer, keyCode)) { + MetaKeyKeyListener.adjustMetaAfterKeypress(buffer); + MetaKeyKeyListener.resetLockedMeta(buffer); + return true; + } + + return false; + } + + private boolean executeDown(TextView widget, Spannable buffer, int keyCode) { boolean handled = false; switch (keyCode) { @@ -170,6 +181,20 @@ implements MovementMethod return false; } + public boolean onKeyOther(TextView view, Spannable text, KeyEvent event) { + int code = event.getKeyCode(); + if (code != KeyEvent.KEYCODE_UNKNOWN + && event.getAction() == KeyEvent.ACTION_MULTIPLE) { + int repeat = event.getRepeatCount(); + boolean handled = false; + while ((--repeat) > 0) { + handled |= executeDown(view, text, code); + } + return handled; + } + return false; + } + public boolean onTrackballEvent(TextView widget, Spannable text, MotionEvent event) { return false; @@ -179,7 +204,7 @@ implements MovementMethod MotionEvent event) { boolean handled = Touch.onTouchEvent(widget, buffer, event); - if (widget.isFocused()) { + if (widget.isFocused() && !widget.didTouchFocusSelect()) { if (event.getAction() == MotionEvent.ACTION_UP) { int x = (int) event.getX(); int y = (int) event.getY(); diff --git a/core/java/android/text/method/BaseKeyListener.java b/core/java/android/text/method/BaseKeyListener.java index a875368834490469bd33d0757210588dfb2121bc..6df6a3ae7ab3b4121b9d30477972a83949e7871a 100644 --- a/core/java/android/text/method/BaseKeyListener.java +++ b/core/java/android/text/method/BaseKeyListener.java @@ -18,7 +18,6 @@ package android.text.method; import android.view.KeyEvent; import android.view.View; -import android.text.InputType; import android.text.*; import android.text.method.TextKeyListener.Capitalize; import android.widget.TextView; @@ -26,7 +25,7 @@ import android.widget.TextView; public abstract class BaseKeyListener extends MetaKeyKeyListener implements KeyListener { - /* package */ static final Object OLD_SEL_START = new Object(); + /* package */ static final Object OLD_SEL_START = new NoCopySpan.Concrete(); /** * Performs the action that happens when you press the DEL key in @@ -127,5 +126,35 @@ implements KeyListener { return super.onKeyDown(view, content, keyCode, event); } + + /** + * Base implementation handles ACTION_MULTIPLE KEYCODE_UNKNOWN by inserting + * the event's text into the content. + */ + public boolean onKeyOther(View view, Editable content, KeyEvent event) { + if (event.getAction() != KeyEvent.ACTION_MULTIPLE + || event.getKeyCode() != KeyEvent.KEYCODE_UNKNOWN) { + // Not something we are interested in. + return false; + } + + int selStart, selEnd; + + { + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + selStart = Math.min(a, b); + selEnd = Math.max(a, b); + } + + CharSequence text = event.getCharacters(); + if (text == null) { + return false; + } + + content.replace(selStart, selEnd, text); + return true; + } } diff --git a/core/java/android/text/method/KeyListener.java b/core/java/android/text/method/KeyListener.java index 4ae6191ef69e857fc95f04d274b2b04c0e5199f8..85948523a009507cc3effb7428ab4855ec8e4330 100644 --- a/core/java/android/text/method/KeyListener.java +++ b/core/java/android/text/method/KeyListener.java @@ -65,6 +65,13 @@ public interface KeyListener { public boolean onKeyUp(View view, Editable text, int keyCode, KeyEvent event); + /** + * If the key listener wants to other kinds of key events, return true, + * otherwise return false and the caller (i.e. the widget host) + * will handle the key. + */ + public boolean onKeyOther(View view, Editable text, KeyEvent event); + /** * Remove the given shift states from the edited text. */ diff --git a/core/java/android/text/method/LinkMovementMethod.java b/core/java/android/text/method/LinkMovementMethod.java index 92ac531ce8c74778c15f8dfdc9995b010249757f..22e9cc6d1bd1502826e56c2a812b4deae7eb5902 100644 --- a/core/java/android/text/method/LinkMovementMethod.java +++ b/core/java/android/text/method/LinkMovementMethod.java @@ -252,5 +252,5 @@ extends ScrollingMovementMethod } private static LinkMovementMethod sInstance; - private static Object FROM_BELOW = new Object(); + private static Object FROM_BELOW = new NoCopySpan.Concrete(); } diff --git a/core/java/android/text/method/MetaKeyKeyListener.java b/core/java/android/text/method/MetaKeyKeyListener.java index d5a473b0d6d92448950899f5a1395d6d2867a12c..61ec67fce237cf62fc5863941b0e5c21d8f718bf 100644 --- a/core/java/android/text/method/MetaKeyKeyListener.java +++ b/core/java/android/text/method/MetaKeyKeyListener.java @@ -71,10 +71,10 @@ public abstract class MetaKeyKeyListener { | META_SYM_LOCKED | META_SYM_USED | META_SYM_PRESSED | META_SYM_RELEASED; - private static final Object CAP = new Object(); - private static final Object ALT = new Object(); - private static final Object SYM = new Object(); - private static final Object SELECTING = new Object(); + private static final Object CAP = new NoCopySpan.Concrete(); + private static final Object ALT = new NoCopySpan.Concrete(); + private static final Object SYM = new NoCopySpan.Concrete(); + private static final Object SELECTING = new NoCopySpan.Concrete(); /** * Resets all meta state to inactive. @@ -159,13 +159,21 @@ public abstract class MetaKeyKeyListener { /** * Returns true if this object is one that this class would use to - * keep track of meta state in the specified text. + * keep track of any meta state in the specified text. */ public static boolean isMetaTracker(CharSequence text, Object what) { return what == CAP || what == ALT || what == SYM || what == SELECTING; } + /** + * Returns true if this object is one that this class would use to + * keep track of the selecting meta state in the specified text. + */ + public static boolean isSelectingMetaTracker(CharSequence text, Object what) { + return what == SELECTING; + } + private static void adjust(Spannable content, Object what) { int current = content.getSpanFlags(what); @@ -283,10 +291,14 @@ public abstract class MetaKeyKeyListener { } public void clearMetaKeyState(View view, Editable content, int states) { - if ((states&META_SHIFT_ON) != 0) resetLock(content, CAP); - if ((states&META_ALT_ON) != 0) resetLock(content, ALT); - if ((states&META_SYM_ON) != 0) resetLock(content, SYM); - if ((states&META_SELECTING) != 0) resetLock(content, SELECTING); + clearMetaKeyState(content, states); + } + + public static void clearMetaKeyState(Editable content, int states) { + if ((states&META_SHIFT_ON) != 0) content.removeSpan(CAP); + if ((states&META_ALT_ON) != 0) content.removeSpan(ALT); + if ((states&META_SYM_ON) != 0) content.removeSpan(SYM); + if ((states&META_SELECTING) != 0) content.removeSpan(SELECTING); } /** diff --git a/core/java/android/text/method/MovementMethod.java b/core/java/android/text/method/MovementMethod.java index 9e37e59a2defcdd629dcabd23e8d8d58f06b8a70..29f67a1ac44492eb474425a9cd4fe682f1194e29 100644 --- a/core/java/android/text/method/MovementMethod.java +++ b/core/java/android/text/method/MovementMethod.java @@ -26,6 +26,14 @@ public interface MovementMethod public void initialize(TextView widget, Spannable text); public boolean onKeyDown(TextView widget, Spannable text, int keyCode, KeyEvent event); public boolean onKeyUp(TextView widget, Spannable text, int keyCode, KeyEvent event); + + /** + * If the key listener wants to other kinds of key events, return true, + * otherwise return false and the caller (i.e. the widget host) + * will handle the key. + */ + public boolean onKeyOther(TextView view, Spannable text, KeyEvent event); + public void onTakeFocus(TextView widget, Spannable text, int direction); public boolean onTrackballEvent(TextView widget, Spannable text, MotionEvent event); diff --git a/core/java/android/text/method/NumberKeyListener.java b/core/java/android/text/method/NumberKeyListener.java index 348b658ebe7e7267679c6bd01cf4855a6938f51e..9270ca58e4a6b765c77e6841593d41adab69c74f 100644 --- a/core/java/android/text/method/NumberKeyListener.java +++ b/core/java/android/text/method/NumberKeyListener.java @@ -24,7 +24,6 @@ import android.text.Selection; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; -import android.util.SparseIntArray; /** * For numeric text entry @@ -102,6 +101,11 @@ public abstract class NumberKeyListener extends BaseKeyListener selEnd = Math.max(a, b); } + if (selStart < 0 || selEnd < 0) { + selStart = selEnd = 0; + Selection.setSelection(content, 0); + } + int i = event != null ? lookup(event, content) : 0; int repeatCount = event != null ? event.getRepeatCount() : 0; if (repeatCount == 0) { diff --git a/core/java/android/text/method/PasswordTransformationMethod.java b/core/java/android/text/method/PasswordTransformationMethod.java index edaa836d6954aabb369e493173b5802fd3560ff0..fad4f64ffe1ea84ba3bbe0451656cadfeb79a082 100644 --- a/core/java/android/text/method/PasswordTransformationMethod.java +++ b/core/java/android/text/method/PasswordTransformationMethod.java @@ -22,6 +22,7 @@ import android.graphics.Rect; import android.view.View; import android.text.Editable; import android.text.GetChars; +import android.text.NoCopySpan; import android.text.TextUtils; import android.text.TextWatcher; import android.text.Selection; @@ -104,8 +105,10 @@ implements TransformationMethod, TextWatcher sp.removeSpan(old[i]); } - sp.setSpan(new Visible(sp, this), start, start + count, - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + if (count == 1) { + sp.setSpan(new Visible(sp, this), start, start + count, + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } } } } @@ -249,7 +252,8 @@ implements TransformationMethod, TextWatcher * Used to stash a reference back to the View in the Editable so we * can use it to check the settings. */ - private static class ViewReference extends WeakReference { + private static class ViewReference extends WeakReference + implements NoCopySpan { public ViewReference(View v) { super(v); } diff --git a/core/java/android/text/method/QwertyKeyListener.java b/core/java/android/text/method/QwertyKeyListener.java index 863b2e2deacdd488c473f29c5d7862f0b28a3a5b..21bc2a6311b6431298dbaa95ac605ee80b9cdb8c 100644 --- a/core/java/android/text/method/QwertyKeyListener.java +++ b/core/java/android/text/method/QwertyKeyListener.java @@ -16,18 +16,12 @@ package android.text.method; -import android.os.Message; -import android.os.Handler; import android.text.*; import android.text.method.TextKeyListener.Capitalize; import android.util.SparseArray; -import android.util.SparseIntArray; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; -import android.widget.TextView; - -import java.util.HashMap; /** * This is the standard key listener for alphabetic input on qwerty @@ -302,21 +296,30 @@ public class QwertyKeyListener extends BaseKeyListener { String old = new String(repl[0].mText); content.removeSpan(repl[0]); - content.setSpan(TextKeyListener.INHIBIT_REPLACEMENT, - en, en, Spannable.SPAN_POINT_POINT); - content.replace(st, en, old); - en = content.getSpanStart(TextKeyListener.INHIBIT_REPLACEMENT); - if (en - 1 >= 0) { + // only cancel the autocomplete if the cursor is at the end of + // the replaced span (or after it, because the user is + // backspacing over the space after the word, not the word + // itself). + if (selStart >= en) { content.setSpan(TextKeyListener.INHIBIT_REPLACEMENT, - en - 1, en, - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + en, en, Spannable.SPAN_POINT_POINT); + content.replace(st, en, old); + + en = content.getSpanStart(TextKeyListener.INHIBIT_REPLACEMENT); + if (en - 1 >= 0) { + content.setSpan(TextKeyListener.INHIBIT_REPLACEMENT, + en - 1, en, + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } else { + content.removeSpan(TextKeyListener.INHIBIT_REPLACEMENT); + } + adjustMetaAfterKeypress(content); } else { - content.removeSpan(TextKeyListener.INHIBIT_REPLACEMENT); + adjustMetaAfterKeypress(content); + return super.onKeyDown(view, content, keyCode, event); } - adjustMetaAfterKeypress(content); - return true; } } @@ -442,7 +445,7 @@ public class QwertyKeyListener extends BaseKeyListener { return Character.toUpperCase(src.charAt(0)) + src.substring(1); } - /* package */ static class Replaced + /* package */ static class Replaced implements NoCopySpan { public Replaced(char[] text) { mText = text; diff --git a/core/java/android/text/method/ScrollingMovementMethod.java b/core/java/android/text/method/ScrollingMovementMethod.java index db470beed0a392867aa33fff23f66401ed3c9e95..563ceed39824107cfbeee584b39169cdb98a21e5 100644 --- a/core/java/android/text/method/ScrollingMovementMethod.java +++ b/core/java/android/text/method/ScrollingMovementMethod.java @@ -144,6 +144,10 @@ implements MovementMethod } public boolean onKeyDown(TextView widget, Spannable buffer, int keyCode, KeyEvent event) { + return executeDown(widget, buffer, keyCode); + } + + private boolean executeDown(TextView widget, Spannable buffer, int keyCode) { boolean handled = false; switch (keyCode) { @@ -171,6 +175,26 @@ implements MovementMethod return false; } + public boolean onKeyOther(TextView view, Spannable text, KeyEvent event) { + int code = event.getKeyCode(); + if (code != KeyEvent.KEYCODE_UNKNOWN + && event.getAction() == KeyEvent.ACTION_MULTIPLE) { + int repeat = event.getRepeatCount(); + boolean first = true; + boolean handled = false; + while ((--repeat) > 0) { + if (first && executeDown(view, text, code)) { + handled = true; + MetaKeyKeyListener.adjustMetaAfterKeypress(text); + MetaKeyKeyListener.resetLockedMeta(text); + } + first = false; + } + return handled; + } + return false; + } + public boolean onTrackballEvent(TextView widget, Spannable text, MotionEvent event) { return false; diff --git a/core/java/android/text/method/SingleLineTransformationMethod.java b/core/java/android/text/method/SingleLineTransformationMethod.java index a4fcf15566816f9e7e26dc1b9f8a8d7ce01a9539..6a05fe4b64fd8f092609fd9d424fc738cf3f563c 100644 --- a/core/java/android/text/method/SingleLineTransformationMethod.java +++ b/core/java/android/text/method/SingleLineTransformationMethod.java @@ -27,22 +27,24 @@ import android.view.View; /** * This transformation method causes any newline characters (\n) to be - * displayed as spaces instead of causing line breaks. + * displayed as spaces instead of causing line breaks, and causes + * carriage return characters (\r) to have no appearance. */ public class SingleLineTransformationMethod extends ReplacementTransformationMethod { - private static char[] ORIGINAL = new char[] { '\n' }; - private static char[] REPLACEMENT = new char[] { ' ' }; + private static char[] ORIGINAL = new char[] { '\n', '\r' }; + private static char[] REPLACEMENT = new char[] { ' ', '\uFEFF' }; /** - * The character to be replaced is \n. + * The characters to be replaced are \n and \r. */ protected char[] getOriginal() { return ORIGINAL; } /** - * The character \n is replaced with is space. + * The character \n is replaced with is space; + * the character \r is replaced with is FEFF (zero width space). */ protected char[] getReplacement() { return REPLACEMENT; diff --git a/core/java/android/text/method/TextKeyListener.java b/core/java/android/text/method/TextKeyListener.java index b1c380ab70e33a293dcd00b8529617692b12a1b2..5be2a4866c4f8435828c8189f3cd803c385462ed 100644 --- a/core/java/android/text/method/TextKeyListener.java +++ b/core/java/android/text/method/TextKeyListener.java @@ -38,10 +38,10 @@ public class TextKeyListener extends BaseKeyListener implements SpanWatcher { private static TextKeyListener[] sInstance = new TextKeyListener[Capitalize.values().length * 2]; - /* package */ static final Object ACTIVE = new Object(); - /* package */ static final Object CAPPED = new Object(); - /* package */ static final Object INHIBIT_REPLACEMENT = new Object(); - /* package */ static final Object LAST_TYPED = new Object(); + /* package */ static final Object ACTIVE = new NoCopySpan.Concrete(); + /* package */ static final Object CAPPED = new NoCopySpan.Concrete(); + /* package */ static final Object INHIBIT_REPLACEMENT = new NoCopySpan.Concrete(); + /* package */ static final Object LAST_TYPED = new NoCopySpan.Concrete(); private Capitalize mAutoCap; private boolean mAutoText; @@ -140,6 +140,13 @@ public class TextKeyListener extends BaseKeyListener implements SpanWatcher { return im.onKeyUp(view, content, keyCode, event); } + @Override + public boolean onKeyOther(View view, Editable content, KeyEvent event) { + KeyListener im = getKeyListener(event); + + return im.onKeyOther(view, content, event); + } + /** * Clear all the input state (autotext, autocap, multitap, undo) * from the specified Editable, going beyond Editable.clear(), which @@ -205,6 +212,10 @@ public class TextKeyListener extends BaseKeyListener implements SpanWatcher { return false; } + public boolean onKeyOther(View view, Editable content, KeyEvent event) { + return false; + } + public void clearMetaKeyState(View view, Editable content, int states) { } diff --git a/core/java/android/text/method/Touch.java b/core/java/android/text/method/Touch.java index 8b097c5b3fa25f3a80f5688c25a9e29d8e1b67bf..65036ad46d01d787ef32ed30ce03d260dc3e93f6 100644 --- a/core/java/android/text/method/Touch.java +++ b/core/java/android/text/method/Touch.java @@ -17,6 +17,7 @@ package android.text.method; import android.text.Layout; +import android.text.NoCopySpan; import android.text.Layout.Alignment; import android.text.Spannable; import android.view.MotionEvent; @@ -103,7 +104,7 @@ public class Touch { if (ds.length > 0) { if (ds[0].mFarEnough == false) { - int slop = ViewConfiguration.getTouchSlop(); + int slop = ViewConfiguration.get(widget.getContext()).getScaledTouchSlop(); if (Math.abs(event.getX() - ds[0].mX) >= slop || Math.abs(event.getY() - ds[0].mY) >= slop) { @@ -141,7 +142,7 @@ public class Touch { return false; } - private static class DragState { + private static class DragState implements NoCopySpan { public float mX; public float mY; public boolean mFarEnough; diff --git a/core/java/android/text/style/AbsoluteSizeSpan.java b/core/java/android/text/style/AbsoluteSizeSpan.java index 8f6ed5ae30e35dac16e3c9fa9a10e24f6c2072ed..484f8ce410a2923752e5d8c50fb1ebc90917ab81 100644 --- a/core/java/android/text/style/AbsoluteSizeSpan.java +++ b/core/java/android/text/style/AbsoluteSizeSpan.java @@ -16,17 +16,35 @@ package android.text.style; -import android.graphics.Paint; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class AbsoluteSizeSpan extends MetricAffectingSpan { +public class AbsoluteSizeSpan extends MetricAffectingSpan implements ParcelableSpan { - private int mSize; + private final int mSize; public AbsoluteSizeSpan(int size) { mSize = size; } + public AbsoluteSizeSpan(Parcel src) { + mSize = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.ABSOLUTE_SIZE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mSize); + } + public int getSize() { return mSize; } diff --git a/core/java/android/text/style/AlignmentSpan.java b/core/java/android/text/style/AlignmentSpan.java index d51edccca1adad24931ee3430bb836d89e4ee92b..b8a37daada33164b96399d309eb7db4385b87592 100644 --- a/core/java/android/text/style/AlignmentSpan.java +++ b/core/java/android/text/style/AlignmentSpan.java @@ -16,24 +16,40 @@ package android.text.style; +import android.os.Parcel; import android.text.Layout; +import android.text.ParcelableSpan; +import android.text.TextUtils; -public interface AlignmentSpan -extends ParagraphStyle -{ +public interface AlignmentSpan extends ParagraphStyle { public Layout.Alignment getAlignment(); public static class Standard - implements AlignmentSpan - { + implements AlignmentSpan, ParcelableSpan { public Standard(Layout.Alignment align) { mAlignment = align; } + public Standard(Parcel src) { + mAlignment = Layout.Alignment.valueOf(src.readString()); + } + + public int getSpanTypeId() { + return TextUtils.ALIGNMENT_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mAlignment.name()); + } + public Layout.Alignment getAlignment() { return mAlignment; } - private Layout.Alignment mAlignment; + private final Layout.Alignment mAlignment; } } diff --git a/core/java/android/text/style/BackgroundColorSpan.java b/core/java/android/text/style/BackgroundColorSpan.java index 27eda69d9734847472d8e5f9811abead6b5391d1..580a3697439e2725d1c40b95d4cf6230d3c15ee7 100644 --- a/core/java/android/text/style/BackgroundColorSpan.java +++ b/core/java/android/text/style/BackgroundColorSpan.java @@ -16,16 +16,36 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class BackgroundColorSpan extends CharacterStyle implements UpdateAppearance { +public class BackgroundColorSpan extends CharacterStyle + implements UpdateAppearance, ParcelableSpan { - private int mColor; + private final int mColor; public BackgroundColorSpan(int color) { mColor = color; } + public BackgroundColorSpan(Parcel src) { + mColor = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.BACKGROUND_COLOR_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mColor); + } + public int getBackgroundColor() { return mColor; } diff --git a/core/java/android/text/style/BulletSpan.java b/core/java/android/text/style/BulletSpan.java index 70c4d33a74fe14129c1986bbdbc5f6730ef11c2f..655bd81cd493dd8b20f50f25d96ab09c6fc95839 100644 --- a/core/java/android/text/style/BulletSpan.java +++ b/core/java/android/text/style/BulletSpan.java @@ -18,17 +18,30 @@ package android.text.style; import android.graphics.Canvas; import android.graphics.Paint; +import android.os.Parcel; import android.text.Layout; +import android.text.ParcelableSpan; import android.text.Spanned; +import android.text.TextUtils; -public class BulletSpan implements LeadingMarginSpan { +public class BulletSpan implements LeadingMarginSpan, ParcelableSpan { + private final int mGapWidth; + private final boolean mWantColor; + private final int mColor; + + private static final int BULLET_RADIUS = 3; + public static final int STANDARD_GAP_WIDTH = 2; public BulletSpan() { mGapWidth = STANDARD_GAP_WIDTH; + mWantColor = false; + mColor = 0; } public BulletSpan(int gapWidth) { mGapWidth = gapWidth; + mWantColor = false; + mColor = 0; } public BulletSpan(int gapWidth, int color) { @@ -37,6 +50,26 @@ public class BulletSpan implements LeadingMarginSpan { mColor = color; } + public BulletSpan(Parcel src) { + mGapWidth = src.readInt(); + mWantColor = src.readInt() != 0; + mColor = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.BULLET_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mGapWidth); + dest.writeInt(mWantColor ? 1 : 0); + dest.writeInt(mColor); + } + public int getLeadingMargin(boolean first) { return 2 * BULLET_RADIUS + mGapWidth; } @@ -66,11 +99,4 @@ public class BulletSpan implements LeadingMarginSpan { p.setStyle(style); } } - - private int mGapWidth; - private boolean mWantColor; - private int mColor; - - private static final int BULLET_RADIUS = 3; - public static final int STANDARD_GAP_WIDTH = 2; } diff --git a/core/java/android/text/style/ForegroundColorSpan.java b/core/java/android/text/style/ForegroundColorSpan.java index 99b33818b8e4356908eba184958fa4ea95e1dfb5..476124d2af0b2658e9113dbf843c2ebff0bfe21b 100644 --- a/core/java/android/text/style/ForegroundColorSpan.java +++ b/core/java/android/text/style/ForegroundColorSpan.java @@ -16,16 +16,36 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class ForegroundColorSpan extends CharacterStyle implements UpdateAppearance { +public class ForegroundColorSpan extends CharacterStyle + implements UpdateAppearance, ParcelableSpan { - private int mColor; + private final int mColor; public ForegroundColorSpan(int color) { mColor = color; } + public ForegroundColorSpan(Parcel src) { + mColor = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.FOREGROUND_COLOR_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mColor); + } + public int getForegroundColor() { return mColor; } diff --git a/core/java/android/text/style/ImageSpan.java b/core/java/android/text/style/ImageSpan.java index 2eebc0deb80e60162dcd1d08e1c6e11b83d5c69a..29c0c76ad1b11bf652a728bd083c6fc49e4c28ac 100644 --- a/core/java/android/text/style/ImageSpan.java +++ b/core/java/android/text/style/ImageSpan.java @@ -44,8 +44,9 @@ public class ImageSpan extends DynamicDrawableSpan { public ImageSpan(Bitmap b, int verticalAlignment) { super(verticalAlignment); mDrawable = new BitmapDrawable(b); - mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), - mDrawable.getIntrinsicHeight()); + int width = mDrawable.getIntrinsicWidth(); + int height = mDrawable.getIntrinsicHeight(); + mDrawable.setBounds(0, 0, width > 0 ? width : 0, height > 0 ? height : 0); } public ImageSpan(Drawable d) { @@ -87,6 +88,7 @@ public class ImageSpan extends DynamicDrawableSpan { super(verticalAlignment); mContext = context; mContentUri = uri; + mSource = uri.toString(); } public ImageSpan(Context context, int resourceId) { @@ -116,6 +118,8 @@ public class ImageSpan extends DynamicDrawableSpan { mContentUri); bitmap = BitmapFactory.decodeStream(is); drawable = new BitmapDrawable(bitmap); + drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), + drawable.getIntrinsicHeight()); is.close(); } catch (Exception e) { Log.e("sms", "Failed to loaded content " + mContentUri, e); diff --git a/core/java/android/text/style/LeadingMarginSpan.java b/core/java/android/text/style/LeadingMarginSpan.java index 85a27dc55eb51a7a33aeec34991c77a23d361f61..8e212e34b2329ac86695c498350c7be5cc42df0f 100644 --- a/core/java/android/text/style/LeadingMarginSpan.java +++ b/core/java/android/text/style/LeadingMarginSpan.java @@ -18,7 +18,10 @@ package android.text.style; import android.graphics.Paint; import android.graphics.Canvas; +import android.os.Parcel; import android.text.Layout; +import android.text.ParcelableSpan; +import android.text.TextUtils; public interface LeadingMarginSpan extends ParagraphStyle @@ -30,9 +33,9 @@ extends ParagraphStyle CharSequence text, int start, int end, boolean first, Layout layout); - public static class Standard - implements LeadingMarginSpan - { + public static class Standard implements LeadingMarginSpan, ParcelableSpan { + private final int mFirst, mRest; + public Standard(int first, int rest) { mFirst = first; mRest = rest; @@ -42,6 +45,24 @@ extends ParagraphStyle this(every, every); } + public Standard(Parcel src) { + mFirst = src.readInt(); + mRest = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.LEADING_MARGIN_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mFirst); + dest.writeInt(mRest); + } + public int getLeadingMargin(boolean first) { return first ? mFirst : mRest; } @@ -53,7 +74,5 @@ extends ParagraphStyle boolean first, Layout layout) { ; } - - private int mFirst, mRest; } } diff --git a/core/java/android/text/style/QuoteSpan.java b/core/java/android/text/style/QuoteSpan.java index 3f4a32f98bb7992c983158a18fc5889c171e2747..29dd2732d0f0eae6a4802f197eb5d3266bb3bb2d 100644 --- a/core/java/android/text/style/QuoteSpan.java +++ b/core/java/android/text/style/QuoteSpan.java @@ -18,26 +18,43 @@ package android.text.style; import android.graphics.Paint; import android.graphics.Canvas; -import android.graphics.RectF; +import android.os.Parcel; import android.text.Layout; +import android.text.ParcelableSpan; +import android.text.TextUtils; -public class QuoteSpan -implements LeadingMarginSpan -{ +public class QuoteSpan implements LeadingMarginSpan, ParcelableSpan { private static final int STRIPE_WIDTH = 2; private static final int GAP_WIDTH = 2; - private int mColor = 0xff0000ff; + private final int mColor; public QuoteSpan() { super(); + mColor = 0xff0000ff; } public QuoteSpan(int color) { - this(); + super(); mColor = color; } + public QuoteSpan(Parcel src) { + mColor = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.QUOTE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mColor); + } + public int getColor() { return mColor; } diff --git a/core/java/android/text/style/RelativeSizeSpan.java b/core/java/android/text/style/RelativeSizeSpan.java index a8ad0769229b6f600df77373d885ea386f288bce..9717362e865ad01908ceb37c93f8ebc899e7c81a 100644 --- a/core/java/android/text/style/RelativeSizeSpan.java +++ b/core/java/android/text/style/RelativeSizeSpan.java @@ -16,17 +16,35 @@ package android.text.style; -import android.graphics.Paint; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class RelativeSizeSpan extends MetricAffectingSpan { +public class RelativeSizeSpan extends MetricAffectingSpan implements ParcelableSpan { - private float mProportion; + private final float mProportion; public RelativeSizeSpan(float proportion) { mProportion = proportion; } + public RelativeSizeSpan(Parcel src) { + mProportion = src.readFloat(); + } + + public int getSpanTypeId() { + return TextUtils.RELATIVE_SIZE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeFloat(mProportion); + } + public float getSizeChange() { return mProportion; } diff --git a/core/java/android/text/style/ScaleXSpan.java b/core/java/android/text/style/ScaleXSpan.java index ac9e35d04fe4b579139eb7dda94cc54ce75f6ca0..655064b46ecea460696d6afa9b57130991ef6aec 100644 --- a/core/java/android/text/style/ScaleXSpan.java +++ b/core/java/android/text/style/ScaleXSpan.java @@ -16,17 +16,35 @@ package android.text.style; -import android.graphics.Paint; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class ScaleXSpan extends MetricAffectingSpan { +public class ScaleXSpan extends MetricAffectingSpan implements ParcelableSpan { - private float mProportion; + private final float mProportion; public ScaleXSpan(float proportion) { mProportion = proportion; } + public ScaleXSpan(Parcel src) { + mProportion = src.readFloat(); + } + + public int getSpanTypeId() { + return TextUtils.SCALE_X_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeFloat(mProportion); + } + public float getScaleX() { return mProportion; } diff --git a/core/java/android/text/style/StrikethroughSpan.java b/core/java/android/text/style/StrikethroughSpan.java index dd430e56ffff97f08bb41e379f4fdf588fafc219..b51363ac4895b13afcbbe1aa56ed0832160a071f 100644 --- a/core/java/android/text/style/StrikethroughSpan.java +++ b/core/java/android/text/style/StrikethroughSpan.java @@ -16,9 +16,29 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class StrikethroughSpan extends CharacterStyle implements UpdateAppearance { +public class StrikethroughSpan extends CharacterStyle + implements UpdateAppearance, ParcelableSpan { + public StrikethroughSpan() { + } + + public StrikethroughSpan(Parcel src) { + } + + public int getSpanTypeId() { + return TextUtils.STRIKETHROUGH_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + } @Override public void updateDrawState(TextPaint ds) { diff --git a/core/java/android/text/style/StyleSpan.java b/core/java/android/text/style/StyleSpan.java index cc8b06c1a17a225668736196ce23e49229ac7b2d..8e6147c8f91b6d17a727f207d460d4057d2849cb 100644 --- a/core/java/android/text/style/StyleSpan.java +++ b/core/java/android/text/style/StyleSpan.java @@ -18,7 +18,10 @@ package android.text.style; import android.graphics.Paint; import android.graphics.Typeface; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; /** * @@ -28,9 +31,9 @@ import android.text.TextPaint; * you get bold italic. You can't turn off a style from the base style. * */ -public class StyleSpan extends MetricAffectingSpan { +public class StyleSpan extends MetricAffectingSpan implements ParcelableSpan { - private int mStyle; + private final int mStyle; /** * @@ -42,6 +45,22 @@ public class StyleSpan extends MetricAffectingSpan { mStyle = style; } + public StyleSpan(Parcel src) { + mStyle = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.STYLE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mStyle); + } + /** * Returns the style constant defined in {@link android.graphics.Typeface}. */ diff --git a/core/java/android/text/style/SubscriptSpan.java b/core/java/android/text/style/SubscriptSpan.java index 78d6ba98ca0fa515fe1d732ab12143da2f801270..de1d8b20f0df6d2e472a1919dd34aee34517a6a4 100644 --- a/core/java/android/text/style/SubscriptSpan.java +++ b/core/java/android/text/style/SubscriptSpan.java @@ -16,9 +16,29 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; + +public class SubscriptSpan extends MetricAffectingSpan implements ParcelableSpan { + public SubscriptSpan() { + } + + public SubscriptSpan(Parcel src) { + } + + public int getSpanTypeId() { + return TextUtils.SUBSCRIPT_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + } -public class SubscriptSpan extends MetricAffectingSpan { @Override public void updateDrawState(TextPaint tp) { tp.baselineShift -= (int) (tp.ascent() / 2); diff --git a/core/java/android/text/style/SuperscriptSpan.java b/core/java/android/text/style/SuperscriptSpan.java index 79be4de8e661c2623daa4919d6c1c01499313fc8..285fe84e9ec745058df052215c39c9e292384820 100644 --- a/core/java/android/text/style/SuperscriptSpan.java +++ b/core/java/android/text/style/SuperscriptSpan.java @@ -16,9 +16,29 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; + +public class SuperscriptSpan extends MetricAffectingSpan implements ParcelableSpan { + public SuperscriptSpan() { + } + + public SuperscriptSpan(Parcel src) { + } + + public int getSpanTypeId() { + return TextUtils.SUPERSCRIPT_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + } -public class SuperscriptSpan extends MetricAffectingSpan { @Override public void updateDrawState(TextPaint tp) { tp.baselineShift += (int) (tp.ascent() / 2); diff --git a/core/java/android/text/style/TextAppearanceSpan.java b/core/java/android/text/style/TextAppearanceSpan.java index c4ec97611d51cf6419af10a26df4ba7222575cce..de929e3b4a0161d055f88824a12071b3291e0f47 100644 --- a/core/java/android/text/style/TextAppearanceSpan.java +++ b/core/java/android/text/style/TextAppearanceSpan.java @@ -19,20 +19,22 @@ package android.text.style; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; -import android.graphics.Paint; import android.graphics.Typeface; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; /** * Sets the text color, size, style, and typeface to match a TextAppearance * resource. */ -public class TextAppearanceSpan extends MetricAffectingSpan { - private String mTypeface; - private int mStyle; - private int mTextSize; - private ColorStateList mTextColor; - private ColorStateList mTextColorLink; +public class TextAppearanceSpan extends MetricAffectingSpan implements ParcelableSpan { + private final String mTypeface; + private final int mStyle; + private final int mTextSize; + private final ColorStateList mTextColor; + private final ColorStateList mTextColorLink; /** * Uses the specified TextAppearance resource to determine the @@ -53,11 +55,13 @@ public class TextAppearanceSpan extends MetricAffectingSpan { */ public TextAppearanceSpan(Context context, int appearance, int colorList) { + ColorStateList textColor; + TypedArray a = context.obtainStyledAttributes(appearance, com.android.internal.R.styleable.TextAppearance); - mTextColor = a.getColorStateList(com.android.internal.R.styleable. + textColor = a.getColorStateList(com.android.internal.R.styleable. TextAppearance_textColor); mTextColorLink = a.getColorStateList(com.android.internal.R.styleable. TextAppearance_textColorLink); @@ -79,6 +83,10 @@ public class TextAppearanceSpan extends MetricAffectingSpan { case 3: mTypeface = "monospace"; break; + + default: + mTypeface = null; + break; } a.recycle(); @@ -87,9 +95,11 @@ public class TextAppearanceSpan extends MetricAffectingSpan { a = context.obtainStyledAttributes(com.android.internal.R.style.Theme, com.android.internal.R.styleable.Theme); - mTextColor = a.getColorStateList(colorList); + textColor = a.getColorStateList(colorList); a.recycle(); } + + mTextColor = textColor; } /** @@ -105,6 +115,48 @@ public class TextAppearanceSpan extends MetricAffectingSpan { mTextColorLink = linkColor; } + public TextAppearanceSpan(Parcel src) { + mTypeface = src.readString(); + mStyle = src.readInt(); + mTextSize = src.readInt(); + if (src.readInt() != 0) { + mTextColor = ColorStateList.CREATOR.createFromParcel(src); + } else { + mTextColor = null; + } + if (src.readInt() != 0) { + mTextColorLink = ColorStateList.CREATOR.createFromParcel(src); + } else { + mTextColorLink = null; + } + } + + public int getSpanTypeId() { + return TextUtils.TEXT_APPEARANCE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mTypeface); + dest.writeInt(mStyle); + dest.writeInt(mTextSize); + if (mTextColor != null) { + dest.writeInt(1); + mTextColor.writeToParcel(dest, flags); + } else { + dest.writeInt(0); + } + if (mTextColorLink != null) { + dest.writeInt(1); + mTextColorLink.writeToParcel(dest, flags); + } else { + dest.writeInt(0); + } + } + /** * Returns the typeface family specified by this span, or null * if it does not specify one. diff --git a/core/java/android/text/style/TypefaceSpan.java b/core/java/android/text/style/TypefaceSpan.java index 7519ac2b34496707aee17e94e78084bd980df04f..f19406007111e39b3e57d3e79100b3b960d723f4 100644 --- a/core/java/android/text/style/TypefaceSpan.java +++ b/core/java/android/text/style/TypefaceSpan.java @@ -18,13 +18,16 @@ package android.text.style; import android.graphics.Paint; import android.graphics.Typeface; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; /** * Changes the typeface family of the text to which the span is attached. */ -public class TypefaceSpan extends MetricAffectingSpan { - private String mFamily; +public class TypefaceSpan extends MetricAffectingSpan implements ParcelableSpan { + private final String mFamily; /** * @param family The font family for this typeface. Examples include @@ -34,6 +37,22 @@ public class TypefaceSpan extends MetricAffectingSpan { mFamily = family; } + public TypefaceSpan(Parcel src) { + mFamily = src.readString(); + } + + public int getSpanTypeId() { + return TextUtils.TYPEFACE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mFamily); + } + /** * Returns the font family name. */ diff --git a/core/java/android/text/style/URLSpan.java b/core/java/android/text/style/URLSpan.java index 79809b551c9ba83d0bdee276d7e1a6967137a82f..d29bfb65d80715cab1547285ece5a58a1889631c 100644 --- a/core/java/android/text/style/URLSpan.java +++ b/core/java/android/text/style/URLSpan.java @@ -16,19 +16,39 @@ package android.text.style; +import android.content.Context; import android.content.Intent; import android.net.Uri; -import android.text.TextPaint; +import android.os.Parcel; +import android.provider.Browser; +import android.text.ParcelableSpan; +import android.text.TextUtils; import android.view.View; -public class URLSpan extends ClickableSpan { +public class URLSpan extends ClickableSpan implements ParcelableSpan { - private String mURL; + private final String mURL; public URLSpan(String url) { mURL = url; } + public URLSpan(Parcel src) { + mURL = src.readString(); + } + + public int getSpanTypeId() { + return TextUtils.URL_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mURL); + } + public String getURL() { return mURL; } @@ -36,8 +56,9 @@ public class URLSpan extends ClickableSpan { @Override public void onClick(View widget) { Uri uri = Uri.parse(getURL()); + Context context = widget.getContext(); Intent intent = new Intent(Intent.ACTION_VIEW, uri); - intent.addCategory(Intent.CATEGORY_BROWSABLE); - widget.getContext().startActivity(intent); + intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()); + context.startActivity(intent); } } diff --git a/core/java/android/text/style/UnderlineSpan.java b/core/java/android/text/style/UnderlineSpan.java index ca6f10c53c474198fff46122081a0c6059f99637..b0cb0e8f2c44844a421aced3bf297cebee96f7a6 100644 --- a/core/java/android/text/style/UnderlineSpan.java +++ b/core/java/android/text/style/UnderlineSpan.java @@ -16,9 +16,29 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class UnderlineSpan extends CharacterStyle implements UpdateAppearance { +public class UnderlineSpan extends CharacterStyle + implements UpdateAppearance, ParcelableSpan { + public UnderlineSpan() { + } + + public UnderlineSpan(Parcel src) { + } + + public int getSpanTypeId() { + return TextUtils.UNDERLINE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + } @Override public void updateDrawState(TextPaint ds) { diff --git a/core/java/android/text/util/Regex.java b/core/java/android/text/util/Regex.java index 4c128ad19e1f58a2e37a88fe34c8e405f1f03d4f..a349b82dbad672f5320e4aa14d61745877f93a77 100644 --- a/core/java/android/text/util/Regex.java +++ b/core/java/android/text/util/Regex.java @@ -66,9 +66,9 @@ public class Regex { public static final Pattern WEB_URL_PATTERN = Pattern.compile( "((?:(http|https|Http|Https):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)" - + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2}))+(?:\\:(?:[a-zA-Z0-9\\$\\-\\_" - + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2}))+)?\\@)?)?" - + "((?:(?:[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+" // named host + + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_" + + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?" + + "((?:(?:[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}\\.)+" // named host + "(?:" // plus top level domain + "(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])" + "|(?:biz|b[abdefghijmnorstvwyz])" @@ -122,12 +122,12 @@ public class Regex { public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile( - "[a-zA-Z0-9\\+\\.\\_\\%\\-]+" + + "[a-zA-Z0-9\\+\\.\\_\\%\\-]{1,256}" + "\\@" + - "[a-zA-Z0-9][a-zA-Z0-9\\-]*" + + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + - "[a-zA-Z0-9][a-zA-Z0-9\\-]*" + + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+" ); diff --git a/core/java/android/text/util/Rfc822Validator.java b/core/java/android/text/util/Rfc822Validator.java index 9f03bb01e3ba03b0154f7fff66abaddc0f906949..6a6bf698360f50427cad2d545d8480f1a2cc64c2 100644 --- a/core/java/android/text/util/Rfc822Validator.java +++ b/core/java/android/text/util/Rfc822Validator.java @@ -16,6 +16,7 @@ package android.text.util; +import android.text.TextUtils; import android.widget.AutoCompleteTextView; import java.util.regex.Pattern; @@ -67,7 +68,7 @@ public class Rfc822Validator implements AutoCompleteTextView.Validator { /** * @return a string in which all the characters that are illegal for the username - * part of the email address have been removed. + * or the domain name part of the email address have been removed. */ private String removeIllegalCharacters(String s) { StringBuilder result = new StringBuilder(); @@ -101,6 +102,9 @@ public class Rfc822Validator implements AutoCompleteTextView.Validator { * {@inheritDoc} */ public CharSequence fixText(CharSequence cs) { + // Return an empty string if the email address only contains spaces, \n or \t + if (TextUtils.getTrimmedLength(cs) == 0) return ""; + Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(cs); StringBuilder sb = new StringBuilder(); @@ -111,10 +115,10 @@ public class Rfc822Validator implements AutoCompleteTextView.Validator { // If there is no @, just append the domain of the account tokens[i].setAddress(removeIllegalCharacters(text) + "@" + mDomain); } else { - // Otherwise, remove everything right of the '@' and append the domain - // ("a@b" becomes "a@gmail.com"). + // Otherwise, remove the illegal characters on both sides of the '@' String fix = removeIllegalCharacters(text.substring(0, index)); - tokens[i].setAddress(fix + "@" + mDomain); + String domain = removeIllegalCharacters(text.substring(index + 1)); + tokens[i].setAddress(fix + "@" + (domain.length() != 0 ? domain : mDomain)); } sb.append(tokens[i].toString()); diff --git a/core/java/android/util/DisplayMetrics.java b/core/java/android/util/DisplayMetrics.java index 8fc3602e8ba966c8e331e7af748ffad33cb780d9..9de4cbe80665f770ecc3c88979b875773dc64807 100644 --- a/core/java/android/util/DisplayMetrics.java +++ b/core/java/android/util/DisplayMetrics.java @@ -16,12 +16,24 @@ package android.util; +import android.os.*; + /** * A structure describing general information about a display, such as its * size, density, and font scaling. */ public class DisplayMetrics { + /** + * The reference density used throughout the system. + * + * @hide Pending API council approval + */ + public static final int DEFAULT_DENSITY = 160; + + private static final int sLcdDensity = SystemProperties.getInt("ro.sf.lcd_density", + DEFAULT_DENSITY); + /** * The absolute width of the display in pixels. */ @@ -43,7 +55,9 @@ public class DisplayMetrics { * example, a 240x320 screen will have a density of 1 even if its width is * 1.8", 1.3", etc. However, if the screen resolution is increased to * 320x480 but the screen size remained 1.5"x2" then the density would be - * increased (probably to 1.5). + * increased (probably to 1.5). + * + * @see #DEFAULT_DENSITY */ public float density; /** @@ -60,7 +74,7 @@ public class DisplayMetrics { * The exact physical pixels per inch of the screen in the Y dimension. */ public float ydpi; - + public DisplayMetrics() { } @@ -76,10 +90,9 @@ public class DisplayMetrics { public void setToDefaults() { widthPixels = 0; heightPixels = 0; - density = 1; - scaledDensity = 1; - xdpi = 160; - ydpi = 160; + density = sLcdDensity / (float) DEFAULT_DENSITY; + scaledDensity = density; + xdpi = sLcdDensity; + ydpi = sLcdDensity; } } - diff --git a/core/java/android/util/SparseIntArray.java b/core/java/android/util/SparseIntArray.java index 610cfd4a461aabf9137396e32f415d21f8d62982..9ab3b53169e3836503fd15aa9ebd1e4aaa148005 100644 --- a/core/java/android/util/SparseIntArray.java +++ b/core/java/android/util/SparseIntArray.java @@ -73,12 +73,19 @@ public class SparseIntArray { int i = binarySearch(mKeys, 0, mSize, key); if (i >= 0) { - System.arraycopy(mKeys, i + 1, mKeys, i, mSize - (i + 1)); - System.arraycopy(mValues, i + 1, mValues, i, mSize - (i + 1)); - mSize--; + removeAt(i); } } + /** + * Removes the mapping at the given index. + */ + public void removeAt(int index) { + System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1)); + System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1)); + mSize--; + } + /** * Adds a mapping from the specified key to the specified value, * replacing the previous mapping from the specified key if there diff --git a/core/java/android/util/TypedValue.java b/core/java/android/util/TypedValue.java index a4ee35ad2e129073b4bf4906e47f700cee9d0576..d4ba9e21ac13f3b37c36f5b5db102d7be92ba8f4 100644 --- a/core/java/android/util/TypedValue.java +++ b/core/java/android/util/TypedValue.java @@ -16,9 +16,6 @@ package android.util; -import android.util.Config; -import android.util.Log; - /** * Container for a dynamically typed data value. Primarily used with * {@link android.content.res.Resources} for holding resource values. @@ -141,6 +138,16 @@ public class TypedValue { /* ------------------------------------------------------------ */ + /** + * If {@link #density} is equal to this value, then the density should be + * treated as the system's default density value: {@link DisplayMetrics#DEFAULT_DENSITY}. + * + * @hide Pending API council approval + */ + public static final int DENSITY_DEFAULT = 0; + + /* ------------------------------------------------------------ */ + /** The type held by this value, as defined by the constants here. * This tells you how to interpret the other fields in the object. */ public int type; @@ -161,7 +168,14 @@ public class TypedValue { /** If Value came from a resource, these are the configurations for which * its contents can change. */ public int changingConfigurations = -1; - + + /** + * If the Value came from a resource, this holds the corresponding pixel density. + * + * @hide Pending API council approval + * */ + public int density; + /* ------------------------------------------------------------ */ /** Return the data for this value as a float. Only use for values @@ -454,6 +468,7 @@ public class TypedValue { data = other.data; assetCookie = other.assetCookie; resourceId = other.resourceId; + density = other.density; } public String toString() diff --git a/core/java/android/view/FocusFinder.java b/core/java/android/view/FocusFinder.java index 4048763d042ce8e2444d4a4b8787c0bc39d2794c..15fb83903e502ae5b2f0e67605fb8318eec7a1f2 100644 --- a/core/java/android/view/FocusFinder.java +++ b/core/java/android/view/FocusFinder.java @@ -397,7 +397,7 @@ public class FocusFinder { int numTouchables = touchables.size(); - int edgeSlop = ViewConfiguration.getEdgeSlop(); + int edgeSlop = ViewConfiguration.get(root.mContext).getScaledEdgeSlop(); Rect closestBounds = new Rect(); Rect touchableBounds = mOtherRect; diff --git a/core/java/android/view/GestureDetector.java b/core/java/android/view/GestureDetector.java index fc9af05944fa14c4f93bd96c80e47070343021d8..f7ac522aba6e09c29b37ef191c6bb7b453640de5 100644 --- a/core/java/android/view/GestureDetector.java +++ b/core/java/android/view/GestureDetector.java @@ -18,6 +18,7 @@ package android.view; import android.os.Handler; import android.os.Message; +import android.content.Context; /** * Detects various gestures and events using the supplied {@link MotionEvent}s. @@ -34,7 +35,6 @@ import android.os.Message; *

          */ public class GestureDetector { - /** * The listener that is used to notify when gestures occur. * If you want to listen for all the different gestures then implement @@ -113,12 +113,48 @@ public class GestureDetector { } /** - * A convenience class to extend when you only want to listen for a - * subset of all the gestures. This implements all methods in the - * {@link OnGestureListener} but does nothing and return {@code false} - * for all applicable methods. + * The listener that is used to notify when a double-tap or a confirmed + * single-tap occur. */ - public static class SimpleOnGestureListener implements OnGestureListener { + public interface OnDoubleTapListener { + /** + * Notified when a single-tap occurs. + *

          + * Unlike {@link OnGestureListener#onSingleTapUp(MotionEvent)}, this + * will only be called after the detector is confident that the user's + * first tap is not followed by a second tap leading to a double-tap + * gesture. + * + * @param e The down motion event of the single-tap. + * @return true if the event is consumed, else false + */ + boolean onSingleTapConfirmed(MotionEvent e); + + /** + * Notified when a double-tap occurs. + * + * @param e The down motion event of the first tap of the double-tap. + * @return true if the event is consumed, else false + */ + boolean onDoubleTap(MotionEvent e); + + /** + * Notified when an event within a double-tap gesture occurs, including + * the down, move, and up events. + * + * @param e The motion event that occurred during the double-tap gesture. + * @return true if the event is consumed, else false + */ + boolean onDoubleTapEvent(MotionEvent e); + } + + /** + * A convenience class to extend when you only want to listen for a subset + * of all the gestures. This implements all methods in the + * {@link OnGestureListener} and {@link OnDoubleTapListener} but does + * nothing and return {@code false} for all applicable methods. + */ + public static class SimpleOnGestureListener implements OnGestureListener, OnDoubleTapListener { public boolean onSingleTapUp(MotionEvent e) { return false; } @@ -142,23 +178,55 @@ public class GestureDetector { public boolean onDown(MotionEvent e) { return false; } + + public boolean onDoubleTap(MotionEvent e) { + return false; + } + + public boolean onDoubleTapEvent(MotionEvent e) { + return false; + } + + public boolean onSingleTapConfirmed(MotionEvent e) { + return false; + } } - private static final int TOUCH_SLOP_SQUARE = ViewConfiguration.getTouchSlop() - * ViewConfiguration.getTouchSlop(); + // TODO: ViewConfiguration + private int mBiggerTouchSlopSquare = 20 * 20; + + private int mTouchSlopSquare; + private int mDoubleTapSlopSquare; + private int mMinimumFlingVelocity; + + private static final int LONGPRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout(); + private static final int TAP_TIMEOUT = ViewConfiguration.getTapTimeout(); + // TODO make new double-tap timeout, and define its events (i.e. either time + // between down-down or time between up-down) + private static final int DOUBLE_TAP_TIMEOUT = ViewConfiguration.getDoubleTapTimeout(); // constants for Message.what used by GestureHandler below private static final int SHOW_PRESS = 1; private static final int LONG_PRESS = 2; + private static final int TAP = 3; private final Handler mHandler; private final OnGestureListener mListener; + private OnDoubleTapListener mDoubleTapListener; + private boolean mStillDown; private boolean mInLongPress; private boolean mAlwaysInTapRegion; + private boolean mAlwaysInBiggerTapRegion; private MotionEvent mCurrentDownEvent; - private MotionEvent mCurrentUpEvent; + private MotionEvent mPreviousUpEvent; + + /** + * True when the user is still touching for the second tap (down, move, and + * up events). Can only be true if there is a double tap listener attached. + */ + private boolean mIsDoubleTapping; private float mLastMotionY; private float mLastMotionX; @@ -189,9 +257,16 @@ public class GestureDetector { case LONG_PRESS: dispatchLongPress(); break; + + case TAP: + // If the user's finger is still down, do not count it as a tap + if (mDoubleTapListener != null && !mStillDown) { + mDoubleTapListener.onSingleTapConfirmed(mCurrentDownEvent); + } + break; default: - throw new RuntimeException("Unknown message " + msg); //never + throw new RuntimeException("Unknown message " + msg); //never } } } @@ -203,16 +278,17 @@ public class GestureDetector { * * @param listener the listener invoked for all the callbacks, this must * not be null. - * @param handler the handler to use, this must - * not be null. + * @param handler the handler to use * * @throws NullPointerException if either {@code listener} or * {@code handler} is null. + * + * @deprecated Use {@link #GestureDetector(android.content.Context, + * android.view.GestureDetector.OnGestureListener, android.os.Handler)} instead. */ + @Deprecated public GestureDetector(OnGestureListener listener, Handler handler) { - mHandler = new GestureHandler(handler); - mListener = listener; - init(); + this(null, listener, handler); } /** @@ -222,19 +298,90 @@ public class GestureDetector { * * @param listener the listener invoked for all the callbacks, this must * not be null. + * * @throws NullPointerException if {@code listener} is null. + * + * @deprecated Use {@link #GestureDetector(android.content.Context, + * android.view.GestureDetector.OnGestureListener)} instead. */ + @Deprecated public GestureDetector(OnGestureListener listener) { - mHandler = new GestureHandler(); + this(null, listener, null); + } + + /** + * Creates a GestureDetector with the supplied listener. + * You may only use this constructor from a UI thread (this is the usual situation). + * @see android.os.Handler#Handler() + * + * @param context the application's context + * @param listener the listener invoked for all the callbacks, this must + * not be null. + * + * @throws NullPointerException if {@code listener} is null. + */ + public GestureDetector(Context context, OnGestureListener listener) { + this(context, listener, null); + } + + /** + * Creates a GestureDetector with the supplied listener. + * You may only use this constructor from a UI thread (this is the usual situation). + * @see android.os.Handler#Handler() + * + * @param context the application's context + * @param listener the listener invoked for all the callbacks, this must + * not be null. + * @param handler the handler to use + * + * @throws NullPointerException if {@code listener} is null. + */ + public GestureDetector(Context context, OnGestureListener listener, Handler handler) { + if (handler != null) { + mHandler = new GestureHandler(handler); + } else { + mHandler = new GestureHandler(); + } mListener = listener; - init(); + if (listener instanceof OnDoubleTapListener) { + setOnDoubleTapListener((OnDoubleTapListener) listener); + } + init(context); } - private void init() { + private void init(Context context) { if (mListener == null) { throw new NullPointerException("OnGestureListener must not be null"); } mIsLongpressEnabled = true; + + // Fallback to support pre-donuts releases + int touchSlop, doubleTapSlop; + if (context == null) { + //noinspection deprecation + touchSlop = ViewConfiguration.getTouchSlop(); + doubleTapSlop = ViewConfiguration.getDoubleTapSlop(); + //noinspection deprecation + mMinimumFlingVelocity = ViewConfiguration.getMinimumFlingVelocity(); + } else { + final ViewConfiguration configuration = ViewConfiguration.get(context); + touchSlop = configuration.getScaledTouchSlop(); + doubleTapSlop = configuration.getScaledDoubleTapSlop(); + mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity(); + } + mTouchSlopSquare = touchSlop * touchSlop; + mDoubleTapSlopSquare = doubleTapSlop * doubleTapSlop; + } + + /** + * Sets the listener which will be called for double-tap and related + * gestures. + * + * @param onDoubleTapListener the listener invoked for all the callbacks, or + * null to stop listening for double-tap gestures. + */ + public void setOnDoubleTapListener(OnDoubleTapListener onDoubleTapListener) { + mDoubleTapListener = onDoubleTapListener; } /** @@ -266,9 +413,6 @@ public class GestureDetector { * else false. */ public boolean onTouchEvent(MotionEvent ev) { - final long tapTime = ViewConfiguration.getTapTimeout(); - final long longpressTime = ViewConfiguration.getLongPressTimeout(); - final int touchSlop = ViewConfiguration.getTouchSlop(); final int action = ev.getAction(); final float y = ev.getY(); final float x = ev.getX(); @@ -282,19 +426,38 @@ public class GestureDetector { switch (action) { case MotionEvent.ACTION_DOWN: + if (mDoubleTapListener != null) { + boolean hadTapMessage = mHandler.hasMessages(TAP); + if (hadTapMessage) mHandler.removeMessages(TAP); + if ((mCurrentDownEvent != null) && (mPreviousUpEvent != null) && hadTapMessage && + isConsideredDoubleTap(mCurrentDownEvent, mPreviousUpEvent, ev)) { + // This is a second tap + mIsDoubleTapping = true; + // Give a callback with the first tap of the double-tap + handled |= mDoubleTapListener.onDoubleTap(mCurrentDownEvent); + // Give a callback with down event of the double-tap + handled |= mDoubleTapListener.onDoubleTapEvent(ev); + } else { + // This is a first tap + mHandler.sendEmptyMessageDelayed(TAP, DOUBLE_TAP_TIMEOUT); + } + } + mLastMotionX = x; mLastMotionY = y; mCurrentDownEvent = MotionEvent.obtain(ev); mAlwaysInTapRegion = true; + mAlwaysInBiggerTapRegion = true; + mStillDown = true; mInLongPress = false; - + if (mIsLongpressEnabled) { mHandler.removeMessages(LONG_PRESS); mHandler.sendEmptyMessageAtTime(LONG_PRESS, mCurrentDownEvent.getDownTime() - + tapTime + longpressTime); + + TAP_TIMEOUT + LONGPRESS_TIMEOUT); } - mHandler.sendEmptyMessageAtTime(SHOW_PRESS, mCurrentDownEvent.getDownTime() + tapTime); - handled = mListener.onDown(ev); + mHandler.sendEmptyMessageAtTime(SHOW_PRESS, mCurrentDownEvent.getDownTime() + TAP_TIMEOUT); + handled |= mListener.onDown(ev); break; case MotionEvent.ACTION_MOVE: @@ -303,18 +466,25 @@ public class GestureDetector { } final float scrollX = mLastMotionX - x; final float scrollY = mLastMotionY - y; - if (mAlwaysInTapRegion) { + if (mIsDoubleTapping) { + // Give the move events of the double-tap + handled |= mDoubleTapListener.onDoubleTapEvent(ev); + } else if (mAlwaysInTapRegion) { final int deltaX = (int) (x - mCurrentDownEvent.getX()); final int deltaY = (int) (y - mCurrentDownEvent.getY()); int distance = (deltaX * deltaX) + (deltaY * deltaY); - if (distance > TOUCH_SLOP_SQUARE) { + if (distance > mTouchSlopSquare) { handled = mListener.onScroll(mCurrentDownEvent, ev, scrollX, scrollY); mLastMotionX = x; mLastMotionY = y; mAlwaysInTapRegion = false; + mHandler.removeMessages(TAP); mHandler.removeMessages(SHOW_PRESS); mHandler.removeMessages(LONG_PRESS); } + if (distance > mBiggerTouchSlopSquare) { + mAlwaysInBiggerTapRegion = false; + } } else if ((Math.abs(scrollX) >= 1) || (Math.abs(scrollY) >= 1)) { handled = mListener.onScroll(mCurrentDownEvent, ev, scrollX, scrollY); mLastMotionX = x; @@ -323,12 +493,15 @@ public class GestureDetector { break; case MotionEvent.ACTION_UP: - mCurrentUpEvent = MotionEvent.obtain(ev); - if (mInLongPress) { + mStillDown = false; + MotionEvent currentUpEvent = MotionEvent.obtain(ev); + if (mIsDoubleTapping) { + // Finally, give the up event of the double-tap + handled |= mDoubleTapListener.onDoubleTapEvent(ev); + } else if (mInLongPress) { + mHandler.removeMessages(TAP); mInLongPress = false; - break; - } - if (mAlwaysInTapRegion) { + } else if (mAlwaysInTapRegion) { handled = mListener.onSingleTapUp(ev); } else { @@ -338,21 +511,26 @@ public class GestureDetector { final float velocityY = velocityTracker.getYVelocity(); final float velocityX = velocityTracker.getXVelocity(); - if ((Math.abs(velocityY) > ViewConfiguration.getMinimumFlingVelocity()) - || (Math.abs(velocityX) > ViewConfiguration.getMinimumFlingVelocity())){ - handled = mListener.onFling(mCurrentDownEvent, mCurrentUpEvent, velocityX, velocityY); + if ((Math.abs(velocityY) > mMinimumFlingVelocity) + || (Math.abs(velocityX) > mMinimumFlingVelocity)){ + handled = mListener.onFling(mCurrentDownEvent, currentUpEvent, velocityX, velocityY); } } + mPreviousUpEvent = MotionEvent.obtain(ev); mVelocityTracker.recycle(); mVelocityTracker = null; + mIsDoubleTapping = false; mHandler.removeMessages(SHOW_PRESS); mHandler.removeMessages(LONG_PRESS); break; case MotionEvent.ACTION_CANCEL: mHandler.removeMessages(SHOW_PRESS); mHandler.removeMessages(LONG_PRESS); + mHandler.removeMessages(TAP); mVelocityTracker.recycle(); mVelocityTracker = null; + mIsDoubleTapping = false; + mStillDown = false; if (mInLongPress) { mInLongPress = false; break; @@ -361,7 +539,23 @@ public class GestureDetector { return handled; } + private boolean isConsideredDoubleTap(MotionEvent firstDown, MotionEvent firstUp, + MotionEvent secondDown) { + if (!mAlwaysInBiggerTapRegion) { + return false; + } + + if (secondDown.getEventTime() - firstUp.getEventTime() > DOUBLE_TAP_TIMEOUT) { + return false; + } + + int deltaX = (int) firstDown.getX() - (int) secondDown.getX(); + int deltaY = (int) firstDown.getY() - (int) secondDown.getY(); + return (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare); + } + private void dispatchLongPress() { + mHandler.removeMessages(TAP); mInLongPress = true; mListener.onLongPress(mCurrentDownEvent); } diff --git a/core/java/android/view/HapticFeedbackConstants.java b/core/java/android/view/HapticFeedbackConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..841066c7ba525572c352edb41680a1e4b547c9fa --- /dev/null +++ b/core/java/android/view/HapticFeedbackConstants.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package android.view; + +/** + * Constants to be used to perform haptic feedback effects via + * {@link View#performHapticFeedback(int)} + */ +public class HapticFeedbackConstants { + + private HapticFeedbackConstants() {} + + public static final int LONG_PRESS = 0; + + /** + * Flag for {@link View#performHapticFeedback(int, int) + * View.performHapticFeedback(int, int)}: Ignore the setting in the + * view for whether to perform haptic feedback, do it always. + */ + public static final int FLAG_IGNORE_VIEW_SETTING = 0x0001; + + /** + * Flag for {@link View#performHapticFeedback(int, int) + * View.performHapticFeedback(int, int)}: Ignore the global setting + * for whether to perform haptic feedback, do it always. + */ + public static final int FLAG_IGNORE_GLOBAL_SETTING = 0x0002; +} diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl index 40251dbbd244525696f44697115806719a59b567..a856b24c635066bb2e500a07ce40e75a23d18c87 100644 --- a/core/java/android/view/IWindowManager.aidl +++ b/core/java/android/view/IWindowManager.aidl @@ -104,6 +104,9 @@ interface IWindowManager int getKeycodeState(int sw); int getKeycodeStateForDevice(int devid, int sw); + // Report whether the hardware supports the given keys; returns true if successful + boolean hasKeys(in int[] keycodes, inout boolean[] keyExists); + // For testing void setInTouchMode(boolean showFocus); diff --git a/core/java/android/view/IWindowSession.aidl b/core/java/android/view/IWindowSession.aidl index 7276f173cf3f50c0960a41c2b8249b9383c3af1c..11568566940627e640c9a2990947b63dda837237 100644 --- a/core/java/android/view/IWindowSession.aidl +++ b/core/java/android/view/IWindowSession.aidl @@ -106,5 +106,6 @@ interface IWindowSession { void setInTouchMode(boolean showFocus); boolean getInTouchMode(); + + boolean performHapticFeedback(IWindow window, int effectId, boolean always); } - diff --git a/core/java/android/view/KeyCharacterMap.java b/core/java/android/view/KeyCharacterMap.java index 0347d5098155e9bd8601cb9710735eddb59dc856..25958aa46314308a8f3631dec549a8b8599ac705 100644 --- a/core/java/android/view/KeyCharacterMap.java +++ b/core/java/android/view/KeyCharacterMap.java @@ -18,6 +18,8 @@ package android.view; import android.text.method.MetaKeyKeyListener; import android.util.SparseIntArray; +import android.os.RemoteException; +import android.os.ServiceManager; import android.os.SystemClock; import android.util.SparseArray; @@ -350,6 +352,28 @@ public class KeyCharacterMap return getKeyboardType_native(mPointer); } + /** + * Queries the framework about whether any physical keys exist on the + * device that are capable of producing the given key codes. + */ + public static boolean deviceHasKey(int keyCode) { + int[] codeArray = new int[1]; + codeArray[0] = keyCode; + boolean[] ret = deviceHasKeys(codeArray); + return ret[0]; + } + + public static boolean[] deviceHasKeys(int[] keyCodes) { + boolean[] ret = new boolean[keyCodes.length]; + IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); + try { + wm.hasKeys(keyCodes, ret); + } catch (RemoteException e) { + // no fallback; just return the empty array + } + return ret; + } + private int mPointer; private int mKeyboardDevice; diff --git a/core/java/android/view/KeyEvent.java b/core/java/android/view/KeyEvent.java index 1575aad11059ca9f29d193b35a5dc17e5e84e6a8..430cc71de6108bbc96f9338f3dee2bb597889c62 100644 --- a/core/java/android/view/KeyEvent.java +++ b/core/java/android/view/KeyEvent.java @@ -92,7 +92,7 @@ public class KeyEvent implements Parcelable { public static final int KEYCODE_SYM = 63; public static final int KEYCODE_EXPLORER = 64; public static final int KEYCODE_ENVELOPE = 65; - public static final int KEYCODE_ENTER = 66; + public static final int KEYCODE_ENTER = 66; public static final int KEYCODE_DEL = 67; public static final int KEYCODE_GRAVE = 68; public static final int KEYCODE_MINUS = 69; @@ -117,7 +117,8 @@ public class KeyEvent implements Parcelable { public static final int KEYCODE_PREVIOUSSONG = 88; public static final int KEYCODE_REWIND = 89; public static final int KEYCODE_FORWARD = 90; - private static final int LAST_KEYCODE = KEYCODE_FORWARD; + public static final int KEYCODE_MUTE = 91; + private static final int LAST_KEYCODE = KEYCODE_MUTE; // NOTE: If you add a new keycode here you must also add it to: // isSystem() @@ -144,8 +145,12 @@ public class KeyEvent implements Parcelable { public static final int ACTION_UP = 1; /** * {@link #getAction} value: multiple duplicate key events have - * occurred in a row. The {#link {@link #getRepeatCount()} method returns - * the number of duplicates. + * occurred in a row, or a complex string is being delivered. If the + * key code is not {#link {@link #KEYCODE_UNKNOWN} then the + * {#link {@link #getRepeatCount()} method returns the number of times + * the given key code should be executed. + * Otherwise, if the key code {@link #KEYCODE_UNKNOWN}, then + * this is a sequence of characters as returned by {@link #getCharacters}. */ public static final int ACTION_MULTIPLE = 2; @@ -223,6 +228,12 @@ public class KeyEvent implements Parcelable { */ public static final int FLAG_SOFT_KEYBOARD = 0x2; + /** + * This mask is set if we don't want the key event to cause us to leave + * touch mode. + */ + public static final int FLAG_KEEP_TOUCH_MODE = 0x4; + /** * Returns the maximum keycode. */ @@ -248,6 +259,7 @@ public class KeyEvent implements Parcelable { private int mFlags; private long mDownTime; private long mEventTime; + private String mCharacters; public interface Callback { /** @@ -405,6 +417,28 @@ public class KeyEvent implements Parcelable { mFlags = flags; } + /** + * Create a new key event for a string of characters. The key code, + * action, and repeat could will automatically be set to + * {@link #KEYCODE_UNKNOWN}, {@link #ACTION_MULTIPLE}, and 0 for you. + * + * @param time The time (in {@link android.os.SystemClock#uptimeMillis}) + * at which this event occured. + * @param characters The string of characters. + * @param device The device ID that generated the key event. + * @param flags The flags for this key event + */ + public KeyEvent(long time, String characters, int device, int flags) { + mDownTime = time; + mEventTime = time; + mCharacters = characters; + mAction = ACTION_MULTIPLE; + mKeyCode = KEYCODE_UNKNOWN; + mRepeatCount = 0; + mDeviceId = device; + mFlags = flags; + } + /** * Copy an existing key event, modifying its time and repeat count. * @@ -423,6 +457,7 @@ public class KeyEvent implements Parcelable { mDeviceId = origEvent.mDeviceId; mScancode = origEvent.mScancode; mFlags = origEvent.mFlags; + mCharacters = origEvent.mCharacters; } /** @@ -441,6 +476,8 @@ public class KeyEvent implements Parcelable { mDeviceId = origEvent.mDeviceId; mScancode = origEvent.mScancode; mFlags = origEvent.mFlags; + // Don't copy mCharacters, since one way or the other we'll lose it + // when changing the action. } /** @@ -472,6 +509,7 @@ public class KeyEvent implements Parcelable { case KEYCODE_ENDCALL: case KEYCODE_VOLUME_UP: case KEYCODE_VOLUME_DOWN: + case KEYCODE_MUTE: case KEYCODE_POWER: case KEYCODE_HEADSETHOOK: case KEYCODE_PLAYPAUSE: @@ -580,7 +618,7 @@ public class KeyEvent implements Parcelable { /** * Retrieve the key code of the key event. This is the physical key that - * was pressed -- not the Unicode character. + * was pressed, not the Unicode character. * * @return The key code of the event. */ @@ -588,6 +626,18 @@ public class KeyEvent implements Parcelable { return mKeyCode; } + /** + * For the special case of a {@link #ACTION_MULTIPLE} event with key + * code of {@link #KEYCODE_UNKNOWN}, this is a raw string of characters + * associated with the event. In all other cases it is null. + * + * @return Returns a String of 1 or more characters associated with + * the event. + */ + public final String getCharacters() { + return mCharacters; + } + /** * Retrieve the hardware key id of this key event. These values are not * reliable and vary from device to device. @@ -772,16 +822,18 @@ public class KeyEvent implements Parcelable { if (receiver.onKeyMultiple(code, count, this)) { return true; } - mAction = ACTION_DOWN; - mRepeatCount = 0; - boolean handled = receiver.onKeyDown(code, this); - if (handled) { - mAction = ACTION_UP; - receiver.onKeyUp(code, this); + if (code != KeyEvent.KEYCODE_UNKNOWN) { + mAction = ACTION_DOWN; + mRepeatCount = 0; + boolean handled = receiver.onKeyDown(code, this); + if (handled) { + mAction = ACTION_UP; + receiver.onKeyUp(code, this); + } + mAction = ACTION_MULTIPLE; + mRepeatCount = count; + return handled; } - mAction = ACTION_MULTIPLE; - mRepeatCount = count; - return handled; } return false; } diff --git a/core/java/android/view/OrientationEventListener.java b/core/java/android/view/OrientationEventListener.java new file mode 100755 index 0000000000000000000000000000000000000000..391ba1e794c30713f28631a4ce8570744f2d548e --- /dev/null +++ b/core/java/android/view/OrientationEventListener.java @@ -0,0 +1,174 @@ +/* + * 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. + */ + +package android.view; + +import android.content.Context; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.util.Config; +import android.util.Log; + +/** + * Helper class for receiving notifications from the SensorManager when + * the orientation of the device has changed. + */ +public abstract class OrientationEventListener { + private static final String TAG = "OrientationEventListener"; + private static final boolean DEBUG = false; + private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV; + private int mOrientation = ORIENTATION_UNKNOWN; + private SensorManager mSensorManager; + private boolean mEnabled = false; + private int mRate; + private Sensor mSensor; + private SensorEventListener mSensorEventListener; + private OrientationListener mOldListener; + + /** + * Returned from onOrientationChanged when the device orientation cannot be determined + * (typically when the device is in a close to flat position). + * + * @see #onOrientationChanged + */ + public static final int ORIENTATION_UNKNOWN = -1; + + /** + * Creates a new OrientationEventListener. + * + * @param context for the OrientationEventListener. + */ + public OrientationEventListener(Context context) { + this(context, SensorManager.SENSOR_DELAY_NORMAL); + } + + /** + * Creates a new OrientationEventListener. + * + * @param context for the OrientationEventListener. + * @param rate at which sensor events are processed (see also + * {@link android.hardware.SensorManager SensorManager}). Use the default + * value of {@link android.hardware.SensorManager#SENSOR_DELAY_NORMAL + * SENSOR_DELAY_NORMAL} for simple screen orientation change detection. + */ + public OrientationEventListener(Context context, int rate) { + mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); + mRate = rate; + mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + if (mSensor != null) { + // Create listener only if sensors do exist + mSensorEventListener = new SensorEventListenerImpl(); + } + } + + void registerListener(OrientationListener lis) { + mOldListener = lis; + } + + /** + * Enables the OrientationEventListener so it will monitor the sensor and call + * {@link #onOrientationChanged} when the device orientation changes. + */ + public void enable() { + if (mSensor == null) { + Log.w(TAG, "Cannot detect sensors. Not enabled"); + return; + } + if (mEnabled == false) { + if (localLOGV) Log.d(TAG, "OrientationEventListener enabled"); + mSensorManager.registerListener(mSensorEventListener, mSensor, mRate); + mEnabled = true; + } + } + + /** + * Disables the OrientationEventListener. + */ + public void disable() { + if (mSensor == null) { + Log.w(TAG, "Cannot detect sensors. Invalid disable"); + return; + } + if (mEnabled == true) { + if (localLOGV) Log.d(TAG, "OrientationEventListener disabled"); + mSensorManager.unregisterListener(mSensorEventListener); + mEnabled = false; + } + } + + class SensorEventListenerImpl implements SensorEventListener { + private static final int _DATA_X = 0; + private static final int _DATA_Y = 1; + private static final int _DATA_Z = 2; + + public void onSensorChanged(SensorEvent event) { + float[] values = event.values; + int orientation = ORIENTATION_UNKNOWN; + float X = -values[_DATA_X]; + float Y = -values[_DATA_Y]; + float Z = -values[_DATA_Z]; + float magnitude = X*X + Y*Y; + // Don't trust the angle if the magnitude is small compared to the y value + if (magnitude * 4 >= Z*Z) { + float OneEightyOverPi = 57.29577957855f; + float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi; + orientation = 90 - (int)Math.round(angle); + // normalize to 0 - 359 range + while (orientation >= 360) { + orientation -= 360; + } + while (orientation < 0) { + orientation += 360; + } + } + if (mOldListener != null) { + mOldListener.onSensorChanged(Sensor.TYPE_ACCELEROMETER, event.values); + } + if (orientation != mOrientation) { + mOrientation = orientation; + onOrientationChanged(orientation); + } + } + + public void onAccuracyChanged(Sensor sensor, int accuracy) { + + } + } + + /* + * Returns true if sensor is enabled and false otherwise + */ + public boolean canDetectOrientation() { + return mSensor != null; + } + + /** + * Called when the orientation of the device has changed. + * orientation parameter is in degrees, ranging from 0 to 359. + * orientation is 0 degrees when the device is oriented in its natural position, + * 90 degrees when its left side is at the top, 180 degrees when it is upside down, + * and 270 degrees when its right side is to the top. + * {@link #ORIENTATION_UNKNOWN} is returned when the device is close to flat + * and the orientation cannot be determined. + * + * @param orientation The new orientation of the device. + * + * @see #ORIENTATION_UNKNOWN + */ + abstract public void onOrientationChanged(int orientation); +} diff --git a/core/java/android/view/OrientationListener.java b/core/java/android/view/OrientationListener.java index 974c2e83565a356b739e18228c0de0b3affb8ac0..ce8074e2ad6f931033dfdf73cb70cd80991903f2 100644 --- a/core/java/android/view/OrientationListener.java +++ b/core/java/android/view/OrientationListener.java @@ -18,23 +18,16 @@ package android.view; import android.content.Context; import android.hardware.SensorListener; -import android.hardware.SensorManager; -import android.util.Config; -import android.util.Log; /** * Helper class for receiving notifications from the SensorManager when * the orientation of the device has changed. + * @deprecated use {@link android.view.OrientationEventListener} instead. + * This class internally uses the OrientationEventListener. */ +@Deprecated public abstract class OrientationListener implements SensorListener { - - private static final String TAG = "OrientationListener"; - private static final boolean DEBUG = false; - private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV; - private SensorManager mSensorManager; - private int mOrientation = ORIENTATION_UNKNOWN; - private boolean mEnabled = false; - private int mRate; + private OrientationEventListener mOrientationEventLis; /** * Returned from onOrientationChanged when the device orientation cannot be determined @@ -42,7 +35,7 @@ public abstract class OrientationListener implements SensorListener { * * @see #onOrientationChanged */ - public static final int ORIENTATION_UNKNOWN = -1; + public static final int ORIENTATION_UNKNOWN = OrientationEventListener.ORIENTATION_UNKNOWN; /** * Creates a new OrientationListener. @@ -50,8 +43,7 @@ public abstract class OrientationListener implements SensorListener { * @param context for the OrientationListener. */ public OrientationListener(Context context) { - mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); - mRate = SensorManager.SENSOR_DELAY_NORMAL; + mOrientationEventLis = new OrientationEventListenerInternal(context); } /** @@ -64,78 +56,55 @@ public abstract class OrientationListener implements SensorListener { * SENSOR_DELAY_NORMAL} for simple screen orientation change detection. */ public OrientationListener(Context context, int rate) { - mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); - mRate = rate; + mOrientationEventLis = new OrientationEventListenerInternal(context, rate); } - + + class OrientationEventListenerInternal extends OrientationEventListener { + OrientationEventListenerInternal(Context context) { + super(context); + } + + OrientationEventListenerInternal(Context context, int rate) { + super(context, rate); + // register so that onSensorChanged gets invoked + registerListener(OrientationListener.this); + } + + public void onOrientationChanged(int orientation) { + OrientationListener.this.onOrientationChanged(orientation); + } + } + /** * Enables the OrientationListener so it will monitor the sensor and call * {@link #onOrientationChanged} when the device orientation changes. */ public void enable() { - if (mEnabled == false) { - if (localLOGV) Log.d(TAG, "OrientationListener enabled"); - mSensorManager.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, mRate); - mEnabled = true; - } + mOrientationEventLis.enable(); } /** * Disables the OrientationListener. */ public void disable() { - if (mEnabled == true) { - if (localLOGV) Log.d(TAG, "OrientationListener disabled"); - mSensorManager.unregisterListener(this); - mEnabled = false; - } + mOrientationEventLis.disable(); } - - /** - * - */ + + public void onAccuracyChanged(int sensor, int accuracy) { + } + public void onSensorChanged(int sensor, float[] values) { - int orientation = ORIENTATION_UNKNOWN; - float X = values[SensorManager.RAW_DATA_X]; - float Y = values[SensorManager.RAW_DATA_Y]; - float Z = values[SensorManager.RAW_DATA_Z]; - float magnitude = X*X + Y*Y; - // Don't trust the angle if the magnitude is small compared to the y value - if (magnitude * 4 >= Z*Z) { - float OneEightyOverPi = 57.29577957855f; - float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi; - orientation = 90 - (int)Math.round(angle); - // normalize to 0 - 359 range - while (orientation >= 360) { - orientation -= 360; - } - while (orientation < 0) { - orientation += 360; - } - } - - if (orientation != mOrientation) { - mOrientation = orientation; - onOrientationChanged(orientation); - } + // just ignore the call here onOrientationChanged is invoked anyway } - public void onAccuracyChanged(int sensor, int accuracy) { - // TODO Auto-generated method stub - } /** - * Called when the orientation of the device has changed. - * orientation parameter is in degrees, ranging from 0 to 359. - * orientation is 0 degrees when the device is oriented in its natural position, - * 90 degrees when its left side is at the top, 180 degrees when it is upside down, - * and 270 degrees when its right side is to the top. - * {@link #ORIENTATION_UNKNOWN} is returned when the device is close to flat - * and the orientation cannot be determined. - * + * Look at {@link android.view.OrientationEventListener#onOrientationChanged} + * for method description and usage * @param orientation The new orientation of the device. * * @see #ORIENTATION_UNKNOWN */ abstract public void onOrientationChanged(int orientation); + } diff --git a/location/java/com/android/internal/location/protocol/GrectangleMessageTypes.java b/core/java/android/view/RemotableViewMethod.java similarity index 59% rename from location/java/com/android/internal/location/protocol/GrectangleMessageTypes.java rename to core/java/android/view/RemotableViewMethod.java index aeb0047f954f6d17ad74d138955d1d2fd5f1c400..4318290affc472e93eb08939e7c84e451ca28a42 100644 --- a/location/java/com/android/internal/location/protocol/GrectangleMessageTypes.java +++ b/core/java/android/view/RemotableViewMethod.java @@ -14,19 +14,22 @@ * limitations under the License. */ -package com.android.internal.location.protocol; +package android.view; -import com.google.common.io.protocol.ProtoBufType; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @hide + * This annotation indicates that a method on a subclass of View + * is alllowed to be used with the {@link android.widget.RemoteViews} mechanism. + */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface RemotableViewMethod { +} -public class GrectangleMessageTypes { - public static final ProtoBufType GRECTANGLE = new ProtoBufType(); - static { - GRECTANGLE - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_MESSAGE, - GRectangle.LOWER_LEFT, GlatlngMessageTypes.GLAT_LNG) - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_MESSAGE, - GRectangle.UPPER_RIGHT, GlatlngMessageTypes.GLAT_LNG); - } -} diff --git a/core/java/android/view/SurfaceHolder.java b/core/java/android/view/SurfaceHolder.java index 21a72e7184fe7f3ed54184719755a3a15e78b5a8..3d0dda3db48be492b6a63390f3b7e7b5163fcf74 100644 --- a/core/java/android/view/SurfaceHolder.java +++ b/core/java/android/view/SurfaceHolder.java @@ -240,7 +240,7 @@ public interface SurfaceHolder { * in particular there is no guarantee that the content of the Surface * will remain unchanged when lockCanvas() is called again. * - * @see android.view.SurfaceHolder.lockCanvas + * @see #lockCanvas() * * @param canvas The Canvas previously returned by lockCanvas(). */ diff --git a/core/java/android/view/TouchDelegate.java b/core/java/android/view/TouchDelegate.java index 057df92ecf93c0a770b80688a137cb7c007ccdcf..27b49dbb377c348236fa784f4e8a4ce8d65a93b6 100644 --- a/core/java/android/view/TouchDelegate.java +++ b/core/java/android/view/TouchDelegate.java @@ -77,7 +77,9 @@ public class TouchDelegate { * actual extent. */ public static final int TO_RIGHT = 8; - + + private int mSlop; + /** * Constructor * @@ -87,10 +89,10 @@ public class TouchDelegate { */ public TouchDelegate(Rect bounds, View delegateView) { mBounds = bounds; - - int slop = ViewConfiguration.getTouchSlop(); + + mSlop = ViewConfiguration.get(delegateView.getContext()).getScaledTouchSlop(); mSlopBounds = new Rect(bounds); - mSlopBounds.inset(-slop, -slop); + mSlopBounds.inset(-mSlop, -mSlop); mDelegateView = delegateView; } @@ -141,7 +143,7 @@ public class TouchDelegate { } else { // Offset event coordinates to be outside the target view (in case it does // something like tracking pressed state) - int slop = ViewConfiguration.getTouchSlop(); + int slop = mSlop; event.setLocation(-(slop * 2), -(slop * 2)); } handled = delegateView.dispatchTouchEvent(event); diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java index 85f482c61cf9cbe27526cc512aed4cb3a77a6135..c3e00c40d941c3991966e40d58c4d3e9f343e24f 100644 --- a/core/java/android/view/View.java +++ b/core/java/android/view/View.java @@ -57,15 +57,35 @@ import com.android.internal.view.menu.MenuBuilder; import java.util.ArrayList; import java.util.Arrays; +import java.lang.ref.SoftReference; /** *

          - * The View class represents the basic UI building block. A view + * This class represents the basic building block for user interface components. A View * occupies a rectangular area on the screen and is responsible for drawing and - * event handling. View is the base class for widgets, - * used to create interactive graphical user interfaces. + * event handling. View is the base class for widgets, which are + * used to create interactive UI components (buttons, text fields, etc.). The + * {@link android.view.ViewGroup} subclass is the base class for layouts, which + * are invisible containers that hold other Views (or other ViewGroups) and define + * their layout properties. *

          * + *
          + *

          For an introduction to using this class to develop your + * application's user interface, read the Developer Guide documentation on + * User Interface. Special topics + * include: + *
          Declaring Layout + *
          Creating Menus + *
          Common Layout Objects + *
          Binding to Data with AdapterView + *
          Handling UI Events + *
          Applying Styles and Themes + *
          Building Custom Components + *
          How Android Draws Views. + *

          + *
          + * * *

          Using Views

          *

          @@ -816,6 +836,12 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ public static final int SOUND_EFFECTS_ENABLED = 0x08000000; + /** + * View flag indicating whether this view should have haptic feedback + * enabled for events such as long presses. + */ + public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; + /** * Use with {@link #focusSearch}. Move focus to the previous selectable * item. @@ -1308,6 +1334,14 @@ public class View implements Drawable.Callback, KeyEvent.Callback { static final int HAS_BOUNDS = 0x00000010; /** {@hide} */ static final int DRAWN = 0x00000020; + /** + * When this flag is set, this view is running an animation on behalf of its + * children and should therefore not cancel invalidate requests, even if they + * lie outside of this view's bounds. + * + * {@hide} + */ + static final int DRAW_ANIMATION = 0x00000040; /** {@hide} */ static final int SKIP_DRAW = 0x00000080; /** {@hide} */ @@ -1353,8 +1387,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ static final int SCROLL_CONTAINER_ADDED = 0x00100000; - // Note: flag 0x00000040 is available - /** * The parent this view is attached to. * {@hide} @@ -1479,8 +1511,14 @@ public class View implements Drawable.Callback, KeyEvent.Callback { @ViewDebug.ExportedProperty int mUserPaddingBottom; - private int mOldWidthMeasureSpec = Integer.MIN_VALUE; - private int mOldHeightMeasureSpec = Integer.MIN_VALUE; + /** + * @hide + */ + int mOldWidthMeasureSpec = Integer.MIN_VALUE; + /** + * @hide + */ + int mOldHeightMeasureSpec = Integer.MIN_VALUE; private Resources mResources = null; @@ -1532,7 +1570,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { private int[] mDrawableState = null; - private Bitmap mDrawingCache; + private SoftReference mDrawingCache; /** * When this view has focus and the next focus is {@link #FOCUS_LEFT}, @@ -1559,6 +1597,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { private int mNextFocusDownId = View.NO_ID; private CheckForLongPress mPendingCheckForLongPress; + private UnsetPressedState mUnsetPressedState; /** * Whether the long press's action has been invoked. The tap's action is invoked on the @@ -1611,6 +1650,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { public View(Context context) { mContext = context; mResources = context != null ? context.getResources() : null; + mViewFlags = SOUND_EFFECTS_ENABLED|HAPTIC_FEEDBACK_ENABLED; ++sInstanceCount; } @@ -1677,9 +1717,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback { int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; - viewFlagValues |= SOUND_EFFECTS_ENABLED; - viewFlagMasks |= SOUND_EFFECTS_ENABLED; - final int N = a.getIndexCount(); for (int i = 0; i < N; i++) { int attr = a.getIndex(i); @@ -1775,6 +1812,11 @@ public class View implements Drawable.Callback, KeyEvent.Callback { viewFlagValues &= ~SOUND_EFFECTS_ENABLED; viewFlagMasks |= SOUND_EFFECTS_ENABLED; } + case com.android.internal.R.styleable.View_hapticFeedbackEnabled: + if (!a.getBoolean(attr, true)) { + viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; + viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; + } case R.styleable.View_scrollbars: final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); if (scrollbars != SCROLLBARS_NONE) { @@ -1898,7 +1940,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback { initScrollCache(); mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( - R.styleable.View_fadingEdgeLength, ViewConfiguration.getFadingEdgeLength()); + R.styleable.View_fadingEdgeLength, + ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); } /** @@ -2013,36 +2056,38 @@ public class View implements Drawable.Callback, KeyEvent.Callback { mScrollCache.scrollBar = new ScrollBarDrawable(); } - mScrollCache.scrollBarSize = a.getDimensionPixelSize( + final ScrollabilityCache scrollabilityCache = mScrollCache; + + scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( com.android.internal.R.styleable.View_scrollbarSize, - ViewConfiguration.getScrollBarSize()); + ViewConfiguration.get(mContext).getScaledScrollBarSize()); Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); - mScrollCache.scrollBar.setHorizontalTrackDrawable(track); + scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); if (thumb != null) { - mScrollCache.scrollBar.setHorizontalThumbDrawable(thumb); + scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); } boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, false); if (alwaysDraw) { - mScrollCache.scrollBar.setAlwaysDrawHorizontalTrack(true); + scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); } track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); - mScrollCache.scrollBar.setVerticalTrackDrawable(track); + scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); if (thumb != null) { - mScrollCache.scrollBar.setVerticalThumbDrawable(thumb); + scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); } alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, false); if (alwaysDraw) { - mScrollCache.scrollBar.setAlwaysDrawVerticalTrack(true); + scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); } // Re-apply user/background padding so that scrollbar(s) get added @@ -2056,7 +2101,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ private void initScrollCache() { if (mScrollCache == null) { - mScrollCache = new ScrollabilityCache(); + mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext)); } } @@ -2153,6 +2198,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback { if (!handled) { handled = showContextMenu(); } + if (handled) { + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + } return handled; } @@ -2619,9 +2667,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @attr ref android.R.styleable#View_visibility */ @ViewDebug.ExportedProperty(mapping = { - @ViewDebug.IntToString(from = 0, to = "VISIBLE"), - @ViewDebug.IntToString(from = 4, to = "INVISIBLE"), - @ViewDebug.IntToString(from = 8, to = "GONE") + @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), + @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), + @ViewDebug.IntToString(from = GONE, to = "GONE") }) public int getVisibility() { return mViewFlags & VISIBILITY_MASK; @@ -2633,8 +2681,10 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. * @attr ref android.R.styleable#View_visibility */ + @RemotableViewMethod public void setVisibility(int visibility) { setFlags(visibility, VISIBILITY_MASK); + if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); } /** @@ -2712,7 +2762,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * Set whether this view should have sound effects enabled for events such as * clicking and touching. * - * You may wish to disable sound effects for a view if you already play sounds, + *

          You may wish to disable sound effects for a view if you already play sounds, * for instance, a dial key that plays dtmf tones. * * @param soundEffectsEnabled whether sound effects are enabled for this view. @@ -2737,6 +2787,35 @@ public class View implements Drawable.Callback, KeyEvent.Callback { return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); } + /** + * Set whether this view should have haptic feedback for events such as + * long presses. + * + *

          You may wish to disable haptic feedback if your view already controls + * its own haptic feedback. + * + * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. + * @see #isHapticFeedbackEnabled() + * @see #performHapticFeedback(int) + * @attr ref android.R.styleable#View_hapticFeedbackEnabled + */ + public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { + setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); + } + + /** + * @return whether this view should have haptic feedback enabled for events + * long presses. + * + * @see #setHapticFeedbackEnabled(boolean) + * @see #performHapticFeedback(int) + * @attr ref android.R.styleable#View_hapticFeedbackEnabled + */ + @ViewDebug.ExportedProperty + public boolean isHapticFeedbackEnabled() { + return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); + } + /** * If this view doesn't do any drawing on its own, set this flag to * allow further optimizations. By default, this flag is not set on @@ -3194,14 +3273,31 @@ public class View implements Drawable.Callback, KeyEvent.Callback { return false; } + /** + * This is called when a container is going to temporarily detach a child + * that currently has focus, with + * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. + * It will either be followed by {@link #onFinishTemporaryDetach()} or + * {@link #onDetachedFromWindow()} when the container is done. Generally + * this is currently only done ListView for a view with focus. + */ + public void onStartTemporaryDetach() { + } + + /** + * Called after {@link #onStartTemporaryDetach} when the container is done + * changing the view. + */ + public void onFinishTemporaryDetach() { + } + /** * capture information of this view for later analysis: developement only * check dynamic switch to make sure we only dump view * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set */ private static void captureViewInfo(String subTag, View v) { - if (v == null || - SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) { + if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) { return; } ViewDebug.dumpCapturedView(subTag, v); @@ -3410,6 +3506,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } void performCollectViewAttributes(int visibility) { + //noinspection PointlessBitwiseExpression if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON)) == (VISIBLE | KEEP_SCREEN_ON)) { mAttachInfo.mKeepScreenOn = true; @@ -3571,8 +3668,15 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * would make sense to automatically display a soft input window for * it. Subclasses should override this if they implement * {@link #onCreateInputConnection(EditorInfo)} to return true if - * a call on that method would return a non-null InputConnection. The - * default implementation always returns false. + * a call on that method would return a non-null InputConnection, and + * they are really a first-class editor that the user would normally + * start typing on when the go into a window containing your view. + * + *

          The default implementation always returns false. This does + * not mean that its {@link #onCreateInputConnection(EditorInfo)} + * will not be called or the user can not otherwise perform edits on your + * view; it is just a hint to the system that this is not the primary + * purpose of this view. * * @return Returns true if this view is a text editor, else false. */ @@ -3596,6 +3700,20 @@ public class View implements Drawable.Callback, KeyEvent.Callback { return null; } + /** + * Called by the {@link android.view.inputmethod.InputMethodManager} + * when a view who is not the current + * input connection target is trying to make a call on the manager. The + * default implementation returns false; you can override this to return + * true for certain views if you are performing InputConnection proxying + * to them. + * @param view The View that is making the InputMethodManager call. + * @return Return true to allow the call, false to reject. + */ + public boolean checkInputConnectionProxy(View view) { + return false; + } + /** * Show the context menu for this view. It is not safe to hold on to the * menu after returning from this method. @@ -3708,10 +3826,13 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } } - final UnsetPressedState unsetPressedState = new UnsetPressedState(); - if (!post(unsetPressedState)) { + if (mUnsetPressedState == null) { + mUnsetPressedState = new UnsetPressedState(); + } + + if (!post(mUnsetPressedState)) { // If the post failed, unpress right now - unsetPressedState.run(); + mUnsetPressedState.run(); } } break; @@ -3734,7 +3855,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { final int y = (int) event.getY(); // Be lenient about moving outside of buttons - int slop = ViewConfiguration.getTouchSlop(); + int slop = ViewConfiguration.get(mContext).getScaledTouchSlop(); if ((x < 0 - slop) || (x >= getWidth() + slop) || (y < 0 - slop) || (y >= getHeight() + slop)) { // Outside button @@ -3874,25 +3995,16 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { - if (mDrawingCache != null) { - mDrawingCache.recycle(); - } - mDrawingCache = null; + destroyDrawingCache(); } if ((changed & DRAWING_CACHE_ENABLED) != 0) { - if (mDrawingCache != null) { - mDrawingCache.recycle(); - } - mDrawingCache = null; + destroyDrawingCache(); mPrivateFlags &= ~DRAWING_CACHE_VALID; } if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { - if (mDrawingCache != null) { - mDrawingCache.recycle(); - } - mDrawingCache = null; + destroyDrawingCache(); mPrivateFlags &= ~DRAWING_CACHE_VALID; } @@ -3941,6 +4053,11 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ protected void onScrollChanged(int l, int t, int oldl, int oldt) { mBackgroundSizeChanged = true; + + final AttachInfo ai = mAttachInfo; + if (ai != null) { + ai.mViewScrollChanged = true; + } } /** @@ -4413,14 +4530,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @see #invalidate() */ public void postInvalidate() { - // We try only with the AttachInfo because there's no point in invalidating - // if we are not attached to our window - if (mAttachInfo != null) { - Message msg = Message.obtain(); - msg.what = AttachInfo.INVALIDATE_MSG; - msg.obj = this; - mAttachInfo.mHandler.sendMessage(msg); - } + postInvalidateDelayed(0); } /** @@ -4436,16 +4546,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @see #invalidate(Rect) */ public void postInvalidate(int left, int top, int right, int bottom) { - // We try only with the AttachInfo because there's no point in invalidating - // if we are not attached to our window - if (mAttachInfo != null) { - Message msg = Message.obtain(); - msg.what = AttachInfo.INVALIDATE_RECT_MSG; - msg.obj = this; - msg.arg1 = (left << 16) | (top & 0xFFFF); - msg.arg2 = (right << 16) | (bottom & 0xFFFF); - mAttachInfo.mHandler.sendMessage(msg); - } + postInvalidateDelayed(0, left, top, right, bottom); } /** @@ -4477,16 +4578,22 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @param right The right coordinate of the rectangle to invalidate. * @param bottom The bottom coordinate of the rectangle to invalidate. */ - public void postInvalidateDelayed(long delayMilliseconds, int left, int top - , int right, int bottom) { + public void postInvalidateDelayed(long delayMilliseconds, int left, int top, + int right, int bottom) { + // We try only with the AttachInfo because there's no point in invalidating // if we are not attached to our window if (mAttachInfo != null) { - Message msg = Message.obtain(); + final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); + info.target = this; + info.left = left; + info.top = top; + info.right = right; + info.bottom = bottom; + + final Message msg = Message.obtain(); msg.what = AttachInfo.INVALIDATE_RECT_MSG; - msg.obj = this; - msg.arg1 = (left << 16) | (top & 0xFFFF); - msg.arg2 = (right << 16) | (bottom & 0xFFFF); + msg.obj = info; mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); } } @@ -4865,7 +4972,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback { final boolean drawHorizontalScrollBar = (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; final boolean drawVerticalScrollBar = - (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; + (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL + && !isVerticalScrollBarHidden(); if (drawVerticalScrollBar || drawHorizontalScrollBar) { final int width = mRight - mLeft; @@ -4887,6 +4995,16 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } } } + + /** + * Override this if the vertical scrollbar needs to be hidden in a subclass, like when + * FastScroller is visible. + * @return whether to temporarily hide the vertical scrollbar + * @hide + */ + protected boolean isVerticalScrollBarHidden() { + return false; + } /** *

          Draw the horizontal scrollbar if @@ -4924,7 +5042,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL ? getVerticalScrollbarWidth() : 0; - scrollBar.setBounds(scrollX + (mPaddingLeft & inside) + getScrollBarPaddingLeft(), top, + scrollBar.setBounds(scrollX + (mPaddingLeft & inside), top, scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap, top + size); scrollBar.setParameters( computeHorizontalScrollRange(), @@ -5022,6 +5140,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { if (mPendingCheckForLongPress != null) { removeCallbacks(mPendingCheckForLongPress); } + destroyDrawingCache(); } /** @@ -5332,11 +5451,10 @@ public class View implements Drawable.Callback, KeyEvent.Callback { if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { return null; } - if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED && - ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDrawingCache == null)) { + if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { buildDrawingCache(); } - return mDrawingCache; + return mDrawingCache == null ? null : mDrawingCache.get(); } /** @@ -5351,7 +5469,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ public void destroyDrawingCache() { if (mDrawingCache != null) { - mDrawingCache.recycle(); + final Bitmap bitmap = mDrawingCache.get(); + if (bitmap != null) bitmap.recycle(); mDrawingCache = null; } } @@ -5391,7 +5510,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @see #destroyDrawingCache() */ public void buildDrawingCache() { - if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDrawingCache == null) { + if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDrawingCache == null || + mDrawingCache.get() == null) { + if (ViewDebug.TRACE_HIERARCHY) { ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); } @@ -5408,16 +5529,13 @@ public class View implements Drawable.Callback, KeyEvent.Callback { if (width <= 0 || height <= 0 || (width * height * (opaque ? 2 : 4) >= // Projected bitmap size in bytes - ViewConfiguration.getMaximumDrawingCacheSize())) { - if (mDrawingCache != null) { - mDrawingCache.recycle(); - } - mDrawingCache = null; + ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { + destroyDrawingCache(); return; } boolean clear = true; - Bitmap bitmap = mDrawingCache; + Bitmap bitmap = mDrawingCache == null ? null : mDrawingCache.get(); if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { @@ -5442,12 +5560,11 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } // Try to cleanup memory - if (mDrawingCache != null) { - mDrawingCache.recycle(); - } + if (bitmap != null) bitmap.recycle(); try { - mDrawingCache = bitmap = Bitmap.createBitmap(width, height, quality); + bitmap = Bitmap.createBitmap(width, height, quality); + mDrawingCache = new SoftReference(bitmap); } catch (OutOfMemoryError e) { // If there is not enough memory to create the bitmap cache, just // ignore the issue as bitmap caches are not required to draw the @@ -5485,9 +5602,10 @@ public class View implements Drawable.Callback, KeyEvent.Callback { final int restoreCount = canvas.save(); canvas.translate(-mScrollX, -mScrollY); + mPrivateFlags |= DRAWN; + // Fast path for layouts with no backgrounds if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { - mPrivateFlags |= DRAWN; if (ViewDebug.TRACE_HIERARCHY) { ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); } @@ -5616,6 +5734,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback { ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); } + mPrivateFlags |= DRAWN; + /* * Draw traversal performs several drawing steps which must be executed * in the appropriate order: @@ -5656,7 +5776,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback { boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; if (!verticalEdges && !horizontalEdges) { // Step 3, draw the content - mPrivateFlags |= DRAWN; onDraw(canvas); // Step 4, draw the children @@ -5760,7 +5879,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } // Step 3, draw the content - mPrivateFlags |= DRAWN; onDraw(canvas); // Step 4, draw the children @@ -6411,32 +6529,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback { return mBGDrawable; } - private int getScrollBarPaddingLeft() { - // TODO: Deal with RTL languages - return 0; - } - - /* - * Returns the pixels occupied by the vertical scrollbar, if not overlaid - */ - private int getScrollBarPaddingRight() { - // TODO: Deal with RTL languages - if ((mViewFlags & SCROLLBARS_VERTICAL) == 0) { - return 0; - } - return (mViewFlags & SCROLLBARS_INSET_MASK) == 0 ? 0 : getVerticalScrollbarWidth(); - } - - /* - * Returns the pixels occupied by the horizontal scrollbar, if not overlaid - */ - private int getScrollBarPaddingBottom() { - if ((mViewFlags & SCROLLBARS_HORIZONTAL) == 0) { - return 0; - } - return (mViewFlags & SCROLLBARS_INSET_MASK) == 0 ? 0 : getHorizontalScrollbarHeight(); - } - /** * Sets the padding. The view may add on the space required to display * the scrollbars, depending on the style and visibility of the scrollbars. @@ -6460,7 +6552,22 @@ public class View implements Drawable.Callback, KeyEvent.Callback { mUserPaddingRight = right; mUserPaddingBottom = bottom; - if (mPaddingLeft != left + getScrollBarPaddingLeft()) { + final int viewFlags = mViewFlags; + + // Common case is there are no scroll bars. + if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { + // TODO: Deal with RTL languages to adjust left padding instead of right. + if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { + right += (viewFlags & SCROLLBARS_INSET_MASK) == 0 + ? 0 : getVerticalScrollbarWidth(); + } + if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) { + bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 + ? 0 : getHorizontalScrollbarHeight(); + } + } + + if (mPaddingLeft != left) { changed = true; mPaddingLeft = left; } @@ -6468,13 +6575,13 @@ public class View implements Drawable.Callback, KeyEvent.Callback { changed = true; mPaddingTop = top; } - if (mPaddingRight != right + getScrollBarPaddingRight()) { + if (mPaddingRight != right) { changed = true; - mPaddingRight = right + getScrollBarPaddingRight(); + mPaddingRight = right; } - if (mPaddingBottom != bottom + getScrollBarPaddingBottom()) { + if (mPaddingBottom != bottom) { changed = true; - mPaddingBottom = bottom + getScrollBarPaddingBottom(); + mPaddingBottom = bottom; } if (changed) { @@ -7275,20 +7382,57 @@ public class View implements Drawable.Callback, KeyEvent.Callback { /** * Play a sound effect for this view. * - * The framework will play sound effects for some built in actions, such as + *

          The framework will play sound effects for some built in actions, such as * clicking, but you may wish to play these effects in your widget, * for instance, for internal navigation. * - * The sound effect will only be played if sound effects are enabled by the user, and + *

          The sound effect will only be played if sound effects are enabled by the user, and * {@link #isSoundEffectsEnabled()} is true. * * @param soundConstant One of the constants defined in {@link SoundEffectConstants} */ - protected void playSoundEffect(int soundConstant) { - if (mAttachInfo == null || mAttachInfo.mSoundEffectPlayer == null || !isSoundEffectsEnabled()) { + public void playSoundEffect(int soundConstant) { + if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { return; } - mAttachInfo.mSoundEffectPlayer.playSoundEffect(soundConstant); + mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); + } + + /** + * Provide haptic feedback to the user for this view. + * + *

          The framework will provide haptic feedback for some built in actions, + * such as long presses, but you may wish to provide feedback for your + * own widget. + * + *

          The feedback will only be performed if + * {@link #isHapticFeedbackEnabled()} is true. + * + * @param feedbackConstant One of the constants defined in + * {@link HapticFeedbackConstants} + */ + public boolean performHapticFeedback(int feedbackConstant) { + return performHapticFeedback(feedbackConstant, 0); + } + + /** + * Like {@link #performHapticFeedback(int)}, with additional options. + * + * @param feedbackConstant One of the constants defined in + * {@link HapticFeedbackConstants} + * @param flags Additional flags as per {@link HapticFeedbackConstants}. + */ + public boolean performHapticFeedback(int feedbackConstant, int flags) { + if (mAttachInfo == null) { + return false; + } + if ((flags&HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 + && !isHapticFeedbackEnabled()) { + return false; + } + return mAttachInfo.mRootCallbacks.performHapticFeedback( + feedbackConstant, + (flags&HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); } /** @@ -7667,8 +7811,70 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ static class AttachInfo { - interface SoundEffectPlayer { + interface Callbacks { void playSoundEffect(int effectId); + boolean performHapticFeedback(int effectId, boolean always); + } + + /** + * InvalidateInfo is used to post invalidate(int, int, int, int) messages + * to a Handler. This class contains the target (View) to invalidate and + * the coordinates of the dirty rectangle. + * + * For performance purposes, this class also implements a pool of up to + * POOL_LIMIT objects that get reused. This reduces memory allocations + * whenever possible. + * + * The pool is implemented as a linked list of InvalidateInfo object with + * the root pointing to the next available InvalidateInfo. If the root + * is null (i.e. when all instances from the pool have been acquired), + * then a new InvalidateInfo is created and returned to the caller. + * + * An InvalidateInfo is sent back to the pool by calling its release() + * method. If the pool is full the object is simply discarded. + * + * This implementation follows the object pool pattern used in the + * MotionEvent class. + */ + static class InvalidateInfo { + private static final int POOL_LIMIT = 10; + private static final Object sLock = new Object(); + + private static int sAcquiredCount = 0; + private static InvalidateInfo sRoot; + + private InvalidateInfo next; + + View target; + + int left; + int top; + int right; + int bottom; + + static InvalidateInfo acquire() { + synchronized (sLock) { + if (sRoot == null) { + return new InvalidateInfo(); + } + + InvalidateInfo info = sRoot; + sRoot = info.next; + sAcquiredCount--; + + return info; + } + } + + void release() { + synchronized (sLock) { + if (sAcquiredCount < POOL_LIMIT) { + sAcquiredCount++; + next = sRoot; + sRoot = this; + } + } + } } final IWindowSession mSession; @@ -7677,7 +7883,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { final IBinder mWindowToken; - final SoundEffectPlayer mSoundEffectPlayer; + final Callbacks mRootCallbacks; /** * The top view of the hierarchy. @@ -7770,6 +7976,11 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ boolean mViewVisibilityChanged; + /** + * Set to true if a view has been scrolled. + */ + boolean mViewScrollChanged; + /** * Global to the view hierarchy used as a temporary for dealing with * x/y points in the transparent region computations. @@ -7824,12 +8035,12 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @param handler the events handler the view must use */ AttachInfo(IWindowSession session, IWindow window, - Handler handler, SoundEffectPlayer effectPlayer) { + Handler handler, Callbacks effectPlayer) { mSession = session; mWindow = window; mWindowToken = window.asBinder(); mHandler = handler; - mSoundEffectPlayer = effectPlayer; + mRootCallbacks = effectPlayer; } } @@ -7839,18 +8050,21 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * instances of View.

          */ private static class ScrollabilityCache { - public int fadingEdgeLength = ViewConfiguration.getFadingEdgeLength(); + public int fadingEdgeLength; - public int scrollBarSize = ViewConfiguration.getScrollBarSize(); + public int scrollBarSize; public ScrollBarDrawable scrollBar; public final Paint paint; public final Matrix matrix; public Shader shader; - private int mLastColor = 0; + private int mLastColor; + + public ScrollabilityCache(ViewConfiguration configuration) { + fadingEdgeLength = configuration.getScaledFadingEdgeLength(); + scrollBarSize = configuration.getScaledScrollBarSize(); - public ScrollabilityCache() { paint = new Paint(); matrix = new Matrix(); // use use a height of 1, and then wack the matrix each time we @@ -7869,7 +8083,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback { shader = new LinearGradient(0, 0, 0, 1, color, 0, Shader.TileMode.CLAMP); paint.setShader(shader); - paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); + // Restore the default transfer mode (src_over) + paint.setXfermode(null); } } } diff --git a/core/java/android/view/ViewConfiguration.java b/core/java/android/view/ViewConfiguration.java index b7110ce101ab709fe4cebd175b03a34b5f6a2d79..d3f48c6a9a56e44590830b9aa41b9f650e506b5f 100644 --- a/core/java/android/view/ViewConfiguration.java +++ b/core/java/android/view/ViewConfiguration.java @@ -16,17 +16,19 @@ package android.view; +import android.content.Context; +import android.util.DisplayMetrics; +import android.util.SparseArray; + /** * Contains methods to standard constants used in the UI for timeouts, sizes, and distances. - * */ public class ViewConfiguration { - /** * Defines the width of the horizontal scrollbar and the height of the vertical scrollbar in * pixels */ - private static final int SCROLL_BAR_SIZE = 6; + private static final int SCROLL_BAR_SIZE = 10; /** * Defines the length of the fading edges in pixels @@ -54,7 +56,7 @@ public class ViewConfiguration { /** * Defines the duration in milliseconds we will wait to see if a touch event - * is a top or a scroll. If the user does not move within this interval, it is + * is a tap or a scroll. If the user does not move within this interval, it is * considered to be a tap. */ private static final int TAP_TIMEOUT = 100; @@ -65,6 +67,13 @@ public class ViewConfiguration { * considered to be a tap. */ private static final int JUMP_TAP_TIMEOUT = 500; + + /** + * Defines the duration in milliseconds between the first tap's up event and + * the second tap's down event for an interaction to be considered a + * double-tap. + */ + private static final int DOUBLE_TAP_TIMEOUT = 300; /** * Defines the duration in milliseconds we want to display zoom controls in response @@ -80,7 +89,12 @@ public class ViewConfiguration { /** * Distance a touch can wander before we think the user is scrolling in pixels */ - private static final int TOUCH_SLOP = 12; + private static final int TOUCH_SLOP = 25; + + /** + * Distance between the first touch and second touch to still be considered a double tap + */ + private static final int DOUBLE_TAP_SLOP = 100; /** * Distance a touch needs to be outside of a window's bounds for it to @@ -97,30 +111,126 @@ public class ViewConfiguration { * The maximum size of View's drawing cache, expressed in bytes. This size * should be at least equal to the size of the screen in ARGB888 format. */ - private static final int MAXIMUM_DRAWING_CACHE_SIZE = 320 * 480 * 4; // One HVGA screen, ARGB8888 + @Deprecated + private static final int MAXIMUM_DRAWING_CACHE_SIZE = 320 * 480 * 4; // HVGA screen, ARGB8888 /** * The coefficient of friction applied to flings/scrolls. */ private static float SCROLL_FRICTION = 0.015f; + private final int mEdgeSlop; + private final int mFadingEdgeLength; + private final int mMinimumFlingVelocity; + private final int mScrollbarSize; + private final int mTouchSlop; + private final int mDoubleTapSlop; + private final int mWindowTouchSlop; + private final int mMaximumDrawingCacheSize; + + private static final SparseArray sConfigurations = + new SparseArray(2); + + /** + * @deprecated Use {@link android.view.ViewConfiguration#get(android.content.Context)} instead. + */ + @Deprecated + public ViewConfiguration() { + mEdgeSlop = EDGE_SLOP; + mFadingEdgeLength = FADING_EDGE_LENGTH; + mMinimumFlingVelocity = MINIMUM_FLING_VELOCITY; + mScrollbarSize = SCROLL_BAR_SIZE; + mTouchSlop = TOUCH_SLOP; + mDoubleTapSlop = DOUBLE_TAP_SLOP; + mWindowTouchSlop = WINDOW_TOUCH_SLOP; + //noinspection deprecation + mMaximumDrawingCacheSize = MAXIMUM_DRAWING_CACHE_SIZE; + } + + /** + * Creates a new configuration for the specified context. The configuration depends on + * various parameters of the context, like the dimension of the display or the density + * of the display. + * + * @param context The application context used to initialize this view configuration. + * + * @see #get(android.content.Context) + * @see android.util.DisplayMetrics + */ + private ViewConfiguration(Context context) { + final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); + final float density = metrics.density; + + mEdgeSlop = (int) (density * EDGE_SLOP + 0.5f); + mFadingEdgeLength = (int) (density * FADING_EDGE_LENGTH + 0.5f); + mMinimumFlingVelocity = (int) (density * MINIMUM_FLING_VELOCITY + 0.5f); + mScrollbarSize = (int) (density * SCROLL_BAR_SIZE + 0.5f); + mTouchSlop = (int) (density * TOUCH_SLOP + 0.5f); + mDoubleTapSlop = (int) (density * DOUBLE_TAP_SLOP + 0.5f); + mWindowTouchSlop = (int) (density * WINDOW_TOUCH_SLOP + 0.5f); + + // Size of the screen in bytes, in ARGB_8888 format + mMaximumDrawingCacheSize = 4 * metrics.widthPixels * metrics.heightPixels; + } + + /** + * Returns a configuration for the specified context. The configuration depends on + * various parameters of the context, like the dimension of the display or the + * density of the display. + * + * @param context The application context used to initialize the view configuration. + */ + public static ViewConfiguration get(Context context) { + final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); + final int density = (int) (100.0f * metrics.density); + + ViewConfiguration configuration = sConfigurations.get(density); + if (configuration == null) { + configuration = new ViewConfiguration(context); + sConfigurations.put(density, configuration); + } + + return configuration; + } + /** * @return The width of the horizontal scrollbar and the height of the vertical * scrollbar in pixels + * + * @deprecated Use {@link #getScaledScrollBarSize()} instead. */ + @Deprecated public static int getScrollBarSize() { return SCROLL_BAR_SIZE; } /** - * @return Defines the length of the fading edges in pixels + * @return The width of the horizontal scrollbar and the height of the vertical + * scrollbar in pixels */ + public int getScaledScrollBarSize() { + return mScrollbarSize; + } + + /** + * @return the length of the fading edges in pixels + * + * @deprecated Use {@link #getScaledFadingEdgeLength()} instead. + */ + @Deprecated public static int getFadingEdgeLength() { return FADING_EDGE_LENGTH; } - + /** - * @return Defines the duration in milliseconds of the pressed state in child + * @return the length of the fading edges in pixels + */ + public int getScaledFadingEdgeLength() { + return mFadingEdgeLength; + } + + /** + * @return the duration in milliseconds of the pressed state in child * components. */ public static int getPressedStateDuration() { @@ -128,7 +238,7 @@ public class ViewConfiguration { } /** - * @return Defines the duration in milliseconds before a press turns into + * @return the duration in milliseconds before a press turns into * a long press */ public static int getLongPressTimeout() { @@ -136,8 +246,8 @@ public class ViewConfiguration { } /** - * @return Defines the duration in milliseconds we will wait to see if a touch event - * is a top or a scroll. If the user does not move within this interval, it is + * @return the duration in milliseconds we will wait to see if a touch event + * is a tap or a scroll. If the user does not move within this interval, it is * considered to be a tap. */ public static int getTapTimeout() { @@ -145,7 +255,7 @@ public class ViewConfiguration { } /** - * @return Defines the duration in milliseconds we will wait to see if a touch event + * @return the duration in milliseconds we will wait to see if a touch event * is a jump tap. If the user does not move within this interval, it is * considered to be a tap. */ @@ -153,46 +263,133 @@ public class ViewConfiguration { return JUMP_TAP_TIMEOUT; } + /** + * @return the duration in milliseconds between the first tap's up event and + * the second tap's down event for an interaction to be considered a + * double-tap. + * @hide pending API council + */ + public static int getDoubleTapTimeout() { + return DOUBLE_TAP_TIMEOUT; + } + /** * @return Inset in pixels to look for touchable content when the user touches the edge of the * screen + * + * @deprecated Use {@link #getScaledEdgeSlop()} instead. */ + @Deprecated public static int getEdgeSlop() { return EDGE_SLOP; } - + + /** + * @return Inset in pixels to look for touchable content when the user touches the edge of the + * screen + */ + public int getScaledEdgeSlop() { + return mEdgeSlop; + } + /** * @return Distance a touch can wander before we think the user is scrolling in pixels + * + * @deprecated Use {@link #getScaledTouchSlop()} instead. */ + @Deprecated public static int getTouchSlop() { return TOUCH_SLOP; } + + /** + * @return Distance a touch can wander before we think the user is scrolling in pixels + */ + public int getScaledTouchSlop() { + return mTouchSlop; + } + + /** + * @return Distance between the first touch and second touch to still be + * considered a double tap + * @deprecated Use {@link #getScaledDoubleTapSlop()} instead. + * @hide The only client of this should be GestureDetector, which needs this + * for clients that still use its deprecated constructor. + */ + @Deprecated + public static int getDoubleTapSlop() { + return DOUBLE_TAP_SLOP; + } + /** + * @return Distance between the first touch and second touch to still be + * considered a double tap + * @hide pending API council + */ + public int getScaledDoubleTapSlop() { + return mDoubleTapSlop; + } + /** * @return Distance a touch must be outside the bounds of a window for it * to be counted as outside the window for purposes of dismissing that * window. + * + * @deprecated Use {@link #getScaledWindowTouchSlop()} instead. */ + @Deprecated public static int getWindowTouchSlop() { return WINDOW_TOUCH_SLOP; } + + /** + * @return Distance a touch must be outside the bounds of a window for it + * to be counted as outside the window for purposes of dismissing that + * window. + */ + public int getScaledWindowTouchSlop() { + return mWindowTouchSlop; + } /** - * Minimum velocity to initiate a fling, as measured in pixels per second + * @return Minimum velocity to initiate a fling, as measured in pixels per second. + * + * @deprecated Use {@link #getScaledMinimumFlingVelocity()} instead. */ - public static int getMinimumFlingVelocity() { - return MINIMUM_FLING_VELOCITY; + @Deprecated + public static int getMinimumFlingVelocity() { + return MINIMUM_FLING_VELOCITY; + } + + /** + * @return Minimum velocity to initiate a fling, as measured in pixels per second. + */ + public int getScaledMinimumFlingVelocity() { + return mMinimumFlingVelocity; } /** * The maximum drawing cache size expressed in bytes. * * @return the maximum size of View's drawing cache expressed in bytes + * + * @deprecated Use {@link #getScaledMaximumDrawingCacheSize()} instead. */ + @Deprecated public static int getMaximumDrawingCacheSize() { + //noinspection deprecation return MAXIMUM_DRAWING_CACHE_SIZE; } + /** + * The maximum drawing cache size expressed in bytes. + * + * @return the maximum size of View's drawing cache expressed in bytes + */ + public int getScaledMaximumDrawingCacheSize() { + return mMaximumDrawingCacheSize; + } + /** * The amount of time that the zoom controls should be * displayed on the screen expressed in milliseconds. diff --git a/core/java/android/view/ViewDebug.java b/core/java/android/view/ViewDebug.java index 883c7bd2e5d26ce1b28e43d9f30aa69158e23aae..6ea7a82f7c92fe491ddb4282e0a035ac4704abe2 100644 --- a/core/java/android/view/ViewDebug.java +++ b/core/java/android/view/ViewDebug.java @@ -17,9 +17,12 @@ package android.view; import android.util.Log; +import android.util.DisplayMetrics; import android.content.res.Resources; import android.graphics.Bitmap; +import android.graphics.Canvas; import android.os.Environment; +import android.os.Debug; import java.io.File; import java.io.BufferedWriter; @@ -43,6 +46,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.AccessibleObject; /** * Various debugging/tracing tools related to {@link View} and the view hierarchy. @@ -73,7 +77,7 @@ public class ViewDebug { * when it is set, we log key events, touch/motion and trackball events */ static final String SYSTEM_PROPERTY_CAPTURE_EVENT = "debug.captureevent"; - + /** * This annotation can be used to mark fields and methods to be dumped by * the view server. Only non-void methods with no arguments can be annotated @@ -112,6 +116,27 @@ public class ViewDebug { */ IntToString[] mapping() default { }; + /** + * A mapping can be defined to map array indices to specific strings. + * A mapping can be used to see human readable values for the indices + * of an array: + * + *
          +         * @ViewDebug.ExportedProperty(mapping = {
          +         *     @ViewDebug.IntToString(from = 0, to = "INVALID"),
          +         *     @ViewDebug.IntToString(from = 1, to = "FIRST"),
          +         *     @ViewDebug.IntToString(from = 2, to = "SECOND")
          +         * })
          +         * private int[] mElements;
          +         * 
          +         *
          +         * @return An array of int to String mappings
          +         *
          +         * @see android.view.ViewDebug.IntToString
          +         * @see #mapping()
          +         */
          +        IntToString[] indexMapping() default { };
          +
                   /**
                    * When deep export is turned on, this property is not dumped. Instead, the
                    * properties contained in this property are dumped. Each child property
          @@ -187,10 +212,12 @@ public class ViewDebug {
               private static final String REMOTE_COMMAND_DUMP = "DUMP";
               private static final String REMOTE_COMMAND_INVALIDATE = "INVALIDATE";
               private static final String REMOTE_COMMAND_REQUEST_LAYOUT = "REQUEST_LAYOUT";
          +    private static final String REMOTE_PROFILE = "PROFILE";
           
               private static HashMap, Field[]> sFieldsForClasses;
               private static HashMap, Method[]> sMethodsForClasses;
          -        
          +    private static HashMap sAnnotations;
          +
               /**
                * Defines the type of hierarhcy trace to output to the hierarchy traces file.
                */
          @@ -347,6 +374,7 @@ public class ViewDebug {
                   }
           
                   File recyclerDump = new File(Environment.getExternalStorageDirectory(), "view-recycler/");
          +        //noinspection ResultOfMethodCallIgnored
                   recyclerDump.mkdirs();
           
                   recyclerDump = new File(recyclerDump, sRecyclerTracePrefix + ".recycler");
          @@ -450,6 +478,7 @@ public class ViewDebug {
                   }
           
                   File hierarchyDump = new File(Environment.getExternalStorageDirectory(), "view-hierarchy/");
          +        //noinspection ResultOfMethodCallIgnored
                   hierarchyDump.mkdirs();
           
                   hierarchyDump = new File(hierarchyDump, prefix + ".traces");
          @@ -497,6 +526,7 @@ public class ViewDebug {
                   sHierarchyTraces = null;
           
                   File hierarchyDump = new File(Environment.getExternalStorageDirectory(), "view-hierarchy/");
          +        //noinspection ResultOfMethodCallIgnored
                   hierarchyDump.mkdirs();
                   hierarchyDump = new File(hierarchyDump, sHierarchyTracePrefix + ".tree");
           
          @@ -538,32 +568,41 @@ public class ViewDebug {
                           invalidate(view, params[0]);
                       } else if (REMOTE_COMMAND_REQUEST_LAYOUT.equalsIgnoreCase(command)) {
                           requestLayout(view, params[0]);
          +            } else if (REMOTE_PROFILE.equalsIgnoreCase(command)) {
          +                profile(view, clientStream, params[0]);
                       }
                   }
               }
           
          -    private static View findViewByHashCode(View root, String parameter) {
          -        final String[] ids = parameter.split("@");
          -        final String className = ids[0];
          -        final int hashCode = Integer.parseInt(ids[1], 16);
          +    private static View findView(View root, String parameter) {
          +        // Look by type/hashcode
          +        if (parameter.indexOf('@') != -1) {
          +            final String[] ids = parameter.split("@");
          +            final String className = ids[0];
          +            final int hashCode = Integer.parseInt(ids[1], 16);
           
          -        View view = root.getRootView();
          -        if (view instanceof ViewGroup) {
          -            return findView((ViewGroup) view, className, hashCode);
          +            View view = root.getRootView();
          +            if (view instanceof ViewGroup) {
          +                return findView((ViewGroup) view, className, hashCode);
          +            }
          +        } else {
          +            // Look by id
          +            final int id = root.getResources().getIdentifier(parameter, null, null);
          +            return root.getRootView().findViewById(id);
                   }
           
                   return null;
               }
           
               private static void invalidate(View root, String parameter) {
          -        final View view = findViewByHashCode(root, parameter);
          +        final View view = findView(root, parameter);
                   if (view != null) {
                       view.postInvalidate();
                   }
               }
           
               private static void requestLayout(View root, String parameter) {
          -        final View view = findViewByHashCode(root, parameter);
          +        final View view = findView(root, parameter);
                   if (view != null) {
                       root.post(new Runnable() {
                           public void run() {
          @@ -573,19 +612,139 @@ public class ViewDebug {
                   }
               }
           
          -    private static void capture(View root, final OutputStream clientStream, String parameter)
          +    private static void profile(View root, OutputStream clientStream, String parameter)
                       throws IOException {
           
          +        final View view = findView(root, parameter);
          +        BufferedWriter out = null;
          +        try {
          +            out = new BufferedWriter(new OutputStreamWriter(clientStream), 32 * 1024);
          +
          +            if (view != null) {
          +                final long durationMeasure = profileViewOperation(view, new ViewOperation() {
          +                    public Void[] pre() {
          +                        forceLayout(view);
          +                        return null;
          +                    }
          +
          +                    private void forceLayout(View view) {
          +                        view.forceLayout();
          +                        if (view instanceof ViewGroup) {
          +                            ViewGroup group = (ViewGroup) view;
          +                            final int count = group.getChildCount();
          +                            for (int i = 0; i < count; i++) {
          +                                forceLayout(group.getChildAt(i));
          +                            }
          +                        }
          +                    }
          +
          +                    public void run(Void... data) {
          +                        view.measure(view.mOldWidthMeasureSpec, view.mOldHeightMeasureSpec);
          +                    }
          +
          +                    public void post(Void... data) {
          +                    }
          +                });
          +
          +                final long durationLayout = profileViewOperation(view, new ViewOperation() {
          +                    public Void[] pre() {
          +                        return null;
          +                    }
          +
          +                    public void run(Void... data) {
          +                        view.layout(view.mLeft, view.mTop, view.mRight, view.mBottom);
          +                    }
          +
          +                    public void post(Void... data) {
          +                    }
          +                });
          +
          +                final long durationDraw = profileViewOperation(view, new ViewOperation() {
          +                    public Object[] pre() {
          +                        final DisplayMetrics metrics = view.getResources().getDisplayMetrics();
          +                        final Bitmap bitmap = Bitmap.createBitmap(metrics.widthPixels,
          +                                metrics.heightPixels, Bitmap.Config.RGB_565);
          +                        final Canvas canvas = new Canvas(bitmap);
          +                        return new Object[] { bitmap, canvas };
          +                    }
          +
          +                    public void run(Object... data) {
          +                        view.draw((Canvas) data[1]);
          +                    }
          +
          +                    public void post(Object... data) {
          +                        ((Bitmap) data[0]).recycle();
          +                    }
          +                });
          +
          +                out.write(String.valueOf(durationMeasure));
          +                out.write(' ');
          +                out.write(String.valueOf(durationLayout));
          +                out.write(' ');
          +                out.write(String.valueOf(durationDraw));
          +                out.newLine();
          +            } else {
          +                out.write("-1 -1 -1");
          +                out.newLine();
          +            }
          +        } catch (Exception e) {
          +            android.util.Log.w("View", "Problem profiling the view:", e);
          +        } finally {
          +            if (out != null) {
          +                out.close();
          +            }
          +        }
          +    }
          +
          +    interface ViewOperation {
          +        T[] pre();
          +        void run(T... data);
          +        void post(T... data);
          +    }
          +
          +    private static  long profileViewOperation(View view, final ViewOperation operation) {
                   final CountDownLatch latch = new CountDownLatch(1);
          -        final View captureView = findViewByHashCode(root, parameter);
          +        final long[] duration = new long[1];
          +
          +        view.post(new Runnable() {
          +            public void run() {
          +                try {
          +                    T[] data = operation.pre();
          +                    long start = Debug.threadCpuTimeNanos();
          +                    operation.run(data);
          +                    duration[0] = Debug.threadCpuTimeNanos() - start;
          +                    operation.post(data);
          +                } finally {
          +                    latch.countDown();
          +                }
          +            }
          +        });
          +
          +        try {
          +            latch.await(CAPTURE_TIMEOUT, TimeUnit.MILLISECONDS);
          +        } catch (InterruptedException e) {
          +            Log.w("View", "Could not complete the profiling of the view " + view);
          +            Thread.currentThread().interrupt();
          +            return -1;
          +        }
          +
          +        return duration[0];
          +    }
          +
          +    private static void capture(View root, final OutputStream clientStream, String parameter)
          +            throws IOException {
          +
          +        final View captureView = findView(root, parameter);
           
                   if (captureView != null) {
          +            final CountDownLatch latch = new CountDownLatch(1);
                       final Bitmap[] cache = new Bitmap[1];
           
                       final boolean hasCache = captureView.isDrawingCacheEnabled();
                       final boolean willNotCache = captureView.willNotCacheDrawing();
           
                       if (willNotCache) {
          +                // TODO: Should happen on the UI thread
                           captureView.setWillNotCacheDrawing(false);
                       }
           
          @@ -619,12 +778,15 @@ public class ViewDebug {
                               }
                           }
                       } catch (InterruptedException e) {
          -                Log.w("View", "Could not complete the capture of the view " + captureView);                
          +                Log.w("View", "Could not complete the capture of the view " + captureView);
          +                Thread.currentThread().interrupt();
                       } finally {
                           if (willNotCache) {
          +                    // TODO: Should happen on the UI thread
                               captureView.setWillNotCacheDrawing(true);
                           }
                           if (!hasCache) {
          +                    // TODO: Should happen on the UI thread                    
                               captureView.destroyDrawingCache();
                           }
                       }
          @@ -642,6 +804,8 @@ public class ViewDebug {
                       }
                       out.write("DONE.");
                       out.newLine();
          +        } catch (Exception e) {
          +            android.util.Log.w("View", "Problem dumping the view:", e);
                   } finally {
                       if (out != null) {
                           out.close();
          @@ -713,7 +877,12 @@ public class ViewDebug {
                   if (sFieldsForClasses == null) {
                       sFieldsForClasses = new HashMap, Field[]>();
                   }
          +        if (sAnnotations == null) {
          +            sAnnotations = new HashMap(512);
          +        }
          +
                   final HashMap, Field[]> map = sFieldsForClasses;
          +        final HashMap annotations = sAnnotations;
           
                   Field[] fields = map.get(klass);
                   if (fields != null) {
          @@ -729,6 +898,7 @@ public class ViewDebug {
                       if (field.isAnnotationPresent(ExportedProperty.class)) {
                           field.setAccessible(true);
                           foundFields.add(field);
          +                annotations.put(field, field.getAnnotation(ExportedProperty.class));
                       }
                   }
           
          @@ -740,9 +910,14 @@ public class ViewDebug {
           
               private static Method[] getExportedPropertyMethods(Class klass) {
                   if (sMethodsForClasses == null) {
          -            sMethodsForClasses = new HashMap, Method[]>();
          +            sMethodsForClasses = new HashMap, Method[]>(100);
          +        }
          +        if (sAnnotations == null) {
          +            sAnnotations = new HashMap(512);
                   }
          +
                   final HashMap, Method[]> map = sMethodsForClasses;
          +        final HashMap annotations = sAnnotations;
           
                   Method[] methods = map.get(klass);
                   if (methods != null) {
          @@ -756,10 +931,11 @@ public class ViewDebug {
                   for (int i = 0; i < count; i++) {
                       final Method method = methods[i];            
                       if (method.getParameterTypes().length == 0 &&
          -                        method.isAnnotationPresent(ExportedProperty.class) &&
          -                        method.getReturnType() != Void.class) {
          +                    method.isAnnotationPresent(ExportedProperty.class) &&
          +                    method.getReturnType() != Void.class) {
                           method.setAccessible(true);
                           foundMethods.add(method);
          +                annotations.put(method, method.getAnnotation(ExportedProperty.class));
                       }
                   }
           
          @@ -799,20 +975,10 @@ public class ViewDebug {
                           final Class returnType = method.getReturnType();
           
                           if (returnType == int.class) {
          -                    ExportedProperty property = method.getAnnotation(ExportedProperty.class);
          +                    final ExportedProperty property = sAnnotations.get(method);
                               if (property.resolveId() && view instanceof View) {
          -                        final Resources resources = ((View) view).getContext().getResources();
                                   final int id = (Integer) methodValue;
          -                        if (id >= 0) {
          -                            try {
          -                                methodValue = resources.getResourceTypeName(id) + '/' +
          -                                        resources.getResourceEntryName(id);
          -                            } catch (Resources.NotFoundException e) {
          -                                methodValue = "UNKNOWN";
          -                            }
          -                        } else {
          -                            methodValue = "NO_ID";
          -                        }
          +                        methodValue = resolveId(view, id);
                               } else {
                                   final IntToString[] mapping = property.mapping();
                                   if (mapping.length > 0) {
          @@ -833,28 +999,22 @@ public class ViewDebug {
                                       }
                                   }
                               }
          +                } else if (returnType == int[].class) {
          +                    final ExportedProperty property = sAnnotations.get(method);
          +                    final int[] array = (int[]) methodValue;
          +                    final String valuePrefix = prefix + method.getName() + '_';
          +                    final String suffix = "()";
          +
          +                    exportUnrolledArray(view, out, property, array, valuePrefix, suffix);
                           } else if (!returnType.isPrimitive()) {
          -                    ExportedProperty property = method.getAnnotation(ExportedProperty.class);
          +                    final ExportedProperty property = sAnnotations.get(method);
                               if (property.deepExport()) {
                                   dumpViewProperties(methodValue, out, prefix + property.prefix());
                                   continue;
                               }
                           }
           
          -                out.write(prefix);
          -                out.write(method.getName());
          -                out.write("()=");
          -
          -                if (methodValue != null) {
          -                    final String value = methodValue.toString().replace("\n", "\\n");
          -                    out.write(String.valueOf(value.length()));
          -                    out.write(",");
          -                    out.write(value);
          -                } else {
          -                    out.write("4,null");
          -                }
          -
          -                out.write(' ');
          +                writeEntry(out, prefix, method.getName(), "()", methodValue);
                       } catch (IllegalAccessException e) {
                       } catch (InvocationTargetException e) {
                       }
          @@ -875,20 +1035,10 @@ public class ViewDebug {
                           final Class type = field.getType();
           
                           if (type == int.class) {
          -                    ExportedProperty property = field.getAnnotation(ExportedProperty.class);
          +                    final ExportedProperty property = sAnnotations.get(field);
                               if (property.resolveId() && view instanceof View) {
          -                        final Resources resources = ((View) view).getContext().getResources();
                                   final int id = field.getInt(view);
          -                        if (id >= 0) {
          -                            try {
          -                                fieldValue = resources.getResourceTypeName(id) + '/' +
          -                                        resources.getResourceEntryName(id);
          -                            } catch (Resources.NotFoundException e) {
          -                                fieldValue = "UNKNOWN";
          -                            }
          -                        } else {
          -                            fieldValue = "NO_ID";
          -                        }
          +                        fieldValue = resolveId(view, id);
                               } else {
                                   final IntToString[] mapping = property.mapping();
                                   if (mapping.length > 0) {
          @@ -907,8 +1057,18 @@ public class ViewDebug {
                                       }
                                   }
                               }
          +                } else if (type == int[].class) {
          +                    final ExportedProperty property = sAnnotations.get(field);
          +                    final int[] array = (int[]) field.get(view);
          +                    final String valuePrefix = prefix + field.getName() + '_';
          +                    final String suffix = "";
          +
          +                    exportUnrolledArray(view, out, property, array, valuePrefix, suffix);
          +
          +                    // We exit here!
          +                    return;
                           } else if (!type.isPrimitive()) {
          -                    ExportedProperty property = field.getAnnotation(ExportedProperty.class);
          +                    final ExportedProperty property = sAnnotations.get(field);
                               if (property.deepExport()) {
                                   dumpViewProperties(field.get(view), out, prefix + property.prefix());
                                   continue;
          @@ -917,24 +1077,100 @@ public class ViewDebug {
           
                           if (fieldValue == null) {
                               fieldValue = field.get(view);
          -                }                
          +                }
           
          -                out.write(prefix);
          -                out.write(field.getName());
          -                out.write('=');
          +                writeEntry(out, prefix, field.getName(), "", fieldValue);
          +            } catch (IllegalAccessException e) {
          +            }
          +        }
          +    }
           
          -                if (fieldValue != null) {
          -                    final String value = fieldValue.toString().replace("\n", "\\n");
          -                    out.write(String.valueOf(value.length()));
          -                    out.write(",");
          -                    out.write(value);
          -                } else {
          -                    out.write("4,null");
          +    private static void writeEntry(BufferedWriter out, String prefix, String name,
          +            String suffix, Object value) throws IOException {
          +
          +        out.write(prefix);
          +        out.write(name);
          +        out.write(suffix);
          +        out.write("=");
          +        writeValue(out, value);
          +        out.write(' ');
          +    }
          +
          +    private static void exportUnrolledArray(Object view, BufferedWriter out,
          +            ExportedProperty property, int[] array, String prefix, String suffix)
          +            throws IOException {
          +
          +        final IntToString[] indexMapping = property.indexMapping();
          +        final boolean hasIndexMapping = indexMapping.length > 0;
          +
          +        final IntToString[] mapping = property.mapping();
          +        final boolean hasMapping = mapping.length > 0;
          +
          +        final boolean resolveId = property.resolveId() && view instanceof View;
          +        final int valuesCount = array.length;
          +
          +        for (int j = 0; j < valuesCount; j++) {
          +            String name;
          +            String value;
          +
          +            final int intValue = array[j];
          +
          +            name = String.valueOf(j);
          +            if (hasIndexMapping) {
          +                int mappingCount = indexMapping.length;
          +                for (int k = 0; k < mappingCount; k++) {
          +                    final IntToString mapped = indexMapping[k];
          +                    if (mapped.from() == j) {
          +                        name = mapped.to();
          +                        break;
          +                    }
                           }
          +            }
           
          -                out.write(' ');
          -            } catch (IllegalAccessException e) {
          +            value = String.valueOf(intValue);
          +            if (hasMapping) {
          +                int mappingCount = mapping.length;
          +                for (int k = 0; k < mappingCount; k++) {
          +                    final IntToString mapped = mapping[k];
          +                    if (mapped.from() == intValue) {
          +                        value = mapped.to();
          +                        break;
          +                    }
          +                }
          +            }
          +
          +            if (resolveId) {
          +                value = (String) resolveId(view, intValue);
                       }
          +
          +            writeEntry(out, prefix, name, suffix, value);
          +        }
          +    }
          +
          +    private static Object resolveId(Object view, int id) {
          +        Object fieldValue;
          +        final Resources resources = ((View) view).getContext().getResources();
          +        if (id >= 0) {
          +            try {
          +                fieldValue = resources.getResourceTypeName(id) + '/' +
          +                        resources.getResourceEntryName(id);
          +            } catch (Resources.NotFoundException e) {
          +                fieldValue = "id/0x" + Integer.toHexString(id);
          +            }
          +        } else {
          +            fieldValue = "NO_ID";
          +        }
          +        return fieldValue;
          +    }
          +
          +    private static void writeValue(BufferedWriter out, Object value) throws IOException {
          +        if (value != null) {
          +            String output = value.toString().replace("\n", "\\n");
          +            out.write(String.valueOf(output.length()));
          +            out.write(",");
          +            out.write(output);
          +        } else {
          +            out.write("4,null");
                   }
               }
           
          diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
          index e26a19e54e5e48a426e0d9ba8a27b211e1d9565e..dc7b299cade7ab31de2be3b51530d5b7301671a8 100644
          --- a/core/java/android/view/ViewGroup.java
          +++ b/core/java/android/view/ViewGroup.java
          @@ -25,7 +25,9 @@ import android.graphics.Canvas;
           import android.graphics.Paint;
           import android.graphics.Rect;
           import android.graphics.Region;
          +import android.graphics.RectF;
           import android.os.Parcelable;
          +import android.os.SystemClock;
           import android.util.AttributeSet;
           import android.util.EventLog;
           import android.util.Log;
          @@ -74,6 +76,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
           
               // The current transformation to apply on the child being drawn
               private Transformation mChildTransformation;
          +    private RectF mInvalidateRegion;
           
               // Target of Motion events
               private View mMotionTarget;
          @@ -1021,6 +1024,20 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
                */
               @Override
               void dispatchDetachedFromWindow() {
          +        // If we still have a motion target, we are still in the process of
          +        // dispatching motion events to a child; we need to get rid of that
          +        // child to avoid dispatching events to it after the window is torn
          +        // down. To make sure we keep the child in a consistent state, we
          +        // first send it an ACTION_CANCEL motion event.
          +        if (mMotionTarget != null) {
          +            final long now = SystemClock.uptimeMillis();
          +            final MotionEvent event = MotionEvent.obtain(now, now,
          +                    MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
          +            mMotionTarget.dispatchTouchEvent(event);
          +            event.recycle();
          +            mMotionTarget = null;
          +        }
          +
                   final int count = mChildrenCount;
                   final View[] children = mChildren;
                   for (int i = 0; i < count; i++) {
          @@ -1199,6 +1216,8 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
           
                   }
           
          +        // We will draw our child's animation, let's reset the flag
          +        mPrivateFlags &= ~DRAW_ANIMATION;
                   mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;
           
                   boolean more = false;
          @@ -1327,9 +1346,19 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
                   final Animation a = child.getAnimation();
                   boolean concatMatrix = false;
           
          +        final int childWidth = cr - cl;
          +        final int childHeight = cb - ct;
          +
                   if (a != null) {
          -            if (!a.isInitialized()) {
          -                a.initialize(cr - cl, cb - ct, getWidth(), getHeight());
          +            if (mInvalidateRegion == null) {
          +                mInvalidateRegion = new RectF();
          +            }
          +            final RectF region = mInvalidateRegion;
          +
          +            final boolean initialized = a.isInitialized();
          +            if (!initialized) {
          +                a.initialize(childWidth, childHeight, getWidth(), getHeight());
          +                a.initializeInvalidateRegion(0, 0, childWidth, childHeight);
                           child.onAnimationStart();
                       }
           
          @@ -1347,10 +1376,21 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
                                       FLAG_OPTIMIZE_INVALIDATE) {
                                   mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
                               } else if ((flags & FLAG_INVALIDATE_REQUIRED) == 0) {
          +                        // The child need to draw an animation, potentially offscreen, so
          +                        // make sure we do not cancel invalidate requests
          +                        mPrivateFlags |= DRAW_ANIMATION;
                                   invalidate(cl, ct, cr, cb);
                               }
                           } else {
          -                    mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
          +                    a.getInvalidateRegion(0, 0, childWidth, childHeight, region, transformToApply);
          +
          +                    // The child need to draw an animation, potentially offscreen, so
          +                    // make sure we do not cancel invalidate requests
          +                    mPrivateFlags |= DRAW_ANIMATION;
          +
          +                    final int left = cl + (int) region.left;
          +                    final int top = ct + (int) region.top;
          +                    invalidate(left, top, left + (int) region.width(), top + (int) region.height());
                           }
                       }
                   } else if ((flags & FLAG_SUPPORT_STATIC_TRANSFORMATIONS) ==
          @@ -1367,7 +1407,8 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
                       }
                   }
           
          -        if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW)) {
          +        if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW) &&
          +                (child.mPrivateFlags & DRAW_ANIMATION) == 0) {
                       return more;
                   }
           
          @@ -1429,16 +1470,19 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
           
                   if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
                       if (hasNoCache) {
          -                canvas.clipRect(sx, sy, sx + cr - cl, sy + cb - ct);
          +                canvas.clipRect(sx, sy, sx + childWidth, sy + childHeight);
                       } else {
          -                canvas.clipRect(0, 0, cr - cl, cb - ct);
          +                canvas.clipRect(0, 0, childWidth, childHeight);
                       }
                   }
           
          +        // Clear the flag as early as possible to allow draw() implementations
          +        // to call invalidate() successfully when doing animations
          +        child.mPrivateFlags |= DRAWN;
          +
                   if (hasNoCache) {
                       // Fast path for layouts with no backgrounds
                       if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
          -                child.mPrivateFlags |= DRAWN;
                           if (ViewDebug.TRACE_HIERARCHY) {
                               ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
                           }
          @@ -1455,7 +1499,6 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
                           cachePaint.setAlpha(255);
                           mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE;
                       }
          -            child.mPrivateFlags |= DRAWN;
                       if (ViewRoot.PROFILE_DRAWING) {
                           EventLog.writeEvent(60003, hashCode());
                       }
          @@ -1922,8 +1965,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
                   LayoutAnimationController.AnimationParameters animationParams =
                               params.layoutAnimationParameters;
                   if (animationParams == null) {
          -            animationParams =
          -                    new LayoutAnimationController.AnimationParameters();
          +            animationParams = new LayoutAnimationController.AnimationParameters();
                       params.layoutAnimationParameters = animationParams;
                   }
           
          @@ -2278,8 +2320,16 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
                       final int[] location = attachInfo.mInvalidateChildLocation;
                       location[CHILD_LEFT_INDEX] = child.mLeft;
                       location[CHILD_TOP_INDEX] = child.mTop;
          +
          +            // If the child is drawing an animation, we want to copy this flag onto
          +            // ourselves and the parent to make sure the invalidate request goes
          +            // through
          +            final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION;
               
                       do {
          +                if (drawAnimation && parent instanceof View) {
          +                    ((View) parent).mPrivateFlags |= DRAW_ANIMATION;
          +                }
                           parent = parent.invalidateChildInParent(location, dirty);
                       } while (parent != null);
                   }
          @@ -2307,7 +2357,8 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
                           final int left = mLeft;
                           final int top = mTop;
           
          -                if (dirty.intersect(0, 0, mRight - left, mBottom - top)) {
          +                if (dirty.intersect(0, 0, mRight - left, mBottom - top) ||
          +                        (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
                               mPrivateFlags &= ~DRAWING_CACHE_VALID;
           
                               location[CHILD_LEFT_INDEX] = left;
          diff --git a/core/java/android/view/ViewRoot.java b/core/java/android/view/ViewRoot.java
          index 9e0289a4bedbb003b32489bb9e3198d48a2c1ba2..dd2b154c7fbefe60eeb7ea4b53141a02bb01ad4d 100644
          --- a/core/java/android/view/ViewRoot.java
          +++ b/core/java/android/view/ViewRoot.java
          @@ -33,6 +33,7 @@ import android.util.Config;
           import android.util.Log;
           import android.util.EventLog;
           import android.util.SparseArray;
          +import android.util.DisplayMetrics;
           import android.view.View.MeasureSpec;
           import android.view.inputmethod.InputConnection;
           import android.view.inputmethod.InputMethodManager;
          @@ -61,7 +62,7 @@ import static javax.microedition.khronos.opengles.GL10.*;
            */
           @SuppressWarnings({"EmptyCatchBlock"})
           public final class ViewRoot extends Handler implements ViewParent,
          -        View.AttachInfo.SoundEffectPlayer {
          +        View.AttachInfo.Callbacks {
               private static final String TAG = "ViewRoot";
               private static final boolean DBG = false;
               @SuppressWarnings({"ConstantConditionalExpression"})
          @@ -142,6 +143,7 @@ public final class ViewRoot extends Handler implements ViewParent,
               boolean mFullRedrawNeeded;
               boolean mNewSurfaceNeeded;
               boolean mHasHadWindowFocus;
          +    boolean mLastWasImTarget;
           
               boolean mWindowAttributesChanged = false;
           
          @@ -177,12 +179,14 @@ public final class ViewRoot extends Handler implements ViewParent,
               boolean mUseGL;
               boolean mGlWanted;
           
          +    final ViewConfiguration mViewConfiguration;    
          +
               /**
                * see {@link #playSoundEffect(int)}
                */
               AudioManager mAudioManager;
           
          -
          +    private final float mDensity;
           
               public ViewRoot(Context context) {
                   super();
          @@ -215,7 +219,7 @@ public final class ViewRoot extends Handler implements ViewParent,
                   mVisRect = new Rect();
                   mVisPoint = new Point();
                   mWinFrame = new Rect();
          -        mWindow = new W(this);
          +        mWindow = new W(this, context);
                   mInputMethodCallback = new InputMethodCallback(this);
                   mViewVisibility = View.GONE;
                   mTransparentRegion = new Region();
          @@ -224,6 +228,8 @@ public final class ViewRoot extends Handler implements ViewParent,
                   mSurface = new Surface();
                   mAdded = false;
                   mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
          +        mViewConfiguration = ViewConfiguration.get(context);
          +        mDensity = context.getResources().getDisplayMetrics().density;
               }
           
               @Override
          @@ -993,6 +999,21 @@ public final class ViewRoot extends Handler implements ViewParent,
                   mNewSurfaceNeeded = false;
                   mViewVisibility = viewVisibility;
           
          +        if (mAttachInfo.mHasWindowFocus) {
          +            final boolean imTarget = WindowManager.LayoutParams
          +                    .mayUseInputMethod(mWindowAttributes.flags);
          +            if (imTarget != mLastWasImTarget) {
          +                mLastWasImTarget = imTarget;
          +                InputMethodManager imm = InputMethodManager.peekInstance();
          +                if (imm != null && imTarget) {
          +                    imm.startGettingWindowFocus(mView);
          +                    imm.onWindowFocus(mView, mView.findFocus(),
          +                            mWindowAttributes.softInputMode,
          +                            !mHasHadWindowFocus, mWindowAttributes.flags);
          +                }
          +            }
          +        }
          +        
                   boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
           
                   if (!cancelDraw && !newSurface) {
          @@ -1075,6 +1096,11 @@ public final class ViewRoot extends Handler implements ViewParent,
                   }
           
                   scrollToRectOrFocus(null, false);
          +
          +        if (mAttachInfo.mViewScrollChanged) {
          +            mAttachInfo.mViewScrollChanged = false;
          +            mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
          +        }
                   
                   int yoff;
                   final boolean scrolling = mScroller != null
          @@ -1088,7 +1114,7 @@ public final class ViewRoot extends Handler implements ViewParent,
                       mCurScrollY = yoff;
                       fullRedrawNeeded = true;
                   }
          -        
          +
                   Rect dirty = mDirty;
                   if (mUseGL) {
                       if (!dirty.isEmpty()) {
          @@ -1101,6 +1127,7 @@ public final class ViewRoot extends Handler implements ViewParent,
           
                               mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
                               canvas.translate(0, -yoff);
          +                    mView.mPrivateFlags |= View.DRAWN;
                               mView.draw(canvas);
                               canvas.translate(0, yoff);
           
          @@ -1123,7 +1150,6 @@ public final class ViewRoot extends Handler implements ViewParent,
                       return;
                   }
           
          -
                   if (fullRedrawNeeded)
                       dirty.union(0, 0, mWidth, mHeight);
           
          @@ -1135,20 +1161,22 @@ public final class ViewRoot extends Handler implements ViewParent,
                               + surface + " surface.isValid()=" + surface.isValid());
                   }
           
          -        if (!dirty.isEmpty()) {
          -            Canvas canvas;
          -            try {
          -                canvas = surface.lockCanvas(dirty);
          -            } catch (Surface.OutOfResourcesException e) {
          -                Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
          -                // TODO: we should ask the window manager to do something!
          -                // for now we just do nothing
          -                return;
          -            }
          +        Canvas canvas;
          +        try {
          +            canvas = surface.lockCanvas(dirty);
          +            // TODO: Do this in native
          +            canvas.setDensityScale(mDensity);
          +        } catch (Surface.OutOfResourcesException e) {
          +            Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
          +            // TODO: we should ask the window manager to do something!
          +            // for now we just do nothing
          +            return;
          +        }
           
          -            long startTime;
          +        try {
          +            if (!dirty.isEmpty()) {
          +                long startTime;
           
          -            try {
                           if (DEBUG_ORIENTATION || DEBUG_DRAW) {
                               Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
                                       + canvas.getWidth() + ", h=" + canvas.getHeight());
          @@ -1164,7 +1192,7 @@ public final class ViewRoot extends Handler implements ViewParent,
                           // properly re-composite its drawing on a transparent
                           // background. This automatically respects the clip/dirty region
                           if (!canvas.isOpaque()) {
          -                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
          +                    canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
                           } else if (yoff != 0) {
                               // If we are applying an offset, we need to clear the area
                               // where the offset doesn't appear to avoid having garbage
          @@ -1175,6 +1203,7 @@ public final class ViewRoot extends Handler implements ViewParent,
                           dirty.setEmpty();
                           mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
                           canvas.translate(0, -yoff);
          +                mView.mPrivateFlags |= View.DRAWN;                    
                           mView.draw(canvas);
                           canvas.translate(0, yoff);
           
          @@ -1186,17 +1215,17 @@ public final class ViewRoot extends Handler implements ViewParent,
                               sDrawTime = now;
                           }
           
          -            } finally {
          -                surface.unlockCanvasAndPost(canvas);
          -            }
          -
          -            if (PROFILE_DRAWING) {
          -                EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
          +                if (PROFILE_DRAWING) {
          +                    EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
          +                }
                       }
          +            
          +        } finally {
          +            surface.unlockCanvasAndPost(canvas);
          +        }
           
          -            if (LOCAL_LOGV) {
          -                Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
          -            }
          +        if (LOCAL_LOGV) {
          +            Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
                   }
                   
                   if (scrolling) {
          @@ -1378,14 +1407,22 @@ public final class ViewRoot extends Handler implements ViewParent,
           
               void dispatchDetachedFromWindow() {
                   if (Config.LOGV) Log.v("ViewRoot", "Detaching in " + this + " of " + mSurface);
          +
                   if (mView != null) {
                       mView.dispatchDetachedFromWindow();
                   }
          +
                   mView = null;
                   mAttachInfo.mRootView = null;
          +
                   if (mUseGL) {
                       destroyGL();
                   }
          +
          +        try {
          +            sWindowSession.remove(mWindow);
          +        } catch (RemoteException e) {
          +        }
               }
               
               /**
          @@ -1414,6 +1451,7 @@ public final class ViewRoot extends Handler implements ViewParent,
               public final static int FINISHED_EVENT = 1010;
               public final static int DISPATCH_KEY_FROM_IME = 1011;
               public final static int FINISH_INPUT_CONNECTION = 1012;
          +    public final static int CHECK_FOCUS = 1013;
           
               @Override
               public void handleMessage(Message msg) {
          @@ -1422,11 +1460,9 @@ public final class ViewRoot extends Handler implements ViewParent,
                       ((View) msg.obj).invalidate();
                       break;
                   case View.AttachInfo.INVALIDATE_RECT_MSG:
          -            int left = msg.arg1 >>> 16;
          -            int top = msg.arg1 & 0xFFFF;
          -            int right = msg.arg2 >>> 16;
          -            int bottom = msg.arg2 & 0xFFFF;
          -            ((View) msg.obj).invalidate(left, top, right, bottom);
          +            final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
          +            info.target.invalidate(info.left, info.top, info.right, info.bottom);
          +            info.release();
                       break;
                   case DO_TRAVERSAL:
                       if (mProfile) {
          @@ -1478,7 +1514,7 @@ public final class ViewRoot extends Handler implements ViewParent,
                               event.offsetLocation(0, mCurScrollY);
                               handled = mView.dispatchTouchEvent(event);
                               if (!handled && isDown) {
          -                        int edgeSlop = ViewConfiguration.getEdgeSlop();
          +                        int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
           
                                   final int edgeFlags = event.getEdgeFlags();
                                   int direction = View.FOCUS_UP;
          @@ -1587,16 +1623,23 @@ public final class ViewRoot extends Handler implements ViewParent,
                                   }
                               }
                           }
          +                
          +                mLastWasImTarget = WindowManager.LayoutParams
          +                        .mayUseInputMethod(mWindowAttributes.flags);
          +                
          +                InputMethodManager imm = InputMethodManager.peekInstance();
                           if (mView != null) {
          +                    if (hasWindowFocus && imm != null && mLastWasImTarget) {
          +                        imm.startGettingWindowFocus(mView);
          +                    }
                               mView.dispatchWindowFocusChanged(hasWindowFocus);
                           }
                           
                           // Note: must be done after the focus change callbacks,
                           // so all of the view state is set up correctly.
                           if (hasWindowFocus) {
          -                    InputMethodManager imm = InputMethodManager.peekInstance();
          -                    if (imm != null) {
          -                        imm.onWindowFocus(mView.findFocus(),
          +                    if (imm != null && mLastWasImTarget) {
          +                        imm.onWindowFocus(mView, mView.findFocus(),
                                           mWindowAttributes.softInputMode,
                                           !mHasHadWindowFocus, mWindowAttributes.flags);
                               }
          @@ -1626,6 +1669,12 @@ public final class ViewRoot extends Handler implements ViewParent,
                           imm.reportFinishInputConnection((InputConnection)msg.obj);
                       }
                   } break;
          +        case CHECK_FOCUS: {
          +            InputMethodManager imm = InputMethodManager.peekInstance();
          +            if (imm != null) {
          +                imm.checkFocus();
          +            }
          +        } break;
                   }
               }
           
          @@ -1787,6 +1836,11 @@ public final class ViewRoot extends Handler implements ViewParent,
                           if (event != null) {
                               event.recycle();
                           }
          +                // If we reach this, we delivered a trackball event to mView and
          +                // mView consumed it. Because we will not translate the trackball
          +                // event into a key event, touch mode will not exit, so we exit
          +                // touch mode here.
          +                ensureTouchMode(false);
                           //noinspection ReturnInsideFinallyBlock
                           return;
                       }
          @@ -1941,6 +1995,9 @@ public final class ViewRoot extends Handler implements ViewParent,
                   if (event.getAction() != KeyEvent.ACTION_DOWN) {
                       return false;
                   }
          +        if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
          +            return false;
          +        }
           
                   // only relevant if we are in touch mode
                   if (!mAttachInfo.mInTouchMode) {
          @@ -2042,8 +2099,10 @@ public final class ViewRoot extends Handler implements ViewParent,
               }
               
               private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
          -        boolean handled = false;
          -        handled = mView.dispatchKeyEventPreIme(event);
          +        // If mView is null, we just consume the key event because it doesn't
          +        // make sense to do anything else with it.
          +        boolean handled = mView != null
          +                ? mView.dispatchKeyEventPreIme(event) : true;
                   if (handled) {
                       if (sendDone) {
                           if (LOCAL_LOGV) Log.v(
          @@ -2058,10 +2117,9 @@ public final class ViewRoot extends Handler implements ViewParent,
                   // If it is possible for this window to interact with the input
                   // method window, then we want to first dispatch our key events
                   // to the input method.
          -        if (WindowManager.LayoutParams.mayUseInputMethod(
          -                mWindowAttributes.flags)) {
          +        if (mLastWasImTarget) {
                       InputMethodManager imm = InputMethodManager.peekInstance();
          -            if (imm != null && mView != null && imm.isActive()) {
          +            if (imm != null && mView != null) {
                           int seq = enqueuePendingEvent(event, sendDone);
                           if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
                                   + seq + " event=" + event);
          @@ -2089,6 +2147,10 @@ public final class ViewRoot extends Handler implements ViewParent,
                               sWindowSession.finishKey(mWindow);
                           } catch (RemoteException e) {
                           }
          +            } else {
          +                Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
          +                        + " handled=" + handled + " ev=" + event
          +                        + ") neither delivering nor finishing key");
                       }
                   }
               }
          @@ -2108,7 +2170,7 @@ public final class ViewRoot extends Handler implements ViewParent,
                           }
                           boolean keyHandled = mView.dispatchKeyEvent(event);
           
          -                if ((!keyHandled && isDown) || (action == KeyEvent.ACTION_MULTIPLE)) {
          +                if (!keyHandled && isDown) {
                               int direction = 0;
                               switch (event.getKeyCode()) {
                               case KeyEvent.KEYCODE_DPAD_LEFT:
          @@ -2205,6 +2267,17 @@ public final class ViewRoot extends Handler implements ViewParent,
                   }
               }
           
          +    /**
          +     * {@inheritDoc}
          +     */
          +    public boolean performHapticFeedback(int effectId, boolean always) {
          +        try {
          +            return sWindowSession.performHapticFeedback(mWindow, effectId, always);
          +        } catch (RemoteException e) {
          +            return false;
          +        }
          +    }
          +
               /**
                * {@inheritDoc}
                */
          @@ -2248,10 +2321,6 @@ public final class ViewRoot extends Handler implements ViewParent,
                       }
                       if (mAdded) {
                           mAdded = false;
          -                try {
          -                    sWindowSession.remove(mWindow);
          -                } catch (RemoteException e) {
          -                }
                           if (immediate) {
                               dispatchDetachedFromWindow();
                           } else if (mView != null) {
          @@ -2384,11 +2453,71 @@ public final class ViewRoot extends Handler implements ViewParent,
                   }
               }
               
          +    static class EventCompletion extends Handler {
          +        final IWindow mWindow;
          +        final KeyEvent mKeyEvent;
          +        final boolean mIsPointer;
          +        final MotionEvent mMotionEvent;
          +        
          +        EventCompletion(Looper looper, IWindow window, KeyEvent key,
          +                boolean isPointer, MotionEvent motion) {
          +            super(looper);
          +            mWindow = window;
          +            mKeyEvent = key;
          +            mIsPointer = isPointer;
          +            mMotionEvent = motion;
          +            sendEmptyMessage(0);
          +        }
          +        
          +        @Override
          +        public void handleMessage(Message msg) {
          +            if (mKeyEvent != null) {
          +                try {
          +                    sWindowSession.finishKey(mWindow);
          +                 } catch (RemoteException e) {
          +                 }
          +            } else if (mIsPointer) {
          +                boolean didFinish;
          +                MotionEvent event = mMotionEvent;
          +                if (event == null) {
          +                    try {
          +                        event = sWindowSession.getPendingPointerMove(mWindow);
          +                    } catch (RemoteException e) {
          +                    }
          +                    didFinish = true;
          +                } else {
          +                    didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
          +                }
          +                if (!didFinish) {
          +                    try {
          +                        sWindowSession.finishKey(mWindow);
          +                     } catch (RemoteException e) {
          +                     }
          +                }
          +            } else {
          +                MotionEvent event = mMotionEvent;
          +                if (event == null) {
          +                    try {
          +                        event = sWindowSession.getPendingTrackballMove(mWindow);
          +                    } catch (RemoteException e) {
          +                    }
          +                } else {
          +                    try {
          +                        sWindowSession.finishKey(mWindow);
          +                     } catch (RemoteException e) {
          +                     }
          +                }
          +            }
          +        }
          +    }
          +    
               static class W extends IWindow.Stub {
          -        private WeakReference mViewRoot;
          +        private final WeakReference mViewRoot;
          +        private final Looper mMainLooper;
           
          -        public W(ViewRoot viewRoot) {
          +        public W(ViewRoot viewRoot, Context context) {
                       mViewRoot = new WeakReference(viewRoot);
          +            mMainLooper = context.getMainLooper();
                   }
           
                   public void resized(int w, int h, Rect coveredInsets,
          @@ -2404,6 +2533,9 @@ public final class ViewRoot extends Handler implements ViewParent,
                       final ViewRoot viewRoot = mViewRoot.get();
                       if (viewRoot != null) {
                           viewRoot.dispatchKey(event);
          +            } else {
          +                Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
          +                new EventCompletion(mMainLooper, this, event, false, null);
                       }
                   }
           
          @@ -2411,6 +2543,8 @@ public final class ViewRoot extends Handler implements ViewParent,
                       final ViewRoot viewRoot = mViewRoot.get();
                       if (viewRoot != null) {
                           viewRoot.dispatchPointer(event, eventTime);
          +            } else {
          +                new EventCompletion(mMainLooper, this, null, true, event);
                       }
                   }
           
          @@ -2418,6 +2552,8 @@ public final class ViewRoot extends Handler implements ViewParent,
                       final ViewRoot viewRoot = mViewRoot.get();
                       if (viewRoot != null) {
                           viewRoot.dispatchTrackball(event, eventTime);
          +            } else {
          +                new EventCompletion(mMainLooper, this, null, false, event);
                       }
                   }
           
          @@ -2502,7 +2638,7 @@ public final class ViewRoot extends Handler implements ViewParent,
                    * for us to consider the user to be doing fast trackball movements,
                    * and thus apply an acceleration.
                    */
          -        static final long FAST_MOVE_TIME = 100;
          +        static final long FAST_MOVE_TIME = 150;
                   
                   /**
                    * Scaling factor to the time (in milliseconds) between events to how
          @@ -2510,7 +2646,7 @@ public final class ViewRoot extends Handler implements ViewParent,
                    * is < FAST_MOVE_TIME this multiplies the acceleration; when >
                    * FAST_MOVE_TIME it divides it.
                    */
          -        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/50);
          +        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
                   
                   float position;
                   float absPosition;
          @@ -2748,7 +2884,6 @@ public final class ViewRoot extends Handler implements ViewParent,
           
                       synchronized (mActions) {
                           final ArrayList actions = mActions;
          -                final int count = actions.size();
           
                           while (actions.remove(handlerAction)) {
                               // Keep going
          @@ -2776,7 +2911,20 @@ public final class ViewRoot extends Handler implements ViewParent,
           
                       @Override
                       public boolean equals(Object o) {
          -                return action.equals(o);
          +                if (this == o) return true;
          +                if (o == null || getClass() != o.getClass()) return false;
          +
          +                HandlerAction that = (HandlerAction) o;
          +
          +                return !(action != null ? !action.equals(that.action) : that.action != null);
          +
          +            }
          +
          +            @Override
          +            public int hashCode() {
          +                int result = action != null ? action.hashCode() : 0;
          +                result = 31 * result + (int) (delay ^ (delay >>> 32));
          +                return result;
                       }
                   }
               }
          diff --git a/core/java/android/view/ViewTreeObserver.java b/core/java/android/view/ViewTreeObserver.java
          index 05f5fa2a153251f4ed2aa7f911538267aa0c85d3..47b52e4a9ad7e4375800137d31fa68789023b33b 100644
          --- a/core/java/android/view/ViewTreeObserver.java
          +++ b/core/java/android/view/ViewTreeObserver.java
          @@ -35,6 +35,7 @@ public final class ViewTreeObserver {
               private ArrayList mOnPreDrawListeners;
               private ArrayList mOnTouchModeChangeListeners;
               private ArrayList mOnComputeInternalInsetsListeners;
          +    private ArrayList mOnScrollChangedListeners;
           
               private boolean mAlive = true;
           
          @@ -98,6 +99,20 @@ public final class ViewTreeObserver {
                   public void onTouchModeChanged(boolean isInTouchMode);
               }
           
          +    /**
          +     * Interface definition for a callback to be invoked when
          +     * something in the view tree has been scrolled.
          +     * 
          +     * @hide pending API council approval
          +     */
          +    public interface OnScrollChangedListener {
          +        /**
          +         * Callback method to be invoked when something in the view tree
          +         * has been scrolled.
          +         */
          +        public void onScrollChanged();
          +    }
          +
               /**
                * Parameters used with OnComputeInternalInsetsListener.
                * {@hide pending API Council approval}
          @@ -360,6 +375,44 @@ public final class ViewTreeObserver {
                   mOnPreDrawListeners.remove(victim);
               }
           
          +    /**
          +     * Register a callback to be invoked when a view has been scrolled.
          +     *
          +     * @param listener The callback to add
          +     *
          +     * @throws IllegalStateException If {@link #isAlive()} returns false
          +     *
          +     * @hide pending API council approval
          +     */
          +    public void addOnScrollChangedListener(OnScrollChangedListener listener) {
          +        checkIsAlive();
          +
          +        if (mOnScrollChangedListeners == null) {
          +            mOnScrollChangedListeners = new ArrayList();
          +        }
          +
          +        mOnScrollChangedListeners.add(listener);
          +    }
          +
          +    /**
          +     * Remove a previously installed scroll-changed callback
          +     *
          +     * @param victim The callback to remove
          +     *
          +     * @throws IllegalStateException If {@link #isAlive()} returns false
          +     *
          +     * @see #addOnScrollChangedListener(OnScrollChangedListener)
          +     *
          +     * @hide pending API council approval
          +     */
          +    public void removeOnScrollChangedListener(OnScrollChangedListener victim) {
          +        checkIsAlive();
          +        if (mOnScrollChangedListeners == null) {
          +            return;
          +        }
          +        mOnScrollChangedListeners.remove(victim);
          +    }
          +
               /**
                * Register a callback to be invoked when the invoked when the touch mode changes.
                *
          @@ -524,6 +577,19 @@ public final class ViewTreeObserver {
                   }
               }
           
          +    /**
          +     * Notifies registered listeners that something has scrolled.
          +     */
          +    final void dispatchOnScrollChanged() {
          +        final ArrayList listeners = mOnScrollChangedListeners;
          +
          +        if (listeners != null) {
          +            for (OnScrollChangedListener scl : mOnScrollChangedListeners) {
          +                scl.onScrollChanged();
          +            }
          +        }
          +    }
          +
               /**
                * Returns whether there are listeners for computing internal insets.
                */
          diff --git a/core/java/android/view/VolumePanel.java b/core/java/android/view/VolumePanel.java
          index f4d0fdeda8057503edf4a5dce06c4b0c6b60a909..a5739835321bbfef8ed720bb02038c374038155e 100644
          --- a/core/java/android/view/VolumePanel.java
          +++ b/core/java/android/view/VolumePanel.java
          @@ -16,18 +16,17 @@
           
           package android.view;
           
          -import android.media.ToneGenerator;
          -import android.media.AudioManager;
          -import android.media.AudioService;
          -import android.media.AudioSystem;
          +import android.bluetooth.HeadsetBase;
           import android.content.Context;
           import android.content.Intent;
          -import android.content.IntentFilter;
           import android.content.res.Resources;
          +import android.media.AudioManager;
          +import android.media.AudioService;
          +import android.media.AudioSystem;
          +import android.media.ToneGenerator;
           import android.os.Handler;
           import android.os.Message;
           import android.os.Vibrator;
          -import android.text.TextUtils;
           import android.util.Config;
           import android.util.Log;
           import android.widget.ImageView;
          @@ -39,7 +38,7 @@ import android.widget.Toast;
            * Handle the volume up and down keys.
            *
            * This code really should be moved elsewhere.
          - * 
          + *
            * @hide
            */
           public class VolumePanel extends Handler
          @@ -54,7 +53,7 @@ public class VolumePanel extends Handler
                * PhoneWindow will implement this part.
                */
               public static final int PLAY_SOUND_DELAY = 300;
          -    
          +
               /**
                * The delay before vibrating. This small period exists so if the user is
                * moving to silent mode, it will not emit a short vibrate (it normally
          @@ -64,28 +63,30 @@ public class VolumePanel extends Handler
               public static final int VIBRATE_DELAY = 300;
           
               private static final int VIBRATE_DURATION = 300;
          -    private static final int BEEP_DURATION = 150; 
          +    private static final int BEEP_DURATION = 150;
               private static final int MAX_VOLUME = 100;
               private static final int FREE_DELAY = 10000;
          -    
          +
               private static final int MSG_VOLUME_CHANGED = 0;
               private static final int MSG_FREE_RESOURCES = 1;
               private static final int MSG_PLAY_SOUND = 2;
               private static final int MSG_STOP_SOUNDS = 3;
               private static final int MSG_VIBRATE = 4;
          -    
          +
               private static final int RINGTONE_VOLUME_TEXT = com.android.internal.R.string.volume_ringtone;
               private static final int MUSIC_VOLUME_TEXT = com.android.internal.R.string.volume_music;
               private static final int INCALL_VOLUME_TEXT = com.android.internal.R.string.volume_call;
               private static final int ALARM_VOLUME_TEXT = com.android.internal.R.string.volume_alarm;
               private static final int UNKNOWN_VOLUME_TEXT = com.android.internal.R.string.volume_unknown;
               private static final int NOTIFICATION_VOLUME_TEXT =
          -            com.android.internal.R.string.volume_notification; 
          -    
          +            com.android.internal.R.string.volume_notification;
          +    private static final int BLUETOOTH_INCALL_VOLUME_TEXT =
          +            com.android.internal.R.string.volume_bluetooth_call;
          +
               protected Context mContext;
               private AudioManager mAudioManager;
               protected AudioService mAudioService;
          -    
          +
               private final Toast mToast;
               private final View mView;
               private final TextView mMessage;
          @@ -117,13 +118,13 @@ public class VolumePanel extends Handler
                   mToneGenerators = new ToneGenerator[AudioSystem.getNumStreamTypes()];
                   mVibrator = new Vibrator();
               }
          -    
          +
               public void postVolumeChanged(int streamType, int flags) {
                   if (hasMessages(MSG_VOLUME_CHANGED)) return;
                   removeMessages(MSG_FREE_RESOURCES);
                   obtainMessage(MSG_VOLUME_CHANGED, streamType, flags).sendToTarget();
               }
          -    
          +
               /**
                * Override this if you have other work to do when the volume changes (for
                * example, vibrating, playing a sound, etc.). Make sure to call through to
          @@ -132,31 +133,31 @@ public class VolumePanel extends Handler
               protected void onVolumeChanged(int streamType, int flags) {
           
                   if (LOGD) Log.d(TAG, "onVolumeChanged(streamType: " + streamType + ", flags: " + flags + ")");
          -        
          +
                   if ((flags & AudioManager.FLAG_SHOW_UI) != 0) {
                       onShowVolumeChanged(streamType, flags);
                   }
          -        
          +
                   if ((flags & AudioManager.FLAG_PLAY_SOUND) != 0) {
                       removeMessages(MSG_PLAY_SOUND);
                       sendMessageDelayed(obtainMessage(MSG_PLAY_SOUND, streamType, flags), PLAY_SOUND_DELAY);
                   }
          -        
          +
                   if ((flags & AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE) != 0) {
                       removeMessages(MSG_PLAY_SOUND);
                       removeMessages(MSG_VIBRATE);
                       onStopSounds();
                   }
          -        
          +
                   removeMessages(MSG_FREE_RESOURCES);
          -        sendMessageDelayed(obtainMessage(MSG_FREE_RESOURCES), FREE_DELAY); 
          +        sendMessageDelayed(obtainMessage(MSG_FREE_RESOURCES), FREE_DELAY);
               }
           
               protected void onShowVolumeChanged(int streamType, int flags) {
                   int index = mAudioService.getStreamVolume(streamType);
                   int message = UNKNOWN_VOLUME_TEXT;
                   int additionalMessage = 0;
          -        
          +
                   if (LOGD) {
                       Log.d(TAG, "onShowVolumeChanged(streamType: " + streamType
                               + ", flags: " + flags + "), index: " + index);
          @@ -166,13 +167,13 @@ public class VolumePanel extends Handler
                   int max = mAudioService.getStreamMaxVolume(streamType);
           
                   switch (streamType) {
          -            
          +
                       case AudioManager.STREAM_RING: {
                           message = RINGTONE_VOLUME_TEXT;
                           setRingerIcon(index);
                           break;
                       }
          -                
          +
                       case AudioManager.STREAM_MUSIC: {
                           message = MUSIC_VOLUME_TEXT;
                           if (mAudioManager.isBluetoothA2dpOn()) {
          @@ -184,7 +185,7 @@ public class VolumePanel extends Handler
                           }
                           break;
                       }
          -                
          +
                       case AudioManager.STREAM_VOICE_CALL: {
                           /*
                            * For in-call voice call volume, there is no inaudible volume.
          @@ -194,13 +195,7 @@ public class VolumePanel extends Handler
                           index++;
                           max++;
                           message = INCALL_VOLUME_TEXT;
          -                if (mAudioManager.isBluetoothScoOn()) {
          -                    additionalMessage =
          -                        com.android.internal.R.string.volume_call_hint_playing_through_bluetooth;
          -                    setLargeIcon(com.android.internal.R.drawable.ic_volume_bluetooth_in_call);
          -                } else {
          -                    setSmallIcon(index);
          -                }
          +                setSmallIcon(index);
                           break;
                       }
           
          @@ -209,12 +204,25 @@ public class VolumePanel extends Handler
                           setSmallIcon(index);
                           break;
                       }
          -            
          +
                       case AudioManager.STREAM_NOTIFICATION: {
                           message = NOTIFICATION_VOLUME_TEXT;
                           setSmallIcon(index);
                           break;
                       }
          +
          +            case AudioManager.STREAM_BLUETOOTH_SCO: {
          +                /*
          +                 * For in-call voice call volume, there is no inaudible volume.
          +                 * Rescale the UI control so the progress bar doesn't go all
          +                 * the way to zero and don't show the mute icon.
          +                 */
          +                index++;
          +                max++;
          +                message = BLUETOOTH_INCALL_VOLUME_TEXT;
          +                setLargeIcon(com.android.internal.R.drawable.ic_volume_bluetooth_in_call);
          +                break;
          +            }
                   }
           
                   String messageString = Resources.getSystem().getString(message);
          @@ -228,25 +236,25 @@ public class VolumePanel extends Handler
                       mAdditionalMessage.setVisibility(View.VISIBLE);
                       mAdditionalMessage.setText(Resources.getSystem().getString(additionalMessage));
                   }
          -        
          +
                   if (max != mLevel.getMax()) {
                       mLevel.setMax(max);
                   }
                   mLevel.setProgress(index);
          -        
          +
                   mToast.setView(mView);
                   mToast.setDuration(Toast.LENGTH_SHORT);
                   mToast.setGravity(Gravity.TOP, 0, 0);
                   mToast.show();
          -        
          +
                   // Do a little vibrate if applicable (only when going into vibrate mode)
          -        if ((flags & AudioManager.FLAG_VIBRATE) != 0 && 
          +        if ((flags & AudioManager.FLAG_VIBRATE) != 0 &&
                           mAudioService.isStreamAffectedByRingerMode(streamType) &&
                           mAudioService.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE &&
                           mAudioService.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER)) {
                       sendMessageDelayed(obtainMessage(MSG_VIBRATE), VIBRATE_DELAY);
                   }
          -        
          +
               }
           
               protected void onPlaySound(int streamType, int flags) {
          @@ -256,7 +264,7 @@ public class VolumePanel extends Handler
                       // Force stop right now
                       onStopSounds();
                   }
          -        
          +
                   synchronized (this) {
                       ToneGenerator toneGen = getOrCreateToneGenerator(streamType);
                       toneGen.startTone(ToneGenerator.TONE_PROP_BEEP);
          @@ -266,7 +274,7 @@ public class VolumePanel extends Handler
               }
           
               protected void onStopSounds() {
          -        
          +
                   synchronized (this) {
                       int numStreamTypes = AudioSystem.getNumStreamTypes();
                       for (int i = numStreamTypes - 1; i >= 0; i--) {
          @@ -277,17 +285,17 @@ public class VolumePanel extends Handler
                       }
                   }
               }
          -    
          +
               protected void onVibrate() {
          -        
          +
                   // Make sure we ended up in vibrate ringer mode
                   if (mAudioService.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE) {
                       return;
                   }
          -        
          +
                   mVibrator.vibrate(VIBRATE_DURATION);
               }
          -    
          +
               /**
                * Lock on this VolumePanel instance as long as you use the returned ToneGenerator.
                */
          @@ -303,13 +311,13 @@ public class VolumePanel extends Handler
           
               /**
                * Makes the small icon visible, and hides the large icon.
          -     * 
          +     *
                * @param index The volume index, where 0 means muted.
                */
               private void setSmallIcon(int index) {
                   mLargeStreamIcon.setVisibility(View.GONE);
                   mSmallStreamIcon.setVisibility(View.VISIBLE);
          -        
          +
                   mSmallStreamIcon.setImageResource(index == 0
                           ? com.android.internal.R.drawable.ic_volume_off_small
                           : com.android.internal.R.drawable.ic_volume_small);
          @@ -317,7 +325,7 @@ public class VolumePanel extends Handler
           
               /**
                * Makes the large image view visible with the given icon.
          -     * 
          +     *
                * @param resId The icon to display.
                */
               private void setLargeIcon(int resId) {
          @@ -329,7 +337,7 @@ public class VolumePanel extends Handler
               /**
                * Makes the ringer icon visible with an icon that is chosen
                * based on the current ringer mode.
          -     * 
          +     *
                * @param index
                */
               private void setRingerIcon(int index) {
          @@ -350,13 +358,13 @@ public class VolumePanel extends Handler
                   }
                   mLargeStreamIcon.setImageResource(icon);
               }
          -    
          +
               protected void onFreeResources() {
                   // We'll keep the views, just ditch the cached drawable and hence
                   // bitmaps
                   mSmallStreamIcon.setImageDrawable(null);
                   mLargeStreamIcon.setImageDrawable(null);
          -        
          +
                   synchronized (this) {
                       for (int i = mToneGenerators.length - 1; i >= 0; i--) {
                           if (mToneGenerators[i] != null) {
          @@ -366,26 +374,26 @@ public class VolumePanel extends Handler
                       }
                   }
               }
          -    
          +
               @Override
               public void handleMessage(Message msg) {
                   switch (msg.what) {
          -            
          +
                       case MSG_VOLUME_CHANGED: {
                           onVolumeChanged(msg.arg1, msg.arg2);
                           break;
                       }
          -            
          +
                       case MSG_FREE_RESOURCES: {
                           onFreeResources();
                           break;
                       }
          -            
          +
                       case MSG_STOP_SOUNDS: {
                           onStopSounds();
                           break;
                       }
          -            
          +
                       case MSG_PLAY_SOUND: {
                           onPlaySound(msg.arg1, msg.arg2);
                           break;
          @@ -395,8 +403,8 @@ public class VolumePanel extends Handler
                           onVibrate();
                           break;
                       }
          -            
          +
                   }
               }
          -    
          +
           }
          diff --git a/core/java/android/view/Window.java b/core/java/android/view/Window.java
          index a68436b0cc15ccbdd00997bd583d6c851fe6d457..428de67ee80ecd5cd62814245c41185820dea1a2 100644
          --- a/core/java/android/view/Window.java
          +++ b/core/java/android/view/Window.java
          @@ -524,6 +524,21 @@ public abstract class Window {
                   }
               }
           
          +    /**
          +     * Specify custom animations to use for the window, as per
          +     * {@link WindowManager.LayoutParams#windowAnimations
          +     * WindowManager.LayoutParams.windowAnimations}.  Providing anything besides
          +     * 0 here will override the animations the window would
          +     * normally retrieve from its theme.
          +     */
          +    public void setWindowAnimations(int resId) {
          +        final WindowManager.LayoutParams attrs = getAttributes();
          +        attrs.windowAnimations = resId;
          +        if (mCallback != null) {
          +            mCallback.onWindowAttributesChanged(attrs);
          +        }
          +    }
          +
               /**
                * Specify an explicit soft input mode to use for the window, as per
                * {@link WindowManager.LayoutParams#softInputMode
          diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java
          index 7e47ad1748a308b59470b55294778472c7bddf34..b87cc42f0e0580874cc4aba9b2d32fcb556dadd3 100644
          --- a/core/java/android/view/WindowManager.java
          +++ b/core/java/android/view/WindowManager.java
          @@ -16,6 +16,7 @@
           
           package android.view;
           
          +import android.content.pm.ActivityInfo;
           import android.graphics.PixelFormat;
           import android.os.IBinder;
           import android.os.Parcel;
          @@ -126,8 +127,6 @@ public interface WindowManager extends ViewManager {
                    * @see #TYPE_APPLICATION_MEDIA
                    * @see #TYPE_APPLICATION_SUB_PANEL
                    * @see #TYPE_APPLICATION_ATTACHED_DIALOG
          -         * @see #TYPE_INPUT_METHOD
          -         * @see #TYPE_INPUT_METHOD_DIALOG
                    * @see #TYPE_STATUS_BAR
                    * @see #TYPE_SEARCH_BAR
                    * @see #TYPE_PHONE
          @@ -514,26 +513,33 @@ public interface WindowManager extends ViewManager {
                   
                   /**
                    * Visibility state for {@link #softInputMode}: please hide any soft input
          -         * area.
          +         * area when normally appropriate (when the user is navigating
          +         * forward to your window).
                    */
                   public static final int SOFT_INPUT_STATE_HIDDEN = 2;
                   
          +        /**
          +         * Visibility state for {@link #softInputMode}: please always hide any
          +         * soft input area when this window receives focus.
          +         */
          +        public static final int SOFT_INPUT_STATE_ALWAYS_HIDDEN = 3;
          +        
                   /**
                    * Visibility state for {@link #softInputMode}: please show the soft
                    * input area when normally appropriate (when the user is navigating
                    * forward to your window).
                    */
          -        public static final int SOFT_INPUT_STATE_VISIBLE = 3;
          +        public static final int SOFT_INPUT_STATE_VISIBLE = 4;
                   
                   /**
                    * Visibility state for {@link #softInputMode}: please always make the
                    * soft input area visible when this window receives input focus.
                    */
          -        public static final int SOFT_INPUT_STATE_ALWAYS_VISIBLE = 4;
          +        public static final int SOFT_INPUT_STATE_ALWAYS_VISIBLE = 5;
                   
                   /**
                    * Mask for {@link #softInputMode} of the bits that determine the
          -         * way that the window should be adjusted to accomodate the soft
          +         * way that the window should be adjusted to accommodate the soft
                    * input window.
                    */
                   public static final int SOFT_INPUT_MASK_ADJUST = 0xf0;
          @@ -634,6 +640,14 @@ public interface WindowManager extends ViewManager {
                    */
                   public float dimAmount = 1.0f;
               
          +        /**
          +         * This can be used to override the user's preferred brightness of
          +         * the screen.  A value of less than 0, the default, means to use the
          +         * preferred screen brightness.  0 to 1 adjusts the brightness from
          +         * dark to full bright.
          +         */
          +        public float screenBrightness = -1.0f;
          +        
                   /**
                    * Identifier for this window.  This will usually be filled in for
                    * you.
          @@ -645,6 +659,17 @@ public interface WindowManager extends ViewManager {
                    */
                   public String packageName = null;
                   
          +        /**
          +         * Specific orientation value for a window.
          +         * May be any of the same values allowed
          +         * for {@link android.content.pm.ActivityInfo#screenOrientation}. 
          +         * If not set, a default value of 
          +         * {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_UNSPECIFIED} 
          +         * will be used.
          +         */
          +        public int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
          +        
          +        
                   public LayoutParams() {
                       super(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
                       type = TYPE_APPLICATION;
          @@ -719,9 +744,11 @@ public interface WindowManager extends ViewManager {
                       out.writeInt(windowAnimations);
                       out.writeFloat(alpha);
                       out.writeFloat(dimAmount);
          +            out.writeFloat(screenBrightness);
                       out.writeStrongBinder(token);
                       out.writeString(packageName);
                       TextUtils.writeToParcel(mTitle, out, parcelableFlags);
          +            out.writeInt(screenOrientation);
                   }
                   
                   public static final Parcelable.Creator CREATOR
          @@ -752,9 +779,11 @@ public interface WindowManager extends ViewManager {
                       windowAnimations = in.readInt();
                       alpha = in.readFloat();
                       dimAmount = in.readFloat();
          +            screenBrightness = in.readFloat();
                       token = in.readStrongBinder();
                       packageName = in.readString();
                       mTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
          +            screenOrientation = in.readInt();
                   }
               
                   public static final int LAYOUT_CHANGED = 1<<0;
          @@ -767,6 +796,8 @@ public interface WindowManager extends ViewManager {
                   public static final int ALPHA_CHANGED = 1<<7;
                   public static final int MEMORY_TYPE_CHANGED = 1<<8;
                   public static final int SOFT_INPUT_MODE_CHANGED = 1<<9;
          +        public static final int SCREEN_ORIENTATION_CHANGED = 1<<10;
          +        public static final int SCREEN_BRIGHTNESS_CHANGED = 1<<11;
               
                   public final int copyFrom(LayoutParams o) {
                       int changes = 0;
          @@ -861,7 +892,15 @@ public interface WindowManager extends ViewManager {
                           dimAmount = o.dimAmount;
                           changes |= DIM_AMOUNT_CHANGED;
                       }
          +            if (screenBrightness != o.screenBrightness) {
          +                screenBrightness = o.screenBrightness;
          +                changes |= SCREEN_BRIGHTNESS_CHANGED;
          +            }
               
          +            if (screenOrientation != o.screenOrientation) {
          +                screenOrientation = o.screenOrientation;
          +                changes |= SCREEN_ORIENTATION_CHANGED;
          +            }
                       return changes;
                   }
               
          @@ -907,6 +946,10 @@ public interface WindowManager extends ViewManager {
                           sb.append(" wanim=0x");
                           sb.append(Integer.toHexString(windowAnimations));
                       }
          +            if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
          +                sb.append(" or=");
          +                sb.append(screenOrientation);
          +            }
                       sb.append('}');
                       return sb.toString();
                   }
          diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
          index 6af4915f8185a618e203e63088216a79f42de555..220869c1d236ef6dbdf4da2f2508d414ed8cb4d0 100644
          --- a/core/java/android/view/WindowManagerPolicy.java
          +++ b/core/java/android/view/WindowManagerPolicy.java
          @@ -54,7 +54,7 @@ import android.view.animation.Animation;
            * window manager is a very low-level system service, there are few other
            * system services you can call with this lock held.  It is explicitly okay to
            * make calls into the package manager and power manager; it is explicitly not
          - * okay to make calls into the activity manager.  Note that
          + * okay to make calls into the activity manager or most other services.  Note that
            * {@link android.content.Context#checkPermission(String, int, int)} and
            * variations require calling into the activity manager.
            * 
          Li
          Called with the input thread lock held. This lock can be @@ -129,13 +129,21 @@ public interface WindowManagerPolicy { Rect contentFrame, Rect visibleFrame); /** - * Retrieve the current frame of the window. Must be called with the - * window manager lock held. + * Retrieve the current frame of the window that has been assigned by + * the window manager. Must be called with the window manager lock held. * * @return Rect The rectangle holding the window frame. */ public Rect getFrameLw(); + /** + * Retrieve the current frame of the window that is actually shown. + * Must be called with the window manager lock held. + * + * @return Rect The rectangle holding the shown window frame. + */ + public Rect getShownFrameLw(); + /** * Retrieve the frame of the display that this window was last * laid out in. Must be called with the @@ -273,9 +281,12 @@ public interface WindowManagerPolicy { * false, this is based on the currently requested * frame, which any current animation will be moving * towards. + * @param onlyOpaque If true, this will only pass if the window is + * also opaque. * @return Returns true if the window is both full screen and opaque */ - public boolean fillsScreenLw(int width, int height, boolean shownFrame); + public boolean fillsScreenLw(int width, int height, boolean shownFrame, + boolean onlyOpaque); /** * Returns true if this window has been shown on screen at some time in @@ -289,16 +300,18 @@ public interface WindowManagerPolicy { * Can be called by the policy to force a window to be hidden, * regardless of whether the client or window manager would like * it shown. Must be called with the window manager lock held. + * Returns true if {@link #showLw} was last called for the window. */ - public void hideLw(boolean doAnimation); + public boolean hideLw(boolean doAnimation); /** * Can be called to undo the effect of {@link #hideLw}, allowing a * window to be shown as long as the window manager and client would * also like it to be shown. Must be called with the window manager * lock held. + * Returns true if {@link #hideLw} was last called for the window. */ - public void showLw(boolean doAnimation); + public boolean showLw(boolean doAnimation); } /** No transition happening. */ @@ -735,10 +748,17 @@ public interface WindowManagerPolicy { * ActivityInfo.SCREEN_ORIENTATION_PORTRAIT}), return a surface * rotation. */ - public int rotationForOrientation(int orientation); + public int rotationForOrientationLw(int orientation, int lastRotation, + boolean displayEnabled); + + /** + * Called when the system is mostly done booting to dentermine whether + * the system should go into safe mode. + */ + public boolean detectSafeMode(); /** - * Called when the system is mostly done booting + * Called when the system is mostly done booting. */ public void systemReady(); @@ -761,5 +781,16 @@ public interface WindowManagerPolicy { */ public boolean isCheekPressedAgainstScreen(MotionEvent ev); - public void setCurrentOrientation(int newOrientation); + public void setCurrentOrientationLw(int newOrientation); + + /** + * Call from application to perform haptic feedback on its window. + */ + public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always); + + /** + * Called when we have stopped keeping the screen on because a window + * requesting this is no longer visible. + */ + public void screenOnStoppedLw(); } diff --git a/core/java/android/view/WindowOrientationListener.java b/core/java/android/view/WindowOrientationListener.java new file mode 100755 index 0000000000000000000000000000000000000000..f1f5f707285d1b1402bcaa48a0f538e5cbfee77c --- /dev/null +++ b/core/java/android/view/WindowOrientationListener.java @@ -0,0 +1,196 @@ +/* + * 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. + */ + +package android.view; + +import android.content.Context; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.util.Config; +import android.util.Log; + +/** + * A special helper class used by the WindowManager + * for receiving notifications from the SensorManager when + * the orientation of the device has changed. + * @hide + */ +public abstract class WindowOrientationListener { + private static final String TAG = "WindowOrientationListener"; + private static final boolean DEBUG = false; + private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV; + private SensorManager mSensorManager; + private boolean mEnabled = false; + private int mRate; + private Sensor mSensor; + private SensorEventListener mSensorEventListener; + private int mSensorRotation = -1; + + /** + * Creates a new WindowOrientationListener. + * + * @param context for the WindowOrientationListener. + */ + public WindowOrientationListener(Context context) { + this(context, SensorManager.SENSOR_DELAY_NORMAL); + } + + /** + * Creates a new WindowOrientationListener. + * + * @param context for the WindowOrientationListener. + * @param rate at which sensor events are processed (see also + * {@link android.hardware.SensorManager SensorManager}). Use the default + * value of {@link android.hardware.SensorManager#SENSOR_DELAY_NORMAL + * SENSOR_DELAY_NORMAL} for simple screen orientation change detection. + */ + public WindowOrientationListener(Context context, int rate) { + mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); + mRate = rate; + mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + if (mSensor != null) { + // Create listener only if sensors do exist + mSensorEventListener = new SensorEventListenerImpl(); + } + } + + /** + * Enables the WindowOrientationListener so it will monitor the sensor and call + * {@link #onOrientationChanged} when the device orientation changes. + */ + public void enable() { + if (mSensor == null) { + Log.w(TAG, "Cannot detect sensors. Not enabled"); + return; + } + if (mEnabled == false) { + if (localLOGV) Log.d(TAG, "WindowOrientationListener enabled"); + mSensorManager.registerListener(mSensorEventListener, mSensor, mRate); + mEnabled = true; + } + } + + /** + * Disables the WindowOrientationListener. + */ + public void disable() { + if (mSensor == null) { + Log.w(TAG, "Cannot detect sensors. Invalid disable"); + return; + } + if (mEnabled == true) { + if (localLOGV) Log.d(TAG, "WindowOrientationListener disabled"); + mSensorManager.unregisterListener(mSensorEventListener); + mEnabled = false; + } + } + + class SensorEventListenerImpl implements SensorEventListener { + private static final int _DATA_X = 0; + private static final int _DATA_Y = 1; + private static final int _DATA_Z = 2; + // Angle around x-axis thats considered almost perfect vertical to hold + // the device + private static final int PIVOT = 30; + // Angle around x-asis that's considered almost too vertical. Beyond + // this angle will not result in any orientation changes. f phone faces uses, + // the device is leaning backward. + private static final int PIVOT_UPPER = 65; + // Angle about x-axis that's considered negative vertical. Beyond this + // angle will not result in any orientation changes. If phone faces uses, + // the device is leaning forward. + private static final int PIVOT_LOWER = 0; + // Upper threshold limit for switching from portrait to landscape + private static final int PL_UPPER = 280; + // Lower threshold limit for switching from landscape to portrait + private static final int LP_LOWER = 320; + // Lower threshold limt for switching from portrait to landscape + private static final int PL_LOWER = 240; + // Upper threshold limit for switching from landscape to portrait + private static final int LP_UPPER = 360; + + // Internal value used for calculating linear variant + private static final float PL_LINEAR_FACTOR = + ((float)(PL_UPPER-PL_LOWER))/((float)(PIVOT_UPPER-PIVOT_LOWER)); + // Internal value used for calculating linear variant + private static final float LP_LINEAR_FACTOR = + ((float)(LP_UPPER - LP_LOWER))/((float)(PIVOT_UPPER-PIVOT_LOWER)); + + public void onSensorChanged(SensorEvent event) { + float[] values = event.values; + float X = values[_DATA_X]; + float Y = values[_DATA_Y]; + float Z = values[_DATA_Z]; + float OneEightyOverPi = 57.29577957855f; + float gravity = (float) Math.sqrt(X*X+Y*Y+Z*Z); + float zyangle = Math.abs((float)Math.asin(Z/gravity)*OneEightyOverPi); + int rotation = mSensorRotation; + if ((zyangle <= PIVOT_UPPER) && (zyangle >= PIVOT_LOWER)) { + // Check orientation only if the phone is flat enough + // Don't trust the angle if the magnitude is small compared to the y value + float angle = (float)Math.atan2(Y, -X) * OneEightyOverPi; + int orientation = 90 - (int)Math.round(angle); + // normalize to 0 - 359 range + while (orientation >= 360) { + orientation -= 360; + } + while (orientation < 0) { + orientation += 360; + } + + float delta = (float)Math.abs(zyangle - PIVOT); + if (((orientation >= 0) && (orientation <= LP_UPPER)) || + (orientation >= PL_LOWER)) { + float threshold; + if (mSensorRotation == Surface.ROTATION_90) { + threshold = LP_LOWER + (LP_LINEAR_FACTOR * delta) ; + } else { + threshold = PL_UPPER - (PL_LINEAR_FACTOR * delta); + } + rotation = (orientation >= PL_LOWER && + orientation <= threshold) ? Surface.ROTATION_90 : Surface.ROTATION_0; + } + + } + if (rotation != mSensorRotation) { + mSensorRotation = rotation; + onOrientationChanged(mSensorRotation); + } + } + + public void onAccuracyChanged(Sensor sensor, int accuracy) { + + } + } + + /* + * Returns true if sensor is enabled and false otherwise + */ + public boolean canDetectOrientation() { + return mSensor != null; + } + + /** + * Called when the rotation view of the device has changed. + * Can be either Surface.ROTATION_90 or Surface.ROTATION_0. + * @param rotation The new orientation of the device. + * + * @see #ORIENTATION_UNKNOWN + */ + abstract public void onOrientationChanged(int rotation); +} diff --git a/core/java/android/view/animation/AlphaAnimation.java b/core/java/android/view/animation/AlphaAnimation.java index 16a10a47c148df55989caf98b2ad0aa3d6072555..651fe458ab4b3bf019ac682ec72fd6fd4ecc09cc 100644 --- a/core/java/android/view/animation/AlphaAnimation.java +++ b/core/java/android/view/animation/AlphaAnimation.java @@ -31,7 +31,7 @@ public class AlphaAnimation extends Animation { private float mToAlpha; /** - * Constructor used whan an AlphaAnimation is loaded from a resource. + * Constructor used when an AlphaAnimation is loaded from a resource. * * @param context Application context to use * @param attrs Attribute set from which to read values diff --git a/core/java/android/view/animation/Animation.java b/core/java/android/view/animation/Animation.java index 92643989e6128983680318bef2399dcc47f3b6e4..a6627609e3be9d929b073ad9983ddab8eefba748 100644 --- a/core/java/android/view/animation/Animation.java +++ b/core/java/android/view/animation/Animation.java @@ -20,13 +20,14 @@ import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.TypedValue; +import android.graphics.RectF; /** * Abstraction for an Animation that can be applied to Views, Surfaces, or * other objects. See the {@link android.view.animation animation package * description file}. */ -public abstract class Animation { +public abstract class Animation implements Cloneable { /** * Repeat the animation indefinitely. */ @@ -174,8 +175,13 @@ public abstract class Animation { */ private int mZAdjustment; - // Indicates what was the last value returned by getTransformation() private boolean mMore = true; + private boolean mOneMoreTime = true; + + RectF mPreviousRegion = new RectF(); + RectF mRegion = new RectF(); + Transformation mTransformation = new Transformation(); + Transformation mPreviousTransformation = new Transformation(); /** * Creates a new animation with a duration of 0ms, the default interpolator, with @@ -217,16 +223,29 @@ public abstract class Animation { a.recycle(); } + @Override + protected Animation clone() throws CloneNotSupportedException { + final Animation animation = (Animation) super.clone(); + animation.mPreviousRegion = new RectF(); + animation.mRegion = new RectF(); + animation.mTransformation = new Transformation(); + animation.mPreviousTransformation = new Transformation(); + return animation; + } + /** * Reset the initialization state of this animation. * * @see #initialize(int, int, int, int) */ public void reset() { + mPreviousRegion.setEmpty(); + mPreviousTransformation.clear(); mInitialized = false; mCycleFlip = false; mRepeated = 0; mMore = true; + mOneMoreTime = true; } /** @@ -255,10 +274,8 @@ public abstract class Animation { * @param parentHeight Height of the animated object's parent */ public void initialize(int width, int height, int parentWidth, int parentHeight) { + reset(); mInitialized = true; - mCycleFlip = false; - mRepeated = 0; - mMore = true; } /** @@ -323,6 +340,7 @@ public abstract class Animation { * to run. */ public void restrictDuration(long durationMillis) { + // If we start after the duration, then we just won't run. if (mStartOffset > durationMillis) { mStartOffset = durationMillis; mDuration = 0; @@ -332,11 +350,26 @@ public abstract class Animation { long dur = mDuration + mStartOffset; if (dur > durationMillis) { - mDuration = dur = durationMillis-mStartOffset; + mDuration = durationMillis-mStartOffset; + dur = durationMillis; + } + // If the duration is 0 or less, then we won't run. + if (mDuration <= 0) { + mDuration = 0; + mRepeatCount = 0; + return; } + // Reduce the number of repeats to keep below the maximum duration. + // The comparison between mRepeatCount and duration is to catch + // overflows after multiplying them. if (mRepeatCount < 0 || mRepeatCount > durationMillis || (dur*mRepeatCount) > durationMillis) { - mRepeatCount = (int)(durationMillis/dur); + // Figure out how many times to do the animation. Subtract 1 since + // repeat count is the number of times to repeat so 0 runs once. + mRepeatCount = (int)(durationMillis/dur) - 1; + if (mRepeatCount < 0) { + mRepeatCount = 0; + } } } @@ -399,7 +432,7 @@ public abstract class Animation { * Sets how many times the animation should be repeated. If the repeat * count is 0, the animation is never repeated. If the repeat count is * greater than 0 or {@link #INFINITE}, the repeat mode will be taken - * into account. The repeat count if 0 by default. + * into account. The repeat count is 0 by default. * * @param repeatCount the number of times the animation should be repeated * @attr ref android.R.styleable#Animation_repeatCount @@ -707,6 +740,11 @@ public abstract class Animation { } } + if (!mMore && mOneMoreTime) { + mOneMoreTime = false; + return true; + } + return mMore; } @@ -765,7 +803,59 @@ public abstract class Animation { return value; } } - + + /** + * @param left + * @param top + * @param right + * @param bottom + * @param invalidate + * @param transformation + * + * @hide + */ + public void getInvalidateRegion(int left, int top, int right, int bottom, + RectF invalidate, Transformation transformation) { + + final RectF tempRegion = mRegion; + final RectF previousRegion = mPreviousRegion; + + invalidate.set(left, top, right, bottom); + transformation.getMatrix().mapRect(invalidate); + // Enlarge the invalidate region to account for rounding errors + invalidate.inset(-1.0f, -1.0f); + tempRegion.set(invalidate); + invalidate.union(previousRegion); + + previousRegion.set(tempRegion); + + final Transformation tempTransformation = mTransformation; + final Transformation previousTransformation = mPreviousTransformation; + + tempTransformation.set(transformation); + transformation.set(previousTransformation); + previousTransformation.set(tempTransformation); + } + + /** + * @param left + * @param top + * @param right + * @param bottom + * + * @hide + */ + public void initializeInvalidateRegion(int left, int top, int right, int bottom) { + final RectF region = mPreviousRegion; + region.set(left, top, right, bottom); + // Enlarge the invalidate region to account for rounding errors + region.inset(-1.0f, -1.0f); + if (mFillBefore) { + final Transformation previousTransformation = mPreviousTransformation; + applyTransformation(0.0f, previousTransformation); + } + } + /** * Utility class to parse a string description of a size. */ diff --git a/core/java/android/view/animation/AnimationSet.java b/core/java/android/view/animation/AnimationSet.java index 688da70edcc1a5c876350cdb52fd65a3e4218e6e..98b259451ae18cacd2fc4e9afb699f57fe43676f 100644 --- a/core/java/android/view/animation/AnimationSet.java +++ b/core/java/android/view/animation/AnimationSet.java @@ -19,6 +19,7 @@ package android.view.animation; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; +import android.graphics.RectF; import java.util.ArrayList; import java.util.List; @@ -39,6 +40,7 @@ public class AnimationSet extends Animation { private static final int PROPERTY_SHARE_INTERPOLATOR_MASK = 0x10; private static final int PROPERTY_DURATION_MASK = 0x20; private static final int PROPERTY_MORPH_MATRIX_MASK = 0x40; + private static final int PROPERTY_CHANGE_BOUNDS_MASK = 0x80; private int mFlags = 0; @@ -51,7 +53,7 @@ public class AnimationSet extends Animation { private long[] mStoredOffsets; /** - * Constructor used whan an AnimationSet is loaded from a resource. + * Constructor used when an AnimationSet is loaded from a resource. * * @param context Application context to use * @param attrs Attribute set from which to read values @@ -82,6 +84,22 @@ public class AnimationSet extends Animation { init(); } + @Override + protected AnimationSet clone() throws CloneNotSupportedException { + final AnimationSet animation = (AnimationSet) super.clone(); + animation.mTempTransformation = new Transformation(); + animation.mAnimations = new ArrayList(); + + final int count = mAnimations.size(); + final ArrayList animations = mAnimations; + + for (int i = 0; i < count; i++) { + animation.mAnimations.add(animations.get(i).clone()); + } + + return animation; + } + private void setFlag(int mask, boolean value) { if (value) { mFlags |= mask; @@ -145,6 +163,11 @@ public class AnimationSet extends Animation { mFlags |= PROPERTY_MORPH_MATRIX_MASK; } + boolean changeBounds = (mFlags & PROPERTY_CHANGE_BOUNDS_MASK) == 0; + if (changeBounds && a.willChangeTransformationMatrix()) { + mFlags |= PROPERTY_CHANGE_BOUNDS_MASK; + } + if (mAnimations.size() == 1) { mDuration = a.getStartOffset() + a.getDuration(); mLastEnd = mStartOffset + mDuration; @@ -239,7 +262,32 @@ public class AnimationSet extends Animation { } return duration; } - + + /** + * @hide + */ + public void initializeInvalidateRegion(int left, int top, int right, int bottom) { + final RectF region = mPreviousRegion; + region.set(left, top, right, bottom); + region.inset(-1.0f, -1.0f); + + if (mFillBefore) { + final int count = mAnimations.size(); + final ArrayList animations = mAnimations; + final Transformation temp = mTempTransformation; + + final Transformation previousTransformation = mPreviousTransformation; + + for (int i = count - 1; i >= 0; --i) { + final Animation a = animations.get(i); + + temp.clear(); + a.applyTransformation(0.0f, temp); + previousTransformation.compose(temp); + } + } + } + /** * The transformation of an animation set is the concatenation of all of its * component animations. @@ -313,7 +361,7 @@ public class AnimationSet extends Animation { == PROPERTY_SHARE_INTERPOLATOR_MASK; boolean startOffsetSet = (mFlags & PROPERTY_START_OFFSET_MASK) == PROPERTY_START_OFFSET_MASK; - + if (shareInterpolator) { ensureInterpolator(); } @@ -327,7 +375,17 @@ public class AnimationSet extends Animation { final int repeatMode = mRepeatMode; final Interpolator interpolator = mInterpolator; final long startOffset = mStartOffset; - + + + long[] storedOffsets = mStoredOffsets; + if (startOffsetSet) { + if (storedOffsets == null || storedOffsets.length != count) { + storedOffsets = mStoredOffsets = new long[count]; + } + } else if (storedOffsets != null) { + storedOffsets = mStoredOffsets = null; + } + for (int i = 0; i < count; i++) { Animation a = children.get(i); if (durationSet) { @@ -346,42 +404,35 @@ public class AnimationSet extends Animation { a.setInterpolator(interpolator); } if (startOffsetSet) { - a.setStartOffset(startOffset); + long offset = a.getStartOffset(); + a.setStartOffset(offset + startOffset); + storedOffsets[i] = offset; } a.initialize(width, height, parentWidth, parentHeight); } } - /** - * @hide - * @param startOffset the startOffset to add to the children's startOffset - */ - void saveChildrenStartOffset(long startOffset) { - final ArrayList children = mAnimations; - final int count = children.size(); - long[] storedOffsets = mStoredOffsets = new long[count]; - - for (int i = 0; i < count; i++) { - Animation animation = children.get(i); - long offset = animation.getStartOffset(); - animation.setStartOffset(offset + startOffset); - storedOffsets[i] = offset; - } + @Override + public void reset() { + super.reset(); + restoreChildrenStartOffset(); } /** * @hide */ void restoreChildrenStartOffset() { + final long[] offsets = mStoredOffsets; + if (offsets == null) return; + final ArrayList children = mAnimations; final int count = children.size(); - final long[] offsets = mStoredOffsets; for (int i = 0; i < count; i++) { children.get(i).setStartOffset(offsets[i]); } } - + /** * @return All the child animations in this AnimationSet. Note that * this may include other AnimationSets, which are not expanded. @@ -394,4 +445,9 @@ public class AnimationSet extends Animation { public boolean willChangeTransformationMatrix() { return (mFlags & PROPERTY_MORPH_MATRIX_MASK) == PROPERTY_MORPH_MATRIX_MASK; } + + @Override + public boolean willChangeBounds() { + return (mFlags & PROPERTY_CHANGE_BOUNDS_MASK) == PROPERTY_CHANGE_BOUNDS_MASK; + } } diff --git a/core/java/android/view/animation/LayoutAnimationController.java b/core/java/android/view/animation/LayoutAnimationController.java index 9cfa8d7fc041cf68a59827ac02441ea5c43f5d97..882e738eaa119e50113dc4acad7fb2c05f0ccb86 100644 --- a/core/java/android/view/animation/LayoutAnimationController.java +++ b/core/java/android/view/animation/LayoutAnimationController.java @@ -318,9 +318,16 @@ public class LayoutAnimationController { * @see #getDelayForView(android.view.View) */ public final Animation getAnimationForView(View view) { - final long delay = getDelayForView(view); + final long delay = getDelayForView(view) + mAnimation.getStartOffset(); mMaxDelay = Math.max(mMaxDelay, delay); - return new DelayedAnimation(delay, mAnimation); + + try { + final Animation animation = mAnimation.clone(); + animation.setStartOffset(delay); + return animation; + } catch (CloneNotSupportedException e) { + return null; + } } /** @@ -425,149 +432,4 @@ public class LayoutAnimationController { */ public int index; } - - /** - * Encapsulates an animation and delays its start offset by a specified - * amount. This allows to reuse the same base animation for various views - * and get the effect of running multiple instances of the animation at - * different times. - */ - private static class DelayedAnimation extends Animation { - private final long mDelay; - private final Animation mAnimation; - - /** - * Creates a new delayed animation that will delay the controller's - * animation by the specified delay in milliseconds. - * - * @param delay the delay in milliseconds by which to offset the - * @param animation the animation to delay - */ - private DelayedAnimation(long delay, Animation animation) { - mDelay = delay; - mAnimation = animation; - } - - @Override - public boolean isInitialized() { - return mAnimation.isInitialized(); - } - - @Override - public void initialize(int width, int height, int parentWidth, int parentHeight) { - mAnimation.initialize(width, height, parentWidth, parentHeight); - } - - @Override - public void reset() { - mAnimation.reset(); - } - - @Override - public boolean getTransformation(long currentTime, Transformation outTransformation) { - final long oldOffset = mAnimation.getStartOffset(); - final boolean isSet = mAnimation instanceof AnimationSet; - if (isSet) { - AnimationSet set = ((AnimationSet) mAnimation); - set.saveChildrenStartOffset(mDelay); - } - mAnimation.setStartOffset(oldOffset + mDelay); - - boolean result = mAnimation.getTransformation(currentTime, - outTransformation); - - if (isSet) { - AnimationSet set = ((AnimationSet) mAnimation); - set.restoreChildrenStartOffset(); - } - mAnimation.setStartOffset(oldOffset); - - return result; - } - - @Override - public void setStartTime(long startTimeMillis) { - mAnimation.setStartTime(startTimeMillis); - } - - @Override - public long getStartTime() { - return mAnimation.getStartTime(); - } - - @Override - public void setInterpolator(Interpolator i) { - mAnimation.setInterpolator(i); - } - - @Override - public void setStartOffset(long startOffset) { - mAnimation.setStartOffset(startOffset); - } - - @Override - public void setDuration(long durationMillis) { - mAnimation.setDuration(durationMillis); - } - - @Override - public void scaleCurrentDuration(float scale) { - mAnimation.scaleCurrentDuration(scale); - } - - @Override - public void setRepeatMode(int repeatMode) { - mAnimation.setRepeatMode(repeatMode); - } - - @Override - public void setFillBefore(boolean fillBefore) { - mAnimation.setFillBefore(fillBefore); - } - - @Override - public void setFillAfter(boolean fillAfter) { - mAnimation.setFillAfter(fillAfter); - } - - @Override - public Interpolator getInterpolator() { - return mAnimation.getInterpolator(); - } - - @Override - public long getDuration() { - return mAnimation.getDuration(); - } - - @Override - public long getStartOffset() { - return mAnimation.getStartOffset() + mDelay; - } - - @Override - public int getRepeatMode() { - return mAnimation.getRepeatMode(); - } - - @Override - public boolean getFillBefore() { - return mAnimation.getFillBefore(); - } - - @Override - public boolean getFillAfter() { - return mAnimation.getFillAfter(); - } - - @Override - public boolean willChangeTransformationMatrix() { - return mAnimation.willChangeTransformationMatrix(); - } - - @Override - public boolean willChangeBounds() { - return mAnimation.willChangeBounds(); - } - } } diff --git a/core/java/android/view/animation/RotateAnimation.java b/core/java/android/view/animation/RotateAnimation.java index 2f51b91840802a8c6d82755f797521571cc427e1..284ccce10cf2403c4697ff03d4b35c37007b4043 100644 --- a/core/java/android/view/animation/RotateAnimation.java +++ b/core/java/android/view/animation/RotateAnimation.java @@ -40,7 +40,7 @@ public class RotateAnimation extends Animation { private float mPivotY; /** - * Constructor used whan an RotateAnimation is loaded from a resource. + * Constructor used when a RotateAnimation is loaded from a resource. * * @param context Application context to use * @param attrs Attribute set from which to read values diff --git a/core/java/android/view/animation/ScaleAnimation.java b/core/java/android/view/animation/ScaleAnimation.java index 122ed6da69c042ca4fa6e0719cbf22f205ede239..1a56c8b83759a9449c38dace6d7aad19494bae5d 100644 --- a/core/java/android/view/animation/ScaleAnimation.java +++ b/core/java/android/view/animation/ScaleAnimation.java @@ -40,7 +40,7 @@ public class ScaleAnimation extends Animation { private float mPivotY; /** - * Constructor used whan an ScaleAnimation is loaded from a resource. + * Constructor used when a ScaleAnimation is loaded from a resource. * * @param context Application context to use * @param attrs Attribute set from which to read values diff --git a/core/java/android/view/animation/TranslateAnimation.java b/core/java/android/view/animation/TranslateAnimation.java index bb139723f763db770c1b97cca21a31a6b1e87cbd..a785d437a1de9c764c19b11cced751f842594857 100644 --- a/core/java/android/view/animation/TranslateAnimation.java +++ b/core/java/android/view/animation/TranslateAnimation.java @@ -45,7 +45,7 @@ public class TranslateAnimation extends Animation { private float mToYDelta; /** - * Constructor used when an TranslateAnimation is loaded from a resource. + * Constructor used when a TranslateAnimation is loaded from a resource. * * @param context Application context to use * @param attrs Attribute set from which to read values diff --git a/core/java/android/view/inputmethod/BaseInputConnection.java b/core/java/android/view/inputmethod/BaseInputConnection.java index a6ce2931f0a23d7425a57cc024b11e88ac3a5574..deca910c6fbfb05423a45dd5aa1c9a98207b4c61 100644 --- a/core/java/android/view/inputmethod/BaseInputConnection.java +++ b/core/java/android/view/inputmethod/BaseInputConnection.java @@ -17,34 +17,386 @@ package android.view.inputmethod; import android.content.Context; +import android.content.res.TypedArray; +import android.os.Bundle; import android.os.Handler; -import android.os.Message; +import android.os.SystemClock; +import android.text.Editable; +import android.text.NoCopySpan; +import android.text.Selection; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.method.MetaKeyKeyListener; +import android.util.Log; +import android.util.LogPrinter; +import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.ViewRoot; +class ComposingText implements NoCopySpan { +} + /** * Base class for implementors of the InputConnection interface, taking care - * of implementing common system-oriented parts of the functionality. + * of most of the common behavior for providing a connection to an Editable. + * Implementors of this class will want to be sure to implement + * {@link #getEditable} to provide access to their own editable object. */ -public abstract class BaseInputConnection implements InputConnection { +public class BaseInputConnection implements InputConnection { + private static final boolean DEBUG = false; + private static final String TAG = "BaseInputConnection"; + static final Object COMPOSING = new ComposingText(); + final InputMethodManager mIMM; final Handler mH; final View mTargetView; + final boolean mDummyMode; - BaseInputConnection(InputMethodManager mgr) { + private Object[] mDefaultComposingSpans; + + Editable mEditable; + KeyCharacterMap mKeyCharacterMap; + + BaseInputConnection(InputMethodManager mgr, boolean dummyMode) { mIMM = mgr; mTargetView = null; mH = null; + mDummyMode = dummyMode; } - public BaseInputConnection(View targetView) { + public BaseInputConnection(View targetView, boolean dummyMode) { mIMM = (InputMethodManager)targetView.getContext().getSystemService( Context.INPUT_METHOD_SERVICE); mH = targetView.getHandler(); mTargetView = targetView; + mDummyMode = dummyMode; } + public static final void removeComposingSpans(Spannable text) { + text.removeSpan(COMPOSING); + Object[] sps = text.getSpans(0, text.length(), Object.class); + if (sps != null) { + for (int i=sps.length-1; i>=0; i--) { + Object o = sps[i]; + if ((text.getSpanFlags(o)&Spanned.SPAN_COMPOSING) != 0) { + text.removeSpan(o); + } + } + } + } + + public static void setComposingSpans(Spannable text) { + final Object[] sps = text.getSpans(0, text.length(), Object.class); + if (sps != null) { + for (int i=sps.length-1; i>=0; i--) { + final Object o = sps[i]; + if (o == COMPOSING) { + text.removeSpan(o); + continue; + } + final int fl = text.getSpanFlags(o); + if ((fl&(Spanned.SPAN_COMPOSING|Spanned.SPAN_POINT_MARK_MASK)) + != (Spanned.SPAN_COMPOSING|Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)) { + text.setSpan(o, text.getSpanStart(o), text.getSpanEnd(o), + (fl&Spanned.SPAN_POINT_MARK_MASK) + | Spanned.SPAN_COMPOSING + | Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } + } + + text.setSpan(COMPOSING, 0, text.length(), + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING); + } + + public static int getComposingSpanStart(Spannable text) { + return text.getSpanStart(COMPOSING); + } + + public static int getComposingSpanEnd(Spannable text) { + return text.getSpanEnd(COMPOSING); + } + + /** + * Return the target of edit operations. The default implementation + * returns its own fake editable that is just used for composing text; + * subclasses that are real text editors should override this and + * supply their own. + */ + public Editable getEditable() { + if (mEditable == null) { + mEditable = Editable.Factory.getInstance().newEditable(""); + Selection.setSelection(mEditable, 0); + } + return mEditable; + } + + /** + * Default implementation does nothing. + */ + public boolean beginBatchEdit() { + return false; + } + + /** + * Default implementation does nothing. + */ + public boolean endBatchEdit() { + return false; + } + + /** + * Default implementation uses + * {@link MetaKeyKeyListener#clearMetaKeyState(long, int) + * MetaKeyKeyListener.clearMetaKeyState(long, int)} to clear the state. + */ + public boolean clearMetaKeyStates(int states) { + final Editable content = getEditable(); + if (content == null) return false; + MetaKeyKeyListener.clearMetaKeyState(content, states); + return true; + } + + /** + * Default implementation does nothing. + */ + public boolean commitCompletion(CompletionInfo text) { + return false; + } + + /** + * Default implementation replaces any existing composing text with + * the given text. In addition, only if dummy mode, a key event is + * sent for the new text and the current editable buffer cleared. + */ + public boolean commitText(CharSequence text, int newCursorPosition) { + if (DEBUG) Log.v(TAG, "commitText " + text); + replaceText(text, newCursorPosition, false); + sendCurrentText(); + return true; + } + + /** + * The default implementation performs the deletion around the current + * selection position of the editable text. + */ + public boolean deleteSurroundingText(int leftLength, int rightLength) { + if (DEBUG) Log.v(TAG, "deleteSurroundingText " + leftLength + + " / " + rightLength); + final Editable content = getEditable(); + if (content == null) return false; + + beginBatchEdit(); + + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + if (a > b) { + int tmp = a; + a = b; + b = tmp; + } + + // ignore the composing text. + int ca = getComposingSpanStart(content); + int cb = getComposingSpanEnd(content); + if (cb < ca) { + int tmp = ca; + ca = cb; + cb = tmp; + } + if (ca != -1 && cb != -1) { + if (ca < a) a = ca; + if (cb > b) b = cb; + } + + int deleted = 0; + + if (leftLength > 0) { + int start = a - leftLength; + if (start < 0) start = 0; + content.delete(start, a); + deleted = a - start; + } + + if (rightLength > 0) { + b = b - deleted; + + int end = b + rightLength; + if (end > content.length()) end = content.length(); + + content.delete(b, end); + } + + endBatchEdit(); + + return true; + } + + /** + * The default implementation removes the composing state from the + * current editable text. In addition, only if dummy mode, a key event is + * sent for the new text and the current editable buffer cleared. + */ + public boolean finishComposingText() { + if (DEBUG) Log.v(TAG, "finishComposingText"); + final Editable content = getEditable(); + if (content != null) { + beginBatchEdit(); + removeComposingSpans(content); + endBatchEdit(); + sendCurrentText(); + } + return true; + } + + /** + * The default implementation uses TextUtils.getCapsMode to get the + * cursor caps mode for the current selection position in the editable + * text, unless in dummy mode in which case 0 is always returned. + */ + public int getCursorCapsMode(int reqModes) { + if (mDummyMode) return 0; + + final Editable content = getEditable(); + if (content == null) return 0; + + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + if (a > b) { + int tmp = a; + a = b; + b = tmp; + } + + return TextUtils.getCapsMode(content, a, reqModes); + } + + /** + * The default implementation always returns null. + */ + public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { + return null; + } + + /** + * The default implementation returns the given amount of text from the + * current cursor position in the buffer. + */ + public CharSequence getTextBeforeCursor(int length, int flags) { + final Editable content = getEditable(); + if (content == null) return null; + + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + if (a > b) { + int tmp = a; + a = b; + b = tmp; + } + + if (length > a) { + length = a; + } + + if ((flags&GET_TEXT_WITH_STYLES) != 0) { + return content.subSequence(a - length, a); + } + return TextUtils.substring(content, a - length, a); + } + + /** + * The default implementation returns the given amount of text from the + * current cursor position in the buffer. + */ + public CharSequence getTextAfterCursor(int length, int flags) { + final Editable content = getEditable(); + if (content == null) return null; + + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + if (a > b) { + int tmp = a; + a = b; + b = tmp; + } + + if (b + length > content.length()) { + length = content.length() - b; + } + + + if ((flags&GET_TEXT_WITH_STYLES) != 0) { + return content.subSequence(b, b + length); + } + return TextUtils.substring(content, b, b + length); + } + + /** + * The default implementation does nothing. + */ + public boolean performEditorAction(int actionCode) { + return false; + } + + /** + * The default implementation does nothing. + */ + public boolean performContextMenuAction(int id) { + return false; + } + + /** + * The default implementation does nothing. + */ + public boolean performPrivateCommand(String action, Bundle data) { + return false; + } + + /** + * The default implementation places the given text into the editable, + * replacing any existing composing text. The new text is marked as + * in a composing state with the composing style. + */ + public boolean setComposingText(CharSequence text, int newCursorPosition) { + if (DEBUG) Log.v(TAG, "setComposingText " + text); + replaceText(text, newCursorPosition, true); + return true; + } + + /** + * The default implementation changes the selection position in the + * current editable text. + */ + public boolean setSelection(int start, int end) { + if (DEBUG) Log.v(TAG, "setSelection " + start + ", " + end); + final Editable content = getEditable(); + if (content == null) return false; + int len = content.length(); + if (start > len || end > len) { + // If the given selection is out of bounds, just ignore it. + // Most likely the text was changed out from under the IME, + // the the IME is going to have to update all of its state + // anyway. + return true; + } + if (start == end && MetaKeyKeyListener.getMetaState(content, + MetaKeyKeyListener.META_SELECTING) != 0) { + // If we are in selection mode, then we want to extend the + // selection instead of replacing it. + Selection.extendSelection(content, start); + } else { + Selection.setSelection(content, start, end); + } + return true; + } + /** * Provides standard implementation for sending a key event to the window * attached to the input connection's view. @@ -66,20 +418,161 @@ public abstract class BaseInputConnection implements InputConnection { } /** - * Provides standard implementation for hiding the status icon associated - * with the current input method. + * Updates InputMethodManager with the current fullscreen mode. */ - public boolean hideStatusIcon() { - mIMM.updateStatusIcon(0, null); + public boolean reportFullscreenMode(boolean enabled) { + mIMM.setFullscreenMode(enabled); return true; } - /** - * Provides standard implementation for showing the status icon associated - * with the current input method. - */ - public boolean showStatusIcon(String packageName, int resId) { - mIMM.updateStatusIcon(resId, packageName); - return true; + private void sendCurrentText() { + if (!mDummyMode) { + return; + } + + Editable content = getEditable(); + if (content != null) { + final int N = content.length(); + if (N == 0) { + return; + } + if (N == 1) { + // If it's 1 character, we have a chance of being + // able to generate normal key events... + if (mKeyCharacterMap == null) { + mKeyCharacterMap = KeyCharacterMap.load( + KeyCharacterMap.BUILT_IN_KEYBOARD); + } + char[] chars = new char[1]; + content.getChars(0, 1, chars, 0); + KeyEvent[] events = mKeyCharacterMap.getEvents(chars); + if (events != null) { + for (int i=0; i=0 && b>= 0 && a != b) { + if (b < a) { + int tmp = a; + a = b; + b = tmp; + } + } + } + + if (composing) { + Spannable sp = null; + if (!(text instanceof Spannable)) { + sp = new SpannableStringBuilder(text); + text = sp; + if (mDefaultComposingSpans == null) { + Context context; + if (mTargetView != null) { + context = mTargetView.getContext(); + } else if (mIMM.mServedView != null) { + context = mIMM.mServedView.getContext(); + } else { + context = null; + } + if (context != null) { + TypedArray ta = context.getTheme() + .obtainStyledAttributes(new int[] { + com.android.internal.R.attr.candidatesTextStyleSpans + }); + CharSequence style = ta.getText(0); + ta.recycle(); + if (style != null && style instanceof Spanned) { + mDefaultComposingSpans = ((Spanned)style).getSpans( + 0, style.length(), Object.class); + } + } + } + if (mDefaultComposingSpans != null) { + for (int i = 0; i < mDefaultComposingSpans.length; ++i) { + sp.setSpan(mDefaultComposingSpans[i], 0, sp.length(), + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } + } else { + sp = (Spannable)text; + } + setComposingSpans(sp); + } + + if (DEBUG) Log.v(TAG, "Replacing from " + a + " to " + b + " with \"" + + text + "\", composing=" + composing + + ", type=" + text.getClass().getCanonicalName()); + + if (DEBUG) { + LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG); + lp.println("Current text:"); + TextUtils.dumpSpans(content, lp, " "); + lp.println("Composing text:"); + TextUtils.dumpSpans(text, lp, " "); + } + + // Position the cursor appropriately, so that after replacing the + // desired range of text it will be located in the correct spot. + // This allows us to deal with filters performing edits on the text + // we are providing here. + if (newCursorPosition > 0) { + newCursorPosition += b - 1; + } else { + newCursorPosition += a; + } + if (newCursorPosition < 0) newCursorPosition = 0; + if (newCursorPosition > content.length()) + newCursorPosition = content.length(); + Selection.setSelection(content, newCursorPosition); + + content.replace(a, b, text); + + if (DEBUG) { + LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG); + lp.println("Final text:"); + TextUtils.dumpSpans(content, lp, " "); + } + + endBatchEdit(); } } diff --git a/core/java/android/view/inputmethod/DefaultInputMethod.java b/core/java/android/view/inputmethod/DefaultInputMethod.java deleted file mode 100644 index 073b01c7b9ce6458beb9a95b4f0e163a2e37b81d..0000000000000000000000000000000000000000 --- a/core/java/android/view/inputmethod/DefaultInputMethod.java +++ /dev/null @@ -1,239 +0,0 @@ -package android.view.inputmethod; - -import android.graphics.Rect; -import android.os.Bundle; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Log; -import android.view.KeyEvent; -import android.view.MotionEvent; - -import com.android.internal.view.IInputContext; -import com.android.internal.view.IInputMethod; -import com.android.internal.view.IInputMethodCallback; -import com.android.internal.view.IInputMethodSession; -import com.android.internal.view.InputConnectionWrapper; - -/** - * This is the default input method that runs in the same context of the - * application that requests text input. It does nothing but returns false for - * any key events, so that all key events will be processed by the key listener - * of the focused text box. - * {@hide} - */ -public class DefaultInputMethod implements InputMethod, InputMethodSession { - private static IInputMethod sInstance = new SimpleInputMethod( - new DefaultInputMethod()); - - private static InputMethodInfo sProperty = new InputMethodInfo( - "android.text.inputmethod", DefaultInputMethod.class.getName(), - "Default", "android.text.inputmethod.defaultImeSettings"); - - private InputConnection mInputConnection; - - public static IInputMethod getInstance() { - return sInstance; - } - - public static InputMethodInfo getMetaInfo() { - return sProperty; - } - - public void bindInput(InputBinding binding) { - mInputConnection = binding.getConnection(); - } - - public void unbindInput() { - } - - public void createSession(SessionCallback callback) { - callback.sessionCreated(this); - } - - public void setSessionEnabled(InputMethodSession session, boolean enabled) { - } - - public void revokeSession(InputMethodSession session) { - } - - public void finishInput() { - mInputConnection.hideStatusIcon(); - } - - public void displayCompletions(CompletionInfo[] completions) { - } - - public void updateExtractedText(int token, ExtractedText text) { - } - - public void updateSelection(int oldSelStart, int oldSelEnd, - int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { - } - - public void updateCursor(Rect newCursor) { - } - - public void dispatchKeyEvent(int seq, KeyEvent event, EventCallback callback) { - callback.finishedEvent(seq, false); - } - - public void dispatchTrackballEvent(int seq, MotionEvent event, EventCallback callback) { - callback.finishedEvent(seq, false); - } - - public void restartInput(EditorInfo attribute) { - } - - public void attachToken(IBinder token) { - } - - public void startInput(EditorInfo attribute) { - mInputConnection - .showStatusIcon("android", com.android.internal.R.drawable.ime_qwerty); - } - - public void appPrivateCommand(String action, Bundle data) { - } - - public void hideSoftInput() { - } - - public void showSoftInput(int flags) { - } -} - -// ---------------------------------------------------------------------- - -class SimpleInputMethod extends IInputMethod.Stub { - final InputMethod mInputMethod; - - static class Session extends IInputMethodSession.Stub { - final InputMethodSession mSession; - - Session(InputMethodSession session) { - mSession = session; - } - - public void finishInput() { - mSession.finishInput(); - } - - public void updateSelection(int oldSelStart, int oldSelEnd, - int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { - mSession.updateSelection(oldSelStart, oldSelEnd, - newSelStart, newSelEnd, candidatesStart, candidatesEnd); - } - - public void updateCursor(Rect newCursor) { - mSession.updateCursor(newCursor); - } - - static class InputMethodEventCallbackWrapper implements InputMethodSession.EventCallback { - final IInputMethodCallback mCb; - InputMethodEventCallbackWrapper(IInputMethodCallback cb) { - mCb = cb; - } - public void finishedEvent(int seq, boolean handled) { - try { - mCb.finishedEvent(seq, handled); - } catch (RemoteException e) { - } - } - } - - public void dispatchKeyEvent(int seq, KeyEvent event, IInputMethodCallback callback) { - mSession.dispatchKeyEvent(seq, event, - new InputMethodEventCallbackWrapper(callback)); - } - - public void dispatchTrackballEvent(int seq, MotionEvent event, IInputMethodCallback callback) { - mSession.dispatchTrackballEvent(seq, event, - new InputMethodEventCallbackWrapper(callback)); - } - - public void displayCompletions(CompletionInfo[] completions) { - mSession.displayCompletions(completions); - } - - public void updateExtractedText(int token, ExtractedText text) { - mSession.updateExtractedText(token, text); - } - - public void appPrivateCommand(String action, Bundle data) { - mSession.appPrivateCommand(action, data); - } - } - - public SimpleInputMethod(InputMethod inputMethod) { - mInputMethod = inputMethod; - } - - public InputMethod getInternalInputMethod() { - return mInputMethod; - } - - public void attachToken(IBinder token) { - mInputMethod.attachToken(token); - } - - public void bindInput(InputBinding binding) { - InputConnectionWrapper ic = new InputConnectionWrapper( - IInputContext.Stub.asInterface(binding.getConnectionToken())); - InputBinding nu = new InputBinding(ic, binding); - mInputMethod.bindInput(nu); - } - - public void unbindInput() { - mInputMethod.unbindInput(); - } - - public void restartInput(EditorInfo attribute) { - mInputMethod.restartInput(attribute); - } - - public void startInput(EditorInfo attribute) { - mInputMethod.startInput(attribute); - } - - static class InputMethodSessionCallbackWrapper implements InputMethod.SessionCallback { - final IInputMethodCallback mCb; - InputMethodSessionCallbackWrapper(IInputMethodCallback cb) { - mCb = cb; - } - - public void sessionCreated(InputMethodSession session) { - try { - mCb.sessionCreated(new Session(session)); - } catch (RemoteException e) { - } - } - } - - public void createSession(IInputMethodCallback callback) throws RemoteException { - mInputMethod.createSession(new InputMethodSessionCallbackWrapper(callback)); - } - - public void setSessionEnabled(IInputMethodSession session, boolean enabled) throws RemoteException { - try { - InputMethodSession ls = ((Session)session).mSession; - mInputMethod.setSessionEnabled(ls, enabled); - } catch (ClassCastException e) { - Log.w("SimpleInputMethod", "Incoming session not of correct type: " + session, e); - } - } - - public void revokeSession(IInputMethodSession session) throws RemoteException { - try { - InputMethodSession ls = ((Session)session).mSession; - mInputMethod.revokeSession(ls); - } catch (ClassCastException e) { - Log.w("SimpleInputMethod", "Incoming session not of correct type: " + session, e); - } - } - - public void showSoftInput(boolean blah) { - } - - public void hideSoftInput() { - } -} diff --git a/core/java/android/view/inputmethod/EditorInfo.java b/core/java/android/view/inputmethod/EditorInfo.java index c0506913e3731609787e6841c73536502f52b009..b00e565956175f9f5fa1a408d4ab26e047f15d98 100644 --- a/core/java/android/view/inputmethod/EditorInfo.java +++ b/core/java/android/view/inputmethod/EditorInfo.java @@ -5,6 +5,7 @@ import android.os.Parcel; import android.os.Parcelable; import android.text.InputType; import android.text.TextUtils; +import android.util.Printer; /** * An EditorInfo describes several attributes of a text editing object @@ -21,20 +22,109 @@ public class EditorInfo implements InputType, Parcelable { * @see #TYPE_MASK_VARIATION * @see #TYPE_MASK_FLAGS */ - public int inputType = TYPE_CLASS_TEXT; + public int inputType = TYPE_NULL; /** - * A string supplying additional information about the content type that - * is private to a particular IME implementation. The string must be + * Set of bits in {@link #imeOptions} that provide alternative actions + * associated with the "enter" key. This both helps the IME provide + * better feedback about what the enter key will do, and also allows it + * to provide alternative mechanisms for providing that command. + */ + public static final int IME_MASK_ACTION = 0x000000ff; + + /** + * Bits of {@link #IME_MASK_ACTION}: no specific action has been + * associated with this editor, let the editor come up with its own if + * it can. + */ + public static final int IME_ACTION_UNSPECIFIED = 0x00000000; + + /** + * Bits of {@link #IME_MASK_ACTION}: there is no available action. + */ + public static final int IME_ACTION_NONE = 0x00000001; + + /** + * Bits of {@link #IME_MASK_ACTION}: the action key performs a "go" + * operation to take the user to the target of the text they typed. + * Typically used, for example, when entering a URL. + */ + public static final int IME_ACTION_GO = 0x00000002; + + /** + * Bits of {@link #IME_MASK_ACTION}: the action key performs a "search" + * operation, taking the user to the results of searching for the text + * the have typed (in whatever context is appropriate). + */ + public static final int IME_ACTION_SEARCH = 0x00000003; + + /** + * Bits of {@link #IME_MASK_ACTION}: the action key performs a "send" + * operation, delivering the text to its target. This is typically used + * when composing a message. + */ + public static final int IME_ACTION_SEND = 0x00000004; + + /** + * Bits of {@link #IME_MASK_ACTION}: the action key performs a "next" + * operation, taking the user to the next field that will accept text. + */ + public static final int IME_ACTION_NEXT = 0x00000005; + + /** + * Bits of {@link #IME_MASK_ACTION}: the action key performs a "done" + * operation, typically meaning the IME will be closed. + */ + public static final int IME_ACTION_DONE = 0x00000006; + + /** + * Flag of {@link #imeOptions}: used in conjunction with + * {@link #IME_MASK_ACTION}, this indicates that the action should not + * be available in-line as the same as a "enter" key. Typically this is + * because the action has such a significant impact or is not recoverable + * enough that accidentally hitting it should be avoided, such as sending + * a message. + */ + public static final int IME_FLAG_NO_ENTER_ACTION = 0x40000000; + + /** + * Generic unspecified type for {@link #imeOptions}. + */ + public static final int IME_NULL = 0x00000000; + + /** + * Extended type information for the editor, to help the IME better + * integrate with it. + */ + public int imeOptions = IME_NULL; + + /** + * A string supplying additional information options that are + * private to a particular IME implementation. The string must be * scoped to a package owned by the implementation, to ensure there are * no conflicts between implementations, but other than that you can put * whatever you want in it to communicate with the IME. For example, * you could have a string that supplies an argument like * "com.example.myapp.SpecialMode=3". This field is can be - * filled in from the {@link android.R.attr#editorPrivateContentType} + * filled in from the {@link android.R.attr#privateImeOptions} * attribute of a TextView. */ - public String privateContentType = null; + public String privateImeOptions = null; + + /** + * In some cases an IME may be able to display an arbitrary label for + * a command the user can perform, which you can specify here. You can + * not count on this being used. + */ + public CharSequence actionLabel = null; + + /** + * If {@link #actionLabel} has been given, this is the id for that command + * when the user presses its button that is delivered back with + * {@link InputConnection#performEditorAction(int) + * InputConnection.performEditorAction()}. + */ + public int actionId = 0; /** * The text offset of the start of the selection at the time editing @@ -70,6 +160,26 @@ public class EditorInfo implements InputType, Parcelable { */ public CharSequence label; + /** + * Name of the package that owns this editor. + */ + public String packageName; + + /** + * Identifier for the editor's field. This is optional, and may be + * 0. By default it is filled in with the result of + * {@link android.view.View#getId() View.getId()} on the View that + * is being edited. + */ + public int fieldId; + + /** + * Additional name for the editor's field. This can supply additional + * name information for the field. By default it is null. The actual + * contents have no meaning. + */ + public String fieldName; + /** * Any extra data to supply to the input method. This is for extended * communication with specific input methods; the name fields in the @@ -80,6 +190,27 @@ public class EditorInfo implements InputType, Parcelable { */ public Bundle extras; + /** + * Write debug output of this object. + */ + public void dump(Printer pw, String prefix) { + pw.println(prefix + "inputType=0x" + Integer.toHexString(inputType) + + " imeOptions=0x" + Integer.toHexString(imeOptions) + + " privateImeOptions=" + privateImeOptions); + pw.println(prefix + "actionLabel=" + actionLabel + + " actionId=" + actionId); + pw.println(prefix + "initialSelStart=" + initialSelStart + + " initialSelEnd=" + initialSelEnd + + " initialCapsMode=0x" + + Integer.toHexString(initialCapsMode)); + pw.println(prefix + "hintText=" + hintText + + " label=" + label); + pw.println(prefix + "packageName=" + packageName + + " fieldId=" + fieldId + + " fieldName=" + fieldName); + pw.println(prefix + "extras=" + extras); + } + /** * Used to package this object into a {@link Parcel}. * @@ -88,12 +219,18 @@ public class EditorInfo implements InputType, Parcelable { */ public void writeToParcel(Parcel dest, int flags) { dest.writeInt(inputType); - dest.writeString(privateContentType); + dest.writeInt(imeOptions); + dest.writeString(privateImeOptions); + TextUtils.writeToParcel(actionLabel, dest, flags); + dest.writeInt(actionId); dest.writeInt(initialSelStart); dest.writeInt(initialSelEnd); dest.writeInt(initialCapsMode); TextUtils.writeToParcel(hintText, dest, flags); TextUtils.writeToParcel(label, dest, flags); + dest.writeString(packageName); + dest.writeInt(fieldId); + dest.writeString(fieldName); dest.writeBundle(extras); } @@ -104,12 +241,18 @@ public class EditorInfo implements InputType, Parcelable { public EditorInfo createFromParcel(Parcel source) { EditorInfo res = new EditorInfo(); res.inputType = source.readInt(); - res.privateContentType = source.readString(); + res.imeOptions = source.readInt(); + res.privateImeOptions = source.readString(); + res.actionLabel = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); + res.actionId = source.readInt(); res.initialSelStart = source.readInt(); res.initialSelEnd = source.readInt(); res.initialCapsMode = source.readInt(); res.hintText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); res.label = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); + res.packageName = source.readString(); + res.fieldId = source.readInt(); + res.fieldName = source.readString(); res.extras = source.readBundle(); return res; } diff --git a/core/java/android/view/inputmethod/ExtractedText.java b/core/java/android/view/inputmethod/ExtractedText.java index 0ca3c79349d752be955b88470598a8d636af0186..c2851d6ca66326b0bdba83ab64c8023453c05ad7 100644 --- a/core/java/android/view/inputmethod/ExtractedText.java +++ b/core/java/android/view/inputmethod/ExtractedText.java @@ -18,6 +18,22 @@ public class ExtractedText implements Parcelable { */ public int startOffset; + /** + * If the content is a report of a partial text change, this is the + * offset where the change starts and it runs until + * {@link #partialEndOffset}. If the content is the full text, this + * field is -1. + */ + public int partialStartOffset; + + /** + * If the content is a report of a partial text change, this is the offset + * where the change ends. Note that the actual text may be larger or + * smaller than the difference between this and {@link #partialEndOffset}, + * meaning a reduction or increase, respectively, in the total text. + */ + public int partialEndOffset; + /** * The offset where the selection currently starts within the extracted * text. The real selection start position is at @@ -38,6 +54,11 @@ public class ExtractedText implements Parcelable { */ public static final int FLAG_SINGLE_LINE = 0x0001; + /** + * Bit for {@link #flags}: set if the editor is currently in selection mode. + */ + public static final int FLAG_SELECTING = 0x0002; + /** * Additional bit flags of information about the edited text. */ @@ -52,9 +73,11 @@ public class ExtractedText implements Parcelable { public void writeToParcel(Parcel dest, int flags) { TextUtils.writeToParcel(text, dest, flags); dest.writeInt(startOffset); + dest.writeInt(partialStartOffset); + dest.writeInt(partialEndOffset); dest.writeInt(selectionStart); dest.writeInt(selectionEnd); - dest.writeInt(flags); + dest.writeInt(this.flags); } /** @@ -65,6 +88,8 @@ public class ExtractedText implements Parcelable { ExtractedText res = new ExtractedText(); res.text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); res.startOffset = source.readInt(); + res.partialStartOffset = source.readInt(); + res.partialEndOffset = source.readInt(); res.selectionStart = source.readInt(); res.selectionEnd = source.readInt(); res.flags = source.readInt(); diff --git a/core/java/android/view/inputmethod/ExtractedTextRequest.java b/core/java/android/view/inputmethod/ExtractedTextRequest.java index d9623290ea7ad5cb5e45a5fa9227b04fe37240ac..e84b094557854d7aeed0748fae62068e547caabe 100644 --- a/core/java/android/view/inputmethod/ExtractedTextRequest.java +++ b/core/java/android/view/inputmethod/ExtractedTextRequest.java @@ -15,6 +15,13 @@ public class ExtractedTextRequest implements Parcelable { */ public int token; + /** + * Additional request flags, having the same possible values as the + * flags parameter of {@link InputConnection#getTextBeforeCursor + * InputConnection.getTextBeforeCursor()}. + */ + public int flags; + /** * Hint for the maximum number of lines to return. */ @@ -33,6 +40,7 @@ public class ExtractedTextRequest implements Parcelable { */ public void writeToParcel(Parcel dest, int flags) { dest.writeInt(token); + dest.writeInt(this.flags); dest.writeInt(hintMaxLines); dest.writeInt(hintMaxChars); } @@ -45,6 +53,7 @@ public class ExtractedTextRequest implements Parcelable { public ExtractedTextRequest createFromParcel(Parcel source) { ExtractedTextRequest res = new ExtractedTextRequest(); res.token = source.readInt(); + res.flags = source.readInt(); res.hintMaxLines = source.readInt(); res.hintMaxChars = source.readInt(); return res; diff --git a/core/java/android/view/inputmethod/InputConnection.java b/core/java/android/view/inputmethod/InputConnection.java index bd7b0507d85b042fe53a06758fa51153b95f6c4d..8b6831e655395fa4e6f563fc647e79786cd7eb26 100644 --- a/core/java/android/view/inputmethod/InputConnection.java +++ b/core/java/android/view/inputmethod/InputConnection.java @@ -17,7 +17,6 @@ package android.view.inputmethod; import android.os.Bundle; -import android.text.Spanned; import android.view.KeyCharacterMap; import android.view.KeyEvent; @@ -31,6 +30,21 @@ import android.view.KeyEvent; * subclassing {@link BaseInputConnection}. */ public interface InputConnection { + /** + * Flag for use with {@link #getTextAfterCursor} and + * {@link #getTextBeforeCursor} to have style information returned along + * with the text. If not set, you will receive only the raw text. If + * set, you may receive a complex CharSequence of both text and style + * spans. + */ + static final int GET_TEXT_WITH_STYLES = 0x0001; + + /** + * Flag for use with {@link #getExtractedText} to indicate you would + * like to receive updates when the extracted text changes. + */ + public static final int GET_EXTRACTED_TEXT_MONITOR = 0x0001; + /** * Get n characters of text before the current cursor position. * @@ -40,11 +54,13 @@ public interface InputConnection { * In either case, a null is returned. * * @param n The expected length of the text. + * @param flags Supplies additional options controlling how the text is + * returned. May be either 0 or {@link #GET_TEXT_WITH_STYLES}. * * @return Returns the text before the cursor position; the length of the * returned text might be less than n. */ - public CharSequence getTextBeforeCursor(int n); + public CharSequence getTextBeforeCursor(int n, int flags); /** * Get n characters of text after the current cursor position. @@ -55,11 +71,13 @@ public interface InputConnection { * In either case, a null is returned. * * @param n The expected length of the text. + * @param flags Supplies additional options controlling how the text is + * returned. May be either 0 or {@link #GET_TEXT_WITH_STYLES}. * * @return Returns the text after the cursor position; the length of the * returned text might be less than n. */ - public CharSequence getTextAfterCursor(int n); + public CharSequence getTextAfterCursor(int n, int flags); /** * Retrieve the current capitalization mode in effect at the current @@ -82,8 +100,6 @@ public interface InputConnection { */ public int getCursorCapsMode(int reqModes); - public static final int EXTRACTED_TEXT_MONITOR = 0x0001; - /** * Retrieve the current text in the input connection's editor, and monitor * for any changes to it. This function returns with the current text, @@ -97,7 +113,7 @@ public interface InputConnection { * * @param request Description of how the text should be returned. * @param flags Additional options to control the client, either 0 or - * {@link #EXTRACTED_TEXT_MONITOR}. + * {@link #GET_EXTRACTED_TEXT_MONITOR}. * * @return Returns an ExtractedText object describing the state of the * text view and containing the extracted text itself. @@ -118,7 +134,7 @@ public interface InputConnection { * @return Returns true on success, false if the input connection is no longer * valid. */ - boolean deleteSurroundingText(int leftLength, int rightLength); + public boolean deleteSurroundingText(int leftLength, int rightLength); /** * Set composing text around the current cursor position with the given text, @@ -131,8 +147,14 @@ public interface InputConnection { * object to the text. {#link android.text.SpannableString} and * {#link android.text.SpannableStringBuilder} are two * implementations of the interface {#link android.text.Spanned}. - * @param newCursorPosition The new cursor position within the - * text. + * @param newCursorPosition The new cursor position around the text. If + * > 0, this is relative to the end of the text - 1; if <= 0, this + * is relative to the start of the text. So a value of 1 will + * always advance you to the position after the full text being + * inserted. Note that this means you can't position the cursor + * within the text, because the editor can make modifications to + * the text you are providing so it is not possible to correctly + * specify locations there. * * @return Returns true on success, false if the input connection is no longer * valid. @@ -141,7 +163,7 @@ public interface InputConnection { /** * Have the text editor finish whatever composing text is currently - * active. This simple leaves the text as-is, removing any special + * active. This simply leaves the text as-is, removing any special * composing styling or other state that was around it. The cursor * position remains unchanged. */ @@ -153,8 +175,14 @@ public interface InputConnection { * automatically. * * @param text The committed text. - * @param newCursorPosition The new cursor position within the - * text. + * @param newCursorPosition The new cursor position around the text. If + * > 0, this is relative to the end of the text - 1; if <= 0, this + * is relative to the start of the text. So a value of 1 will + * always advance you to the position after the full text being + * inserted. Note that this means you can't position the cursor + * within the text, because the editor can make modifications to + * the text you are providing so it is not possible to correctly + * specify locations there. * * * @return Returns true on success, false if the input connection is no longer @@ -176,6 +204,36 @@ public interface InputConnection { */ public boolean commitCompletion(CompletionInfo text); + /** + * Set the selection of the text editor. To set the cursor position, + * start and end should have the same value. + * @return Returns true on success, false if the input connection is no longer + * valid. + */ + public boolean setSelection(int start, int end); + + /** + * Have the editor perform an action it has said it can do. + * + * @param editorAction This must be one of the action constants for + * {@link EditorInfo#imeOptions EditorInfo.editorType}, such as + * {@link EditorInfo#IME_ACTION_GO EditorInfo.EDITOR_ACTION_GO}. + * + * @return Returns true on success, false if the input connection is no longer + * valid. + */ + public boolean performEditorAction(int editorAction); + + /** + * Perform a context menu action on the field. The given id may be one of: + * {@link android.R.id#selectAll}, + * {@link android.R.id#startSelectingText}, {@link android.R.id#stopSelectingText}, + * {@link android.R.id#cut}, {@link android.R.id#copy}, + * {@link android.R.id#paste}, {@link android.R.id#copyUrl}, + * or {@link android.R.id#switchInputMethod} + */ + public boolean performContextMenuAction(int id); + /** * Tell the editor that you are starting a batch of editor operations. * The editor will try to avoid sending you updates about its state @@ -233,6 +291,13 @@ public interface InputConnection { */ public boolean clearMetaKeyStates(int states); + /** + * Called by the IME to tell the client when it switches between fullscreen + * and normal modes. This will normally be called for you by the standard + * implementation of {@link android.inputmethodservice.InputMethodService}. + */ + public boolean reportFullscreenMode(boolean enabled); + /** * API to send private commands from an input method to its connected * editor. This can be used to provide domain-specific features that are @@ -251,23 +316,4 @@ public interface InputConnection { * valid. */ public boolean performPrivateCommand(String action, Bundle data); - - /** - * Show an icon in the status bar. - * - * @param packageName The package holding the icon resource to be shown. - * @param resId The resource id of the icon to show. - * - * @return Returns true on success, false if the input connection is no longer - * valid. - */ - public boolean showStatusIcon(String packageName, int resId); - - /** - * Hide the icon shown in the status bar. - * - * @return Returns true on success, false if the input connection is no longer - * valid. - */ - public boolean hideStatusIcon(); } diff --git a/core/java/android/view/inputmethod/InputConnectionWrapper.java b/core/java/android/view/inputmethod/InputConnectionWrapper.java index f65b2a1081c79e784f8e7e30befe671e8f6b2ef6..e3d5e62151b10b4e34782ba82678198f64c17c3c 100644 --- a/core/java/android/view/inputmethod/InputConnectionWrapper.java +++ b/core/java/android/view/inputmethod/InputConnectionWrapper.java @@ -20,88 +20,86 @@ import android.os.Bundle; import android.view.KeyEvent; /** - * Wrapper around InputConnection interface, calling through to another - * implementation of it. + *

          Wrapper class for proxying calls to another InputConnection. Subclass + * and have fun! */ public class InputConnectionWrapper implements InputConnection { - InputConnection mBase; + private final InputConnection mTarget; - /** - * Create a new wrapper around an existing InputConnection implementation. - */ - public InputConnectionWrapper(InputConnection base) { - mBase = base; + public InputConnectionWrapper(InputConnection target) { + mTarget = target; } - /** - * Return the base InputConnection that this class is wrapping. - */ - InputConnection getBase() { - return mBase; + public CharSequence getTextBeforeCursor(int n, int flags) { + return mTarget.getTextBeforeCursor(n, flags); } - public CharSequence getTextBeforeCursor(int n) { - return mBase.getTextBeforeCursor(n); - } - - public CharSequence getTextAfterCursor(int n) { - return mBase.getTextAfterCursor(n); + public CharSequence getTextAfterCursor(int n, int flags) { + return mTarget.getTextAfterCursor(n, flags); } public int getCursorCapsMode(int reqModes) { - return mBase.getCursorCapsMode(reqModes); + return mTarget.getCursorCapsMode(reqModes); } public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { - return mBase.getExtractedText(request, flags); + return mTarget.getExtractedText(request, flags); } public boolean deleteSurroundingText(int leftLength, int rightLength) { - return mBase.deleteSurroundingText(leftLength, rightLength); + return mTarget.deleteSurroundingText(leftLength, rightLength); } public boolean setComposingText(CharSequence text, int newCursorPosition) { - return mBase.setComposingText(text, newCursorPosition); + return mTarget.setComposingText(text, newCursorPosition); } public boolean finishComposingText() { - return mBase.finishComposingText(); + return mTarget.finishComposingText(); } public boolean commitText(CharSequence text, int newCursorPosition) { - return mBase.commitText(text, newCursorPosition); + return mTarget.commitText(text, newCursorPosition); } public boolean commitCompletion(CompletionInfo text) { - return mBase.commitCompletion(text); + return mTarget.commitCompletion(text); + } + + public boolean setSelection(int start, int end) { + return mTarget.setSelection(start, end); + } + + public boolean performEditorAction(int editorAction) { + return mTarget.performEditorAction(editorAction); + } + + public boolean performContextMenuAction(int id) { + return mTarget.performContextMenuAction(id); } public boolean beginBatchEdit() { - return mBase.beginBatchEdit(); + return mTarget.beginBatchEdit(); } public boolean endBatchEdit() { - return mBase.endBatchEdit(); + return mTarget.endBatchEdit(); } public boolean sendKeyEvent(KeyEvent event) { - return mBase.sendKeyEvent(event); + return mTarget.sendKeyEvent(event); } public boolean clearMetaKeyStates(int states) { - return mBase.clearMetaKeyStates(states); - } - - public boolean performPrivateCommand(String action, Bundle data) { - return mBase.performPrivateCommand(action, data); + return mTarget.clearMetaKeyStates(states); } - public boolean showStatusIcon(String packageName, int resId) { - return mBase.showStatusIcon(packageName, resId); + public boolean reportFullscreenMode(boolean enabled) { + return mTarget.reportFullscreenMode(enabled); } - public boolean hideStatusIcon() { - return mBase.hideStatusIcon(); + public boolean performPrivateCommand(String action, Bundle data) { + return mTarget.performPrivateCommand(action, data); } } diff --git a/core/java/android/view/inputmethod/InputMethod.java b/core/java/android/view/inputmethod/InputMethod.java index c0e6590c71102f17456efea146fc64c50ddd0afe..a5e0e9491d1e250c0767a31d1d44102e910a712e 100644 --- a/core/java/android/view/inputmethod/InputMethod.java +++ b/core/java/android/view/inputmethod/InputMethod.java @@ -18,6 +18,7 @@ package android.view.inputmethod; import android.inputmethodservice.InputMethodService; import android.os.IBinder; +import android.os.ResultReceiver; /** * The InputMethod interface represents an input method which can generate key @@ -113,12 +114,15 @@ public interface InputMethod { * is ready for this input method to process received events and send result * text back to the application. * - * @param attribute The attribute of the text box (typically, a EditText) + * @param inputConnection Optional specific input connection for + * communicating with the text box; if null, you should use the generic + * bound input connection. + * @param info Information about the text box (typically, an EditText) * that requests input. * * @see EditorInfo */ - public void startInput(EditorInfo attribute); + public void startInput(InputConnection inputConnection, EditorInfo info); /** * This method is called when the state of this input method needs to be @@ -128,12 +132,15 @@ public interface InputMethod { * Typically, this method is called when the input focus is moved from one * text box to another. * + * @param inputConnection Optional specific input connection for + * communicating with the text box; if null, you should use the generic + * bound input connection. * @param attribute The attribute of the text box (typically, a EditText) * that requests input. * * @see EditorInfo */ - public void restartInput(EditorInfo attribute); + public void restartInput(InputConnection inputConnection, EditorInfo attribute); /** * Create a new {@link InputMethodSession} that can be handed to client @@ -165,23 +172,46 @@ public interface InputMethod { public void revokeSession(InputMethodSession session); /** - * Flag for {@link #showSoftInput(int)}: this show has been explicitly + * Flag for {@link #showSoftInput}: this show has been explicitly * requested by the user. If not set, the system has decided it may be * a good idea to show the input method based on a navigation operation * in the UI. */ public static final int SHOW_EXPLICIT = 0x00001; + /** + * Flag for {@link #showSoftInput}: this show has been forced to + * happen by the user. If set, the input method should remain visible + * until deliberated dismissed by the user in its UI. + */ + public static final int SHOW_FORCED = 0x00002; + /** * Request that any soft input part of the input method be shown to the user. * - * @param flags Provide additional information about the show request. + * @param flags Provides additional information about the show request. * Currently may be 0 or have the bit {@link #SHOW_EXPLICIT} set. + * @param resultReceiver The client requesting the show may wish to + * be told the impact of their request, which should be supplied here. + * The result code should be + * {@link InputMethodManager#RESULT_UNCHANGED_SHOWN InputMethodManager.RESULT_UNCHANGED_SHOWN}, + * {@link InputMethodManager#RESULT_UNCHANGED_HIDDEN InputMethodManager.RESULT_UNCHANGED_HIDDEN}, + * {@link InputMethodManager#RESULT_SHOWN InputMethodManager.RESULT_SHOWN}, or + * {@link InputMethodManager#RESULT_HIDDEN InputMethodManager.RESULT_HIDDEN}. */ - public void showSoftInput(int flags); + public void showSoftInput(int flags, ResultReceiver resultReceiver); /** * Request that any soft input part of the input method be hidden from the user. + * @param flags Provides additional information about the show request. + * Currently always 0. + * @param resultReceiver The client requesting the show may wish to + * be told the impact of their request, which should be supplied here. + * The result code should be + * {@link InputMethodManager#RESULT_UNCHANGED_SHOWN InputMethodManager.RESULT_UNCHANGED_SHOWN}, + * {@link InputMethodManager#RESULT_UNCHANGED_HIDDEN InputMethodManager.RESULT_UNCHANGED_HIDDEN}, + * {@link InputMethodManager#RESULT_SHOWN InputMethodManager.RESULT_SHOWN}, or + * {@link InputMethodManager#RESULT_HIDDEN InputMethodManager.RESULT_HIDDEN}. */ - public void hideSoftInput(); + public void hideSoftInput(int flags, ResultReceiver resultReceiver); } diff --git a/core/java/android/view/inputmethod/InputMethodInfo.java b/core/java/android/view/inputmethod/InputMethodInfo.java index e8f4b54cbd34b6b89aa66a4fdf21365c45a244b9..b4c5b72f33eb563d0956913c3f700fc5452760b1 100644 --- a/core/java/android/view/inputmethod/InputMethodInfo.java +++ b/core/java/android/view/inputmethod/InputMethodInfo.java @@ -173,6 +173,14 @@ public final class InputMethodInfo implements Parcelable { return mService.serviceInfo.name; } + /** + * Return the raw information about the Service implementing this + * input method. Do not modify the returned object. + */ + public ServiceInfo getServiceInfo() { + return mService.serviceInfo; + } + /** * Return the component of the service that implements this input * method. @@ -225,15 +233,6 @@ public final class InputMethodInfo implements Parcelable { return mIsDefaultResId; } - /** - * Returns true if this input method is one of the components that is - * built in to the system. - */ - public boolean isBuiltin() { - return mService.serviceInfo.packageName.equals( - InputMethodManager.BUILDIN_INPUTMETHOD_PACKAGE); - } - public void dump(Printer pw, String prefix) { pw.println(prefix + "mId=" + mId + " mSettingsActivityName=" + mSettingsActivityName); diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java index a9a95944dc4a96297d82698b5c0a1f4a3f8cd8d9..4de9eef04d40032bd38f12c32b580098c7ad06c3 100644 --- a/core/java/android/view/inputmethod/InputMethodManager.java +++ b/core/java/android/view/inputmethod/InputMethodManager.java @@ -24,13 +24,17 @@ import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.RemoteException; +import android.os.ResultReceiver; import android.os.ServiceManager; import android.util.Log; +import android.util.PrintWriterPrinter; +import android.util.Printer; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewRoot; +import com.android.internal.os.HandlerCaller; import com.android.internal.view.IInputConnectionWrapper; import com.android.internal.view.IInputContext; import com.android.internal.view.IInputMethodCallback; @@ -39,7 +43,11 @@ import com.android.internal.view.IInputMethodManager; import com.android.internal.view.IInputMethodSession; import com.android.internal.view.InputBindResult; +import java.io.FileDescriptor; +import java.io.PrintWriter; import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /** * Central system API to the overall input method framework (IMF) architecture, @@ -183,12 +191,6 @@ public final class InputMethodManager { static final boolean DEBUG = false; static final String TAG = "InputMethodManager"; - /** - * The package name of the build-in input method. - * {@hide} - */ - public static final String BUILDIN_INPUTMETHOD_PACKAGE = "android.text.inputmethod"; - static final Object mInstanceSync = new Object(); static InputMethodManager mInstance; @@ -199,8 +201,7 @@ public final class InputMethodManager { // global lock. final H mH; - // The currently active input connection. - final MutableInputConnectionWrapper mInputConnectionWrapper; + // Our generic input connection if the current target does not have its own. final IInputContext mIInputContext; /** @@ -209,22 +210,38 @@ public final class InputMethodManager { boolean mActive = false; /** - * The current base input connection, used when mActive is true. + * Set whenever this client becomes inactive, to know we need to reset + * state with the IME then next time we receive focus. */ - InputConnection mCurrentInputConnection; - + boolean mHasBeenInactive = true; + + /** + * As reported by IME through InputConnection. + */ + boolean mFullscreenMode; + // ----------------------------------------------------------- + /** + * This is the root view of the overall window that currently has input + * method focus. + */ + View mCurRootView; /** * This is the view that should currently be served by an input method, * regardless of the state of setting that up. */ View mServedView; /** - * For evaluating the state after a focus change, this is the view that - * had focus. + * This is then next view that will be served by the input method, when + * we get around to updating things. */ - View mLastServedView; + View mNextServedView; + /** + * True if we should restart input in the next served view, even if the + * view hasn't actually changed from the current serve view. + */ + boolean mNextServedNeedsStart; /** * This is set when we are in the process of connecting, to determine * when we have actually finished. @@ -270,7 +287,10 @@ public final class InputMethodManager { // ----------------------------------------------------------- - static final int MSG_CHECK_FOCUS = 1; + static final int MSG_DUMP = 1; + static final int MSG_BIND = 2; + static final int MSG_UNBIND = 3; + static final int MSG_SET_ACTIVE = 4; class H extends Handler { H(Looper looper) { @@ -280,185 +300,140 @@ public final class InputMethodManager { @Override public void handleMessage(Message msg) { switch (msg.what) { - case MSG_CHECK_FOCUS: - checkFocus(); + case MSG_DUMP: { + HandlerCaller.SomeArgs args = (HandlerCaller.SomeArgs)msg.obj; + try { + doDump((FileDescriptor)args.arg1, + (PrintWriter)args.arg2, (String[])args.arg3); + } catch (RuntimeException e) { + ((PrintWriter)args.arg2).println("Exception: " + e); + } + synchronized (args.arg4) { + ((CountDownLatch)args.arg4).countDown(); + } return; + } + case MSG_BIND: { + final InputBindResult res = (InputBindResult)msg.obj; + synchronized (mH) { + if (mBindSequence < 0 || mBindSequence != res.sequence) { + Log.w(TAG, "Ignoring onBind: cur seq=" + mBindSequence + + ", given seq=" + res.sequence); + return; + } + + mCurMethod = res.method; + mCurId = res.id; + mBindSequence = res.sequence; + } + startInputInner(); + return; + } + case MSG_UNBIND: { + final int sequence = msg.arg1; + synchronized (mH) { + if (mBindSequence == sequence) { + if (false) { + // XXX the server has already unbound! + if (mCurMethod != null && mCurrentTextBoxAttribute != null) { + try { + mCurMethod.finishInput(); + } catch (RemoteException e) { + Log.w(TAG, "IME died: " + mCurId, e); + } + } + } + clearBindingLocked(); + + // If we were actively using the last input method, then + // we would like to re-connect to the next input method. + if (mServedView != null && mServedView.isFocused()) { + mServedConnecting = true; + } + } + startInputInner(); + } + return; + } + case MSG_SET_ACTIVE: { + final boolean active = msg.arg1 != 0; + synchronized (mH) { + mActive = active; + mFullscreenMode = false; + if (!active) { + // Some other client has starting using the IME, so note + // that this happened and make sure our own editor's + // state is reset. + mHasBeenInactive = true; + try { + // Note that finishComposingText() is allowed to run + // even when we are not active. + mIInputContext.finishComposingText(); + } catch (RemoteException e) { + } + } + } + return; + } } } } - static class NoOpInputConnection implements InputConnection { - - public boolean clearMetaKeyStates(int states) { - return false; - } - - public boolean beginBatchEdit() { - return false; - } - - public boolean endBatchEdit() { - return false; - } - - public boolean commitCompletion(CompletionInfo text) { - return false; + class ControlledInputConnectionWrapper extends IInputConnectionWrapper { + public ControlledInputConnectionWrapper(Looper mainLooper, InputConnection conn) { + super(mainLooper, conn); } - public boolean commitText(CharSequence text, int newCursorPosition) { - return false; - } - - public boolean deleteSurroundingText(int leftLength, int rightLength) { - return false; - } - - public int getCursorCapsMode(int reqModes) { - return 0; - } - - public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { - return null; - } - - public CharSequence getTextAfterCursor(int n) { - return null; - } - - public CharSequence getTextBeforeCursor(int n) { - return null; - } - - public boolean hideStatusIcon() { - return false; - } - - public boolean performPrivateCommand(String action, Bundle data) { - return false; - } - - public boolean sendKeyEvent(KeyEvent event) { - return false; - } - - public boolean setComposingText(CharSequence text, int newCursorPosition) { - return false; - } - - public boolean finishComposingText() { - return false; - } - - public boolean showStatusIcon(String packageName, int resId) { - return false; + public boolean isActive() { + return mActive; } } - final NoOpInputConnection mNoOpInputConnection = new NoOpInputConnection(); - final IInputMethodClient.Stub mClient = new IInputMethodClient.Stub() { - public void setUsingInputMethod(boolean state) { + @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { + // No need to check for dump permission, since we only give this + // interface to the system. + CountDownLatch latch = new CountDownLatch(1); + HandlerCaller.SomeArgs sargs = new HandlerCaller.SomeArgs(); + sargs.arg1 = fd; + sargs.arg2 = fout; + sargs.arg3 = args; + sargs.arg4 = latch; + mH.sendMessage(mH.obtainMessage(MSG_DUMP, sargs)); + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + fout.println("Timeout waiting for dump"); + } + } catch (InterruptedException e) { + fout.println("Interrupted waiting for dump"); + } + } + + public void setUsingInputMethod(boolean state) { } public void onBindMethod(InputBindResult res) { - synchronized (mH) { - if (mBindSequence < 0 || mBindSequence != res.sequence) { - Log.w(TAG, "Ignoring onBind: cur seq=" + mBindSequence - + ", given seq=" + res.sequence); - return; - } - - mCurMethod = res.method; - mCurId = res.id; - mBindSequence = res.sequence; - } - startInputInner(); + mH.sendMessage(mH.obtainMessage(MSG_BIND, res)); } public void onUnbindMethod(int sequence) { - synchronized (mH) { - if (mBindSequence == sequence) { - if (false) { - // XXX the server has already unbound! - if (mCurMethod != null && mCurrentTextBoxAttribute != null) { - try { - mCurMethod.finishInput(); - } catch (RemoteException e) { - Log.w(TAG, "IME died: " + mCurId, e); - } - } - } - clearBindingLocked(); - - // If we were actively using the last input method, then - // we would like to re-connect to the next input method. - if (mServedView != null && mServedView.isFocused()) { - mServedConnecting = true; - } - } - startInputInner(); - } + mH.sendMessage(mH.obtainMessage(MSG_UNBIND, sequence, 0)); } public void setActive(boolean active) { - mActive = active; - mInputConnectionWrapper.setBaseInputConnection(active - ? mCurrentInputConnection : mNoOpInputConnection); + mH.sendMessage(mH.obtainMessage(MSG_SET_ACTIVE, active ? 1 : 0, 0)); } }; - final InputConnection mDummyInputConnection = new BaseInputConnection(this) { - public boolean beginBatchEdit() { - return false; - } - public boolean endBatchEdit() { - return false; - } - public boolean commitText(CharSequence text, int newCursorPosition) { - return false; - } - public boolean commitCompletion(CompletionInfo text) { - return false; - } - public boolean deleteSurroundingText(int leftLength, int rightLength) { - return false; - } - public ExtractedText getExtractedText(ExtractedTextRequest request, - int flags) { - return null; - } - public CharSequence getTextAfterCursor(int n) { - return null; - } - public CharSequence getTextBeforeCursor(int n) { - return null; - } - public int getCursorCapsMode(int reqModes) { - return 0; - } - public boolean clearMetaKeyStates(int states) { - return false; - } - public boolean performPrivateCommand(String action, Bundle data) { - return false; - } - public boolean setComposingText(CharSequence text, int newCursorPosition) { - return false; - } - public boolean finishComposingText() { - return false; - } - }; + final InputConnection mDummyInputConnection = new BaseInputConnection(this, true); InputMethodManager(IInputMethodManager service, Looper looper) { mService = service; mMainLooper = looper; mH = new H(looper); - mInputConnectionWrapper = new MutableInputConnectionWrapper(mNoOpInputConnection); - mIInputContext = new IInputConnectionWrapper(looper, - mInputConnectionWrapper); - setCurrentInputConnection(mDummyInputConnection); + mIInputContext = new ControlledInputConnectionWrapper(looper, + mDummyInputConnection); if (mInstance == null) { mInstance = this; @@ -517,21 +492,47 @@ public final class InputMethodManager { } } - public void updateStatusIcon(int iconId, String iconPackage) { + public void showStatusIcon(IBinder imeToken, String packageName, int iconId) { + try { + mService.updateStatusIcon(imeToken, packageName, iconId); + } catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + public void hideStatusIcon(IBinder imeToken) { try { - mService.updateStatusIcon(iconId, iconPackage); + mService.updateStatusIcon(imeToken, null, 0); } catch (RemoteException e) { throw new RuntimeException(e); } } + /** @hide */ + public void setFullscreenMode(boolean fullScreen) { + mFullscreenMode = fullScreen; + } + + /** + * Allows you to discover whether the attached input method is running + * in fullscreen mode. Return true if it is fullscreen, entirely covering + * your UI, else returns false. + */ + public boolean isFullscreenMode() { + return mFullscreenMode; + } + /** * Return true if the given view is the currently active view for the * input method. */ public boolean isActive(View view) { + checkFocus(); synchronized (mH) { - return mServedView == view && mCurrentTextBoxAttribute != null; + return (mServedView == view + || (mServedView != null + && mServedView.checkInputConnectionProxy(view))) + && mCurrentTextBoxAttribute != null; } } @@ -539,6 +540,7 @@ public final class InputMethodManager { * Return true if any view is currently active in the input method. */ public boolean isActive() { + checkFocus(); synchronized (mH) { return mServedView != null && mCurrentTextBoxAttribute != null; } @@ -549,6 +551,7 @@ public final class InputMethodManager { * If false, it has no input connection, so can only handle raw key events. */ public boolean isAcceptingText() { + checkFocus(); return mServedInputConnection != null; } @@ -562,15 +565,6 @@ public final class InputMethodManager { mCurMethod = null; } - /** - * Record the desired input connection, but only set it if mActive is true. - */ - void setCurrentInputConnection(InputConnection connection) { - mCurrentInputConnection = connection; - mInputConnectionWrapper.setBaseInputConnection(mActive - ? connection : mNoOpInputConnection); - } - /** * Reset all of the state associated with a served view being connected * to an input method @@ -578,16 +572,15 @@ public final class InputMethodManager { void clearConnectionLocked() { mCurrentTextBoxAttribute = null; mServedInputConnection = null; - setCurrentInputConnection(mDummyInputConnection); } /** * Disconnect any existing input connection, clearing the served view. */ void finishInputLocked() { + mNextServedView = null; if (mServedView != null) { if (DEBUG) Log.v(TAG, "FINISH INPUT: " + mServedView); - updateStatusIcon(0, null); if (mCurrentTextBoxAttribute != null) { try { @@ -628,8 +621,10 @@ public final class InputMethodManager { } public void displayCompletions(View view, CompletionInfo[] completions) { + checkFocus(); synchronized (mH) { - if (mServedView != view) { + if (mServedView != view && (mServedView == null + || !mServedView.checkInputConnectionProxy(view))) { return; } @@ -644,8 +639,10 @@ public final class InputMethodManager { } public void updateExtractedText(View view, int token, ExtractedText text) { + checkFocus(); synchronized (mH) { - if (mServedView != view) { + if (mServedView != view && (mServedView == null + || !mServedView.checkInputConnectionProxy(view))) { return; } @@ -659,12 +656,65 @@ public final class InputMethodManager { } /** - * Flag for {@link #showSoftInput} to indicate that the this is an implicit + * Flag for {@link #showSoftInput} to indicate that this is an implicit * request to show the input window, not as the result of a direct request * by the user. The window may not be shown in this case. */ public static final int SHOW_IMPLICIT = 0x0001; + /** + * Flag for {@link #showSoftInput} to indicate that the user has forced + * the input method open (such as by long-pressing menu) so it should + * not be closed until they explicitly do so. + */ + public static final int SHOW_FORCED = 0x0002; + + /** + * Synonym for {@link #showSoftInput(View, int, ResultReceiver)} without + * a result receiver: explicitly request that the current input method's + * soft input area be shown to the user, if needed. + * + * @param view The currently focused view, which would like to receive + * soft keyboard input. + * @param flags Provides additional operating flags. Currently may be + * 0 or have the {@link #SHOW_IMPLICIT} bit set. + */ + public boolean showSoftInput(View view, int flags) { + return showSoftInput(view, flags, null); + } + + /** + * Flag for the {@link ResultReceiver} result code from + * {@link #showSoftInput(View, int, ResultReceiver)} and + * {@link #hideSoftInputFromWindow(IBinder, int, ResultReceiver)}: the + * state of the soft input window was unchanged and remains shown. + */ + public static final int RESULT_UNCHANGED_SHOWN = 0; + + /** + * Flag for the {@link ResultReceiver} result code from + * {@link #showSoftInput(View, int, ResultReceiver)} and + * {@link #hideSoftInputFromWindow(IBinder, int, ResultReceiver)}: the + * state of the soft input window was unchanged and remains hidden. + */ + public static final int RESULT_UNCHANGED_HIDDEN = 1; + + /** + * Flag for the {@link ResultReceiver} result code from + * {@link #showSoftInput(View, int, ResultReceiver)} and + * {@link #hideSoftInputFromWindow(IBinder, int, ResultReceiver)}: the + * state of the soft input window changed from hidden to shown. + */ + public static final int RESULT_SHOWN = 2; + + /** + * Flag for the {@link ResultReceiver} result code from + * {@link #showSoftInput(View, int, ResultReceiver)} and + * {@link #hideSoftInputFromWindow(IBinder, int, ResultReceiver)}: the + * state of the soft input window changed from shown to hidden. + */ + public static final int RESULT_HIDDEN = 3; + /** * Explicitly request that the current input method's soft input area be * shown to the user, if needed. Call this if the user interacts with @@ -675,17 +725,35 @@ public final class InputMethodManager { * soft keyboard input. * @param flags Provides additional operating flags. Currently may be * 0 or have the {@link #SHOW_IMPLICIT} bit set. + * @param resultReceiver If non-null, this will be called by the IME when + * it has processed your request to tell you what it has done. The result + * code you receive may be either {@link #RESULT_UNCHANGED_SHOWN}, + * {@link #RESULT_UNCHANGED_HIDDEN}, {@link #RESULT_SHOWN}, or + * {@link #RESULT_HIDDEN}. */ - public void showSoftInput(View view, int flags) { + public boolean showSoftInput(View view, int flags, + ResultReceiver resultReceiver) { + checkFocus(); synchronized (mH) { - if (mServedView != view) { - return; + if (mServedView != view && (mServedView == null + || !mServedView.checkInputConnectionProxy(view))) { + return false; } try { - mService.showSoftInput(mClient, flags); + return mService.showSoftInput(mClient, flags, resultReceiver); } catch (RemoteException e) { } + + return false; + } + } + + /** @hide */ + public void showSoftInputUnchecked(int flags, ResultReceiver resultReceiver) { + try { + mService.showSoftInput(mClient, flags, resultReceiver); + } catch (RemoteException e) { } } @@ -696,6 +764,27 @@ public final class InputMethodManager { */ public static final int HIDE_IMPLICIT_ONLY = 0x0001; + /** + * Flag for {@link #hideSoftInputFromWindow} to indicate that the soft + * input window should normally be hidden, unless it was originally + * shown with {@link #SHOW_FORCED}. + */ + public static final int HIDE_NOT_ALWAYS = 0x0002; + + /** + * Synonym for {@link #hideSoftInputFromWindow(IBinder, int, ResultReceiver) + * without a result: request to hide the soft input window from the + * context of the window that is currently accepting input. + * + * @param windowToken The token of the window that is making the request, + * as returned by {@link View#getWindowToken() View.getWindowToken()}. + * @param flags Provides additional operating flags. Currently may be + * 0 or have the {@link #HIDE_IMPLICIT_ONLY} bit set. + */ + public boolean hideSoftInputFromWindow(IBinder windowToken, int flags) { + return hideSoftInputFromWindow(windowToken, flags, null); + } + /** * Request to hide the soft input window from the context of the window * that is currently accepting input. This should be called as a result @@ -706,20 +795,77 @@ public final class InputMethodManager { * as returned by {@link View#getWindowToken() View.getWindowToken()}. * @param flags Provides additional operating flags. Currently may be * 0 or have the {@link #HIDE_IMPLICIT_ONLY} bit set. + * @param resultReceiver If non-null, this will be called by the IME when + * it has processed your request to tell you what it has done. The result + * code you receive may be either {@link #RESULT_UNCHANGED_SHOWN}, + * {@link #RESULT_UNCHANGED_HIDDEN}, {@link #RESULT_SHOWN}, or + * {@link #RESULT_HIDDEN}. */ - public void hideSoftInputFromWindow(IBinder windowToken, int flags) { + public boolean hideSoftInputFromWindow(IBinder windowToken, int flags, + ResultReceiver resultReceiver) { + checkFocus(); synchronized (mH) { if (mServedView == null || mServedView.getWindowToken() != windowToken) { - return; + return false; } try { - mService.hideSoftInput(mClient, flags); + return mService.hideSoftInput(mClient, flags, resultReceiver); } catch (RemoteException e) { } + return false; } } + + /** + * This method toggles the input method window display. + * If the input window is already displayed, it gets hidden. + * If not the input window will be displayed. + * @param windowToken The token of the window that is making the request, + * as returned by {@link View#getWindowToken() View.getWindowToken()}. + * @param showFlags Provides additional operating flags. May be + * 0 or have the {@link #SHOW_IMPLICIT}, + * {@link #SHOW_FORCED} bit set. + * @param hideFlags Provides additional operating flags. May be + * 0 or have the {@link #HIDE_IMPLICIT_ONLY}, + * {@link #HIDE_NOT_ALWAYS} bit set. + **/ + public void toggleSoftInputFromWindow(IBinder windowToken, int showFlags, int hideFlags) { + synchronized (mH) { + if (mServedView == null || mServedView.getWindowToken() != windowToken) { + return; + } + if (mCurMethod != null) { + try { + mCurMethod.toggleSoftInput(showFlags, hideFlags); + } catch (RemoteException e) { + } + } + } + } + + /* + * This method toggles the input method window display. + * If the input window is already displayed, it gets hidden. + * If not the input window will be displayed. + * @param showFlags Provides additional operating flags. May be + * 0 or have the {@link #SHOW_IMPLICIT}, + * {@link #SHOW_FORCED} bit set. + * @param hideFlags Provides additional operating flags. May be + * 0 or have the {@link #HIDE_IMPLICIT_ONLY}, + * {@link #HIDE_NOT_ALWAYS} bit set. + * @hide + */ + public void toggleSoftInput(int showFlags, int hideFlags) { + if (mCurMethod != null) { + try { + mCurMethod.toggleSoftInput(showFlags, hideFlags); + } catch (RemoteException e) { + } + } + } + /** * If the input method is currently connected to the given view, * restart it with its new contents. You should call this when the text @@ -729,8 +875,10 @@ public final class InputMethodManager { * @param view The view whose text has changed. */ public void restartInput(View view) { + checkFocus(); synchronized (mH) { - if (mServedView != view) { + if (mServedView != view && (mServedView == null + || !mServedView.checkInputConnectionProxy(view))) { return; } @@ -773,12 +921,15 @@ public final class InputMethodManager { startInputInner(); } }); + return; } // Okay we are now ready to call into the served view and have it // do its stuff. // Life is good: let's hook everything up! EditorInfo tba = new EditorInfo(); + tba.packageName = view.getContext().getPackageName(); + tba.fieldId = view.getId(); InputConnection ic = view.onCreateInputConnection(tba); if (DEBUG) Log.v(TAG, "Starting input: tba=" + tba + " ic=" + ic); @@ -801,22 +952,23 @@ public final class InputMethodManager { mCurrentTextBoxAttribute = tba; mServedConnecting = false; mServedInputConnection = ic; + IInputContext servedContext; if (ic != null) { mCursorSelStart = tba.initialSelStart; mCursorSelEnd = tba.initialSelEnd; mCursorCandStart = -1; mCursorCandEnd = -1; mCursorRect.setEmpty(); - setCurrentInputConnection(ic); + servedContext = new ControlledInputConnectionWrapper(vh.getLooper(), ic); } else { - setCurrentInputConnection(mDummyInputConnection); + servedContext = null; } try { if (DEBUG) Log.v(TAG, "START INPUT: " + view + " ic=" + ic + " tba=" + tba + " initial=" + initial); - InputBindResult res = mService.startInput(mClient, tba, initial, - mCurMethod == null); + InputBindResult res = mService.startInput(mClient, + servedContext, tba, initial, mCurMethod == null); if (DEBUG) Log.v(TAG, "Starting input: Bind result=" + res); if (res != null) { if (res.id != null) { @@ -846,6 +998,7 @@ public final class InputMethodManager { * @hide */ public void windowDismissed(IBinder appWindowToken) { + checkFocus(); synchronized (mH) { if (mServedView != null && mServedView.getWindowToken() == appWindowToken) { @@ -860,17 +1013,22 @@ public final class InputMethodManager { */ public void focusIn(View view) { synchronized (mH) { - if (DEBUG) Log.v(TAG, "focusIn: " + view); - // Okay we have a new view that is being served. - if (mServedView != view) { - mCurrentTextBoxAttribute = null; - } - mServedView = view; - mCompletions = null; - mServedConnecting = true; + focusInLocked(view); } + } + + void focusInLocked(View view) { + if (DEBUG) Log.v(TAG, "focusIn: " + view); - startInputInner(); + if (mCurRootView != view.getRootView()) { + // This is a request from a window that isn't in the window with + // IME focus, so ignore it. + if (DEBUG) Log.v(TAG, "Not IME target window, ignoring"); + return; + } + + mNextServedView = view; + scheduleCheckFocusLocked(view); } /** @@ -878,77 +1036,132 @@ public final class InputMethodManager { * @hide */ public void focusOut(View view) { - InputConnection ic = null; synchronized (mH) { if (DEBUG) Log.v(TAG, "focusOut: " + view + " mServedView=" + mServedView + " winFocus=" + view.hasWindowFocus()); - if (mServedView == view) { - ic = mServedInputConnection; - if (view.hasWindowFocus()) { - mLastServedView = view; - mH.removeMessages(MSG_CHECK_FOCUS); - mH.sendEmptyMessage(MSG_CHECK_FOCUS); + if (mServedView != view) { + // The following code would auto-hide the IME if we end up + // with no more views with focus. This can happen, however, + // whenever we go into touch mode, so it ends up hiding + // at times when we don't really want it to. For now it + // seems better to just turn it all off. + if (false && view.hasWindowFocus()) { + mNextServedView = null; + scheduleCheckFocusLocked(view); } } } - - if (ic != null) { - ic.finishComposingText(); - } } - void checkFocus() { + void scheduleCheckFocusLocked(View view) { + Handler vh = view.getHandler(); + if (vh != null && !vh.hasMessages(ViewRoot.CHECK_FOCUS)) { + // This will result in a call to checkFocus() below. + vh.sendMessage(vh.obtainMessage(ViewRoot.CHECK_FOCUS)); + } + } + + /** + * @hide + */ + public void checkFocus() { + // This is called a lot, so short-circuit before locking. + if (mServedView == mNextServedView && !mNextServedNeedsStart) { + return; + } + + InputConnection ic = null; synchronized (mH) { + if (mServedView == mNextServedView && !mNextServedNeedsStart) { + return; + } if (DEBUG) Log.v(TAG, "checkFocus: view=" + mServedView - + " last=" + mLastServedView); - if (mServedView == mLastServedView) { + + " next=" + mNextServedView + + " restart=" + mNextServedNeedsStart); + + mNextServedNeedsStart = false; + if (mNextServedView == null) { finishInputLocked(); // In this case, we used to have a focused view on the window, // but no longer do. We should make sure the input method is // no longer shown, since it serves no purpose. closeCurrentInput(); + return; } - mLastServedView = null; + + ic = mServedInputConnection; + + mServedView = mNextServedView; + mCurrentTextBoxAttribute = null; + mCompletions = null; + mServedConnecting = true; + } + + if (ic != null) { + ic.finishComposingText(); } + + startInputInner(); } void closeCurrentInput() { try { - mService.hideSoftInput(mClient, 0); + mService.hideSoftInput(mClient, HIDE_NOT_ALWAYS, null); } catch (RemoteException e) { } } /** - * Called by ViewRoot the first time it gets window focus. + * Called by ViewRoot when its window gets input focus. * @hide */ - public void onWindowFocus(View focusedView, int softInputMode, + public void onWindowFocus(View rootView, View focusedView, int softInputMode, boolean first, int windowFlags) { synchronized (mH) { if (DEBUG) Log.v(TAG, "onWindowFocus: " + focusedView + " softInputMode=" + softInputMode + " first=" + first + " flags=#" + Integer.toHexString(windowFlags)); + if (mHasBeenInactive) { + if (DEBUG) Log.v(TAG, "Has been inactive! Starting fresh"); + mHasBeenInactive = false; + mNextServedNeedsStart = true; + } + focusInLocked(focusedView != null ? focusedView : rootView); + } + + checkFocus(); + + synchronized (mH) { try { final boolean isTextEditor = focusedView != null && - focusedView.onCheckIsTextEditor(); - mService.windowGainedFocus(mClient, focusedView != null, - isTextEditor, softInputMode, first, windowFlags); + focusedView.onCheckIsTextEditor(); + mService.windowGainedFocus(mClient, rootView.getWindowToken(), + focusedView != null, isTextEditor, softInputMode, first, + windowFlags); } catch (RemoteException e) { } } } + /** @hide */ + public void startGettingWindowFocus(View rootView) { + synchronized (mH) { + mCurRootView = rootView; + } + } + /** * Report the current selection range. */ public void updateSelection(View view, int selStart, int selEnd, int candidatesStart, int candidatesEnd) { + checkFocus(); synchronized (mH) { - if (mServedView != view || mCurrentTextBoxAttribute == null - || mCurMethod == null) { + if ((mServedView != view && (mServedView == null + || !mServedView.checkInputConnectionProxy(view))) + || mCurrentTextBoxAttribute == null || mCurMethod == null) { return; } @@ -984,9 +1197,11 @@ public final class InputMethodManager { * Report the current cursor location in its window. */ public void updateCursor(View view, int left, int top, int right, int bottom) { + checkFocus(); synchronized (mH) { - if (mServedView != view || mCurrentTextBoxAttribute == null - || mCurMethod == null) { + if ((mServedView != view && (mServedView == null + || !mServedView.checkInputConnectionProxy(view))) + || mCurrentTextBoxAttribute == null || mCurMethod == null) { return; } @@ -1005,6 +1220,34 @@ public final class InputMethodManager { } } + /** + * Call {@link InputMethodSession#appPrivateCommand(String, Bundle) + * InputMethodSession.appPrivateCommand()} on the current Input Method. + * @param view Optional View that is sending the command, or null if + * you want to send the command regardless of the view that is attached + * to the input method. + * @param action Name of the command to be performed. This must + * be a scoped name, i.e. prefixed with a package name you own, so that + * different developers will not create conflicting commands. + * @param data Any data to include with the command. + */ + public void sendAppPrivateCommand(View view, String action, Bundle data) { + checkFocus(); + synchronized (mH) { + if ((mServedView != view && (mServedView == null + || !mServedView.checkInputConnectionProxy(view))) + || mCurrentTextBoxAttribute == null || mCurMethod == null) { + return; + } + try { + if (DEBUG) Log.v(TAG, "APP PRIVATE COMMAND " + action + ": " + data); + mCurMethod.appPrivateCommand(action, data); + } catch (RemoteException e) { + Log.w(TAG, "IME died: " + mCurId, e); + } + } + } + /** * Force switch to a new input method component. This can only be called * from the currently active input method, as validated by the given token. @@ -1030,7 +1273,8 @@ public final class InputMethodManager { * when it was started, which allows it to perform this operation on * itself. * @param flags Provides additional operating flags. Currently may be - * 0 or have the {@link #HIDE_IMPLICIT_ONLY} bit set. + * 0 or have the {@link #HIDE_IMPLICIT_ONLY}, + * {@link #HIDE_NOT_ALWAYS} bit set. */ public void hideSoftInputFromInputMethod(IBinder token, int flags) { try { @@ -1040,6 +1284,27 @@ public final class InputMethodManager { } } + /** + * Show the input method's soft input area, so the user + * sees the input method window and can interact with it. + * This can only be called from the currently active input method, + * as validated by the given token. + * + * @param token Supplies the identifying token given to an input method + * when it was started, which allows it to perform this operation on + * itself. + * @param flags Provides additional operating flags. Currently may be + * 0 or have the {@link #SHOW_IMPLICIT} or + * {@link #SHOW_FORCED} bit set. + */ + public void showSoftInputFromInputMethod(IBinder token, int flags) { + try { + mService.showMySoftInput(token, flags); + } catch (RemoteException e) { + throw new RuntimeException(e); + } + } + /** * @hide */ @@ -1048,7 +1313,7 @@ public final class InputMethodManager { synchronized (mH) { if (DEBUG) Log.d(TAG, "dispatchKeyEvent"); - if (mCurMethod == null || mCurrentTextBoxAttribute == null) { + if (mCurMethod == null) { try { callback.finishedEvent(seq, false); } catch (RemoteException e) { @@ -1116,4 +1381,36 @@ public final class InputMethodManager { } } } + + void doDump(FileDescriptor fd, PrintWriter fout, String[] args) { + final Printer p = new PrintWriterPrinter(fout); + p.println("Input method client state for " + this + ":"); + + p.println(" mService=" + mService); + p.println(" mMainLooper=" + mMainLooper); + p.println(" mIInputContext=" + mIInputContext); + p.println(" mActive=" + mActive + + " mHasBeenInactive=" + mHasBeenInactive + + " mBindSequence=" + mBindSequence + + " mCurId=" + mCurId); + p.println(" mCurMethod=" + mCurMethod); + p.println(" mCurRootView=" + mCurRootView); + p.println(" mServedView=" + mServedView); + p.println(" mNextServedNeedsStart=" + mNextServedNeedsStart + + " mNextServedView=" + mNextServedView); + p.println(" mServedConnecting=" + mServedConnecting); + if (mCurrentTextBoxAttribute != null) { + p.println(" mCurrentTextBoxAttribute:"); + mCurrentTextBoxAttribute.dump(p, " "); + } else { + p.println(" mCurrentTextBoxAttribute: null"); + } + p.println(" mServedInputConnection=" + mServedInputConnection); + p.println(" mCompletions=" + mCompletions); + p.println(" mCursorRect=" + mCursorRect); + p.println(" mCursorSelStart=" + mCursorSelStart + + " mCursorSelEnd=" + mCursorSelEnd + + " mCursorCandStart=" + mCursorCandStart + + " mCursorCandEnd=" + mCursorCandEnd); + } } diff --git a/core/java/android/view/inputmethod/InputMethodSession.java b/core/java/android/view/inputmethod/InputMethodSession.java index b5bbaffdbf4f470fb01c5e750df4eb339f265283..bb03afad56ae09cfb8719edbdbef184976475c09 100644 --- a/core/java/android/view/inputmethod/InputMethodSession.java +++ b/core/java/android/view/inputmethod/InputMethodSession.java @@ -139,4 +139,16 @@ public interface InputMethodSession { * @param data Any data to include with the command. */ public void appPrivateCommand(String action, Bundle data); + + /** + * Toggle the soft input window. + * Applications can toggle the state of the soft input window. + * @param showFlags Provides additional operating flags. May be + * 0 or have the {@link InputMethodManager#SHOW_IMPLICIT}, + * {@link InputMethodManager#SHOW_FORCED} bit set. + * @param hideFlags Provides additional operating flags. May be + * 0 or have the {@link InputMethodManager#HIDE_IMPLICIT_ONLY}, + * {@link InputMethodManager#HIDE_NOT_ALWAYS} bit set. + */ + public void toggleSoftInput(int showFlags, int hideFlags); } diff --git a/core/java/android/view/inputmethod/MutableInputConnectionWrapper.java b/core/java/android/view/inputmethod/MutableInputConnectionWrapper.java deleted file mode 100644 index 025a0599aab0bc9352f90cf5d809d641f1f19771..0000000000000000000000000000000000000000 --- a/core/java/android/view/inputmethod/MutableInputConnectionWrapper.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2007-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. - */ - -package android.view.inputmethod; - - -/** - * Special version of {@link InputConnectionWrapper} that allows the base - * input connection to be modified after it is initially set. - */ -public class MutableInputConnectionWrapper extends InputConnectionWrapper { - public MutableInputConnectionWrapper(InputConnection base) { - super(base); - } - - /** - * Change the base InputConnection for this wrapper. All calls will then be - * delegated to the base input connection. - * - * @param base The new base InputConnection for this wrapper. - */ - public void setBaseInputConnection(InputConnection base) { - mBase = base; - } -} diff --git a/core/java/android/webkit/BrowserFrame.java b/core/java/android/webkit/BrowserFrame.java index 1dd37be06493ffe5be2c8bb7c85b81cca9ec5bd1..5401a6e0af12a220f5d8ebd69edc94ffec0100d7 100644 --- a/core/java/android/webkit/BrowserFrame.java +++ b/core/java/android/webkit/BrowserFrame.java @@ -51,7 +51,7 @@ class BrowserFrame extends Handler { private final Context mContext; private final WebViewDatabase mDatabase; private final WebViewCore mWebViewCore; - private boolean mLoadInitFromJava; + /* package */ boolean mLoadInitFromJava; private int mLoadType; private boolean mFirstLayoutDone = true; private boolean mCommitted = true; @@ -201,10 +201,14 @@ class BrowserFrame extends Handler { final String failingUrl) { // As this is called for the main resource and loading will be stopped // after, reset the state variables. + resetLoadingStates(); + mCallbackProxy.onReceivedError(errorCode, description, failingUrl); + } + + private void resetLoadingStates() { mCommitted = true; mWebViewCore.mEndScaleZoom = mFirstLayoutDone == false; mFirstLayoutDone = true; - mCallbackProxy.onReceivedError(errorCode, description, failingUrl); } /* package */boolean committed() { @@ -290,6 +294,7 @@ class BrowserFrame extends Handler { if (isMainFrame || loadType == FRAME_LOADTYPE_STANDARD) { if (isMainFrame) { + resetLoadingStates(); mCallbackProxy.switchOutDrawHistory(); mCallbackProxy.onPageFinished(url); } @@ -555,8 +560,11 @@ class BrowserFrame extends Handler { method, isHighPriority); loader.setHeaders(headers); loader.setPostData(postData); - loader.setCacheMode(cacheMode); // Set the load mode to the mode used - // for the current page. + // Set the load mode to the mode used for the current page. + // If WebKit wants validation, go to network directly. + loader.setCacheMode(headers.containsKey("If-Modified-Since") + || headers.containsKey("If-None-Match") ? + WebSettings.LOAD_NO_CACHE : cacheMode); // Set referrer to current URL? if (!loader.executeLoad()) { checker.responseAlert("startLoadingResource fail"); @@ -751,7 +759,14 @@ class BrowserFrame extends Handler { /** * Stop loading the current page. */ - public native void stopLoading(); + public void stopLoading() { + if (mIsMainFrame) { + resetLoadingStates(); + } + nativeStopLoading(); + } + + private native void nativeStopLoading(); /** * Return true if the document has images. diff --git a/core/java/android/webkit/ByteArrayBuilder.java b/core/java/android/webkit/ByteArrayBuilder.java index 16d663ce390baf50c630e579c175c4b6742974c3..806b458fa8c096c6a328e1ce81fb1cf0b97bb0bf 100644 --- a/core/java/android/webkit/ByteArrayBuilder.java +++ b/core/java/android/webkit/ByteArrayBuilder.java @@ -94,6 +94,14 @@ class ByteArrayBuilder { return mChunks.isEmpty(); } + public synchronized void clear() { + Chunk c = getFirstChunk(); + while (c != null) { + releaseChunk(c); + c = getFirstChunk(); + } + } + private Chunk appendChunk(int length) { if (length < mMinCapacity) { length = mMinCapacity; diff --git a/core/java/android/webkit/CacheManager.java b/core/java/android/webkit/CacheManager.java index d12940d04f41e3f4450da79738714a6a8c7739e6..dcf68cd9353f302c3614a05cafcfdf6dfca4bd0e 100644 --- a/core/java/android/webkit/CacheManager.java +++ b/core/java/android/webkit/CacheManager.java @@ -52,6 +52,7 @@ public final class CacheManager { private static final String NO_STORE = "no-store"; private static final String NO_CACHE = "no-cache"; + private static final String PRIVATE = "private"; private static final String MAX_AGE = "max-age"; private static long CACHE_THRESHOLD = 6 * 1024 * 1024; @@ -612,7 +613,7 @@ public final class CacheManager { // must be re-validated on every load. It does not mean that // the content can not be cached. set to expire 0 means it // can only be used in CACHE_MODE_CACHE_ONLY case - if (NO_CACHE.equals(controls[i])) { + if (NO_CACHE.equals(controls[i]) || PRIVATE.equals(controls[i])) { ret.expires = 0; } else if (controls[i].startsWith(MAX_AGE)) { int separator = controls[i].indexOf('='); diff --git a/core/java/android/webkit/CallbackProxy.java b/core/java/android/webkit/CallbackProxy.java index 4f8e5e4fbcbeb8629e202d6d8fa7140894b4fff2..0f9f29cedb6d6df8ecef5626730402caf52048c0 100644 --- a/core/java/android/webkit/CallbackProxy.java +++ b/core/java/android/webkit/CallbackProxy.java @@ -29,6 +29,7 @@ import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; +import android.provider.Browser; import android.util.Config; import android.util.Log; import android.view.KeyEvent; @@ -175,6 +176,11 @@ class CallbackProxy extends Handler { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(overrideUrl)); intent.addCategory(Intent.CATEGORY_BROWSABLE); + // If another application is running a WebView and launches the + // Browser through this Intent, we want to reuse the same window if + // possible. + intent.putExtra(Browser.EXTRA_APPLICATION_ID, + mContext.getPackageName()); try { mContext.startActivity(intent); override = true; @@ -907,10 +913,12 @@ class CallbackProxy extends Handler { } public void onReceivedIcon(Bitmap icon) { - if (Config.DEBUG && mBackForwardList.getCurrentItem() == null) { - throw new AssertionError(); + // The current item might be null if the icon was already stored in the + // database and this is a new WebView. + WebHistoryItem i = mBackForwardList.getCurrentItem(); + if (i != null) { + i.setFavicon(icon); } - mBackForwardList.getCurrentItem().setFavicon(icon); // Do an unsynchronized quick check to avoid posting if no callback has // been set. if (mWebChromeClient == null) { diff --git a/core/java/android/webkit/CookieManager.java b/core/java/android/webkit/CookieManager.java index 5a37f040d5ff7780f4ccf8eed6aed7b5ce18d7ce..d90a2fdbd11b1abc12ac56f8fa2fe3440fa716fe 100644 --- a/core/java/android/webkit/CookieManager.java +++ b/core/java/android/webkit/CookieManager.java @@ -171,6 +171,10 @@ public final class CookieManager { boolean pathMatch(String urlPath) { if (urlPath.startsWith(path)) { int len = path.length(); + if (len == 0) { + Log.w(LOGTAG, "Empty cookie path"); + return false; + } int urlLen = urlPath.length(); if (path.charAt(len-1) != PATH_DELIM && urlLen > len) { // make sure /wee doesn't match /we @@ -739,11 +743,16 @@ public final class CookieManager { * Note: in the case of "foo=bluh, bar=bluh;path=/", we interpret * it as one cookie instead of two cookies. */ + int semicolonIndex = cookieString.indexOf(SEMICOLON, index); int equalIndex = cookieString.indexOf(EQUAL, index); if (equalIndex == -1) { // bad format, force return break; } + if (semicolonIndex > -1 && semicolonIndex < equalIndex) { + // empty cookie, like "; path=/", return + break; + } cookie = new Cookie(host, path); cookie.name = cookieString.substring(index, equalIndex); if (cookieString.charAt(equalIndex + 1) == QUOTATION) { @@ -753,7 +762,7 @@ public final class CookieManager { break; } } - int semicolonIndex = cookieString.indexOf(SEMICOLON, index); + semicolonIndex = cookieString.indexOf(SEMICOLON, index); if (semicolonIndex == -1) { semicolonIndex = length; } @@ -864,7 +873,10 @@ public final class CookieManager { "illegal format for max-age: " + value); } } else if (name.equals(PATH)) { - cookie.path = value; + // only allow non-empty path value + if (value.length() > 0) { + cookie.path = value; + } } else if (name.equals(DOMAIN)) { int lastPeriod = value.lastIndexOf(PERIOD); if (lastPeriod == 0) { diff --git a/core/java/android/webkit/FileLoader.java b/core/java/android/webkit/FileLoader.java index 10343b2c0e24157a8c4eda9cc911a4c4d0638536..54a4c1d12468c77f2f77a1b198de24c969083974 100644 --- a/core/java/android/webkit/FileLoader.java +++ b/core/java/android/webkit/FileLoader.java @@ -76,8 +76,12 @@ class FileLoader extends StreamLoader { protected boolean setupStreamAndSendStatus() { try { if (mIsAsset) { - mDataStream = mContext.getAssets().open(mPath, - AssetManager.ACCESS_STREAMING); + try { + mDataStream = mContext.getAssets().open(mPath); + } catch (java.io.FileNotFoundException ex) { + // try the rest files included in the package + mDataStream = mContext.getAssets().openNonAsset(mPath); + } } else { if (!mAllowFileAccess) { mHandler.error(EventHandler.FILE_ERROR, diff --git a/core/java/android/webkit/FrameLoader.java b/core/java/android/webkit/FrameLoader.java index 7a3bbe6ca32ba2afb0ae12441b394b1c7307d319..42d03f0dcc99b648ee242f165574aff203636b10 100644 --- a/core/java/android/webkit/FrameLoader.java +++ b/core/java/android/webkit/FrameLoader.java @@ -21,7 +21,6 @@ import android.net.http.RequestHandle; import android.util.Config; import android.util.Log; import android.webkit.CacheManager.CacheResult; -import android.webkit.UrlInterceptRegistry; import java.util.HashMap; import java.util.Map; @@ -220,6 +219,7 @@ class FrameLoader { // Tell the Listener respond with the cache file CacheLoader cacheLoader = new CacheLoader(mListener, result); + mListener.setCacheLoader(cacheLoader); cacheLoader.load(); } @@ -233,12 +233,14 @@ class FrameLoader { private boolean handleUrlIntercept() { // Check if the URL can be served from UrlIntercept. If // successful, return the data just like a cache hit. - CacheResult result = UrlInterceptRegistry.getSurrogate( + + PluginData data = UrlInterceptRegistry.getPluginData( mListener.url(), mHeaders); - if(result != null) { - // Intercepted. The data is stored in result.stream. Setup - // a load from the CacheResult. - startCacheLoad(result); + + if(data != null) { + PluginContentLoader loader = + new PluginContentLoader(mListener, data); + loader.load(); return true; } // Not intercepted. Carry on as normal. diff --git a/core/java/android/webkit/LoadListener.java b/core/java/android/webkit/LoadListener.java index 3f2bbe5a7908591883a6f9d15d03608102e71795..f9fb0b0fccaae6610687057dd71affafe68c5169 100644 --- a/core/java/android/webkit/LoadListener.java +++ b/core/java/android/webkit/LoadListener.java @@ -33,6 +33,8 @@ import android.util.Config; import android.util.Log; import android.webkit.CacheManager.CacheResult; +import com.android.internal.R; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -56,6 +58,9 @@ class LoadListener extends Handler implements EventHandler { private static final int MSG_CONTENT_ERROR = 130; private static final int MSG_LOCATION_CHANGED = 140; private static final int MSG_LOCATION_CHANGED_REQUEST = 150; + private static final int MSG_STATUS = 160; + private static final int MSG_SSL_CERTIFICATE = 170; + private static final int MSG_SSL_ERROR = 180; // Standard HTTP status codes in a more representative format private static final int HTTP_OK = 200; @@ -166,9 +171,7 @@ class LoadListener extends Handler implements EventHandler { * available. The headers are sent onto WebCore to see what we * should do with them. */ - if (mNativeLoader != 0) { - commitHeadersCheckRedirect(); - } + handleHeaders((Headers) msg.obj); break; case MSG_CONTENT_DATA: @@ -177,7 +180,7 @@ class LoadListener extends Handler implements EventHandler { * in it's data buffer. This data buffer could be filled from a * file (this thread) or from http (Network thread). */ - if (mNativeLoader != 0) { + if (mNativeLoader != 0 && !ignoreCallbacks()) { commitLoad(); } break; @@ -189,7 +192,7 @@ class LoadListener extends Handler implements EventHandler { * error. * */ - tearDown(); + handleEndData(); break; case MSG_CONTENT_ERROR: @@ -197,8 +200,7 @@ class LoadListener extends Handler implements EventHandler { * This message is sent when a load error has occured. The * LoadListener will clean itself up. */ - notifyError(); - tearDown(); + handleError(msg.arg1, (String) msg.obj); break; case MSG_LOCATION_CHANGED: @@ -224,6 +226,33 @@ class LoadListener extends Handler implements EventHandler { stopMsg, contMsg); break; + case MSG_STATUS: + /* + * This message is sent from the network thread when the http + * stack has received the status response from the server. + */ + HashMap status = (HashMap) msg.obj; + handleStatus(((Integer) status.get("major")).intValue(), + ((Integer) status.get("minor")).intValue(), + ((Integer) status.get("code")).intValue(), + (String) status.get("reason")); + break; + + case MSG_SSL_CERTIFICATE: + /* + * This message is sent when the network thread receives a ssl + * certificate. + */ + handleCertificate((SslCertificate) msg.obj); + break; + + case MSG_SSL_ERROR: + /* + * This message is sent when the network thread encounters a + * ssl error. + */ + handleSslError((SslError) msg.obj); + break; } } @@ -257,6 +286,11 @@ class LoadListener extends Handler implements EventHandler { */ public void headers(Headers headers) { if (Config.LOGV) Log.v(LOGTAG, "LoadListener.headers"); + sendMessageInternal(obtainMessage(MSG_CONTENT_HEADERS, headers)); + } + + // Does the header parsing work on the WebCore thread. + private void handleHeaders(Headers headers) { if (mCancelled) return; mHeaders = headers; mMimeType = ""; @@ -342,6 +376,11 @@ class LoadListener extends Handler implements EventHandler { } } } + + // if there is buffered data, commit them in the end + boolean needToCommit = mAuthHeader != null && !mustAuthenticate + && mNativeLoader != 0 && !mDataBuilder.isEmpty(); + // it is only here that we can reset the last mAuthHeader object // (if existed) and start a new one!!! mAuthHeader = null; @@ -375,7 +414,11 @@ class LoadListener extends Handler implements EventHandler { mCacheResult.encoding = mEncoding; } } - sendMessageInternal(obtainMessage(MSG_CONTENT_HEADERS)); + commitHeadersCheckRedirect(); + + if (needToCommit) { + commitLoad(); + } } /** @@ -404,11 +447,20 @@ class LoadListener extends Handler implements EventHandler { + " code: " + code + " reason: " + reasonPhrase); } + HashMap status = new HashMap(); + status.put("major", majorVersion); + status.put("minor", minorVersion); + status.put("code", code); + status.put("reason", reasonPhrase); + sendMessageInternal(obtainMessage(MSG_STATUS, status)); + } + // Handle the status callback on the WebCore thread. + private void handleStatus(int major, int minor, int code, String reason) { if (mCancelled) return; mStatusCode = code; - mStatusText = reasonPhrase; + mStatusText = reason; mPermanent = false; } @@ -418,8 +470,15 @@ class LoadListener extends Handler implements EventHandler { * connection. In this context, can be called multiple * times if we have redirects * @param certificate The SSL certifcate + * IMPORTANT: as this is called from network thread, can't call native + * directly */ public void certificate(SslCertificate certificate) { + sendMessageInternal(obtainMessage(MSG_SSL_CERTIFICATE, certificate)); + } + + // Handle the certificate on the WebCore thread. + private void handleCertificate(SslCertificate certificate) { // if this is the top-most main-frame page loader if (mIsMainPageLoader) { // update the browser frame (ie, the main frame) @@ -436,14 +495,20 @@ class LoadListener extends Handler implements EventHandler { * directly */ public void error(int id, String description) { - mErrorID = id; - mErrorDescription = description; - sendMessageInternal(obtainMessage(MSG_CONTENT_ERROR)); if (Config.LOGV) { Log.v(LOGTAG, "LoadListener.error url:" + url() + " id:" + id + " description:" + description); } + sendMessageInternal(obtainMessage(MSG_CONTENT_ERROR, id, 0, description)); + } + + // Handle the error on the WebCore thread. + private void handleError(int id, String description) { + mErrorID = id; + mErrorDescription = description; detachRequestHandle(); + notifyError(); + tearDown(); } /** @@ -453,11 +518,15 @@ class LoadListener extends Handler implements EventHandler { * @param length The length of data. * IMPORTANT: as this is called from network thread, can't call native * directly + * XXX: Unlike the other network thread methods, this method can do the + * work of decoding the data and appending it to the data builder because + * mDataBuilder is a thread-safe structure. */ public void data(byte[] data, int length) { if (Config.LOGV) { Log.v(LOGTAG, "LoadListener.data(): url: " + url()); } + // Decode base64 data // Note: It's fine that we only decode base64 here and not in the other // data call because the only caller of the stream version is not @@ -479,7 +548,7 @@ class LoadListener extends Handler implements EventHandler { sendMessage = mDataBuilder.isEmpty(); mDataBuilder.append(data, 0, length); } - if (sendMessage && !ignoreCallbacks()) { + if (sendMessage) { // Send a message whenever data comes in after a write to WebCore sendMessageInternal(obtainMessage(MSG_CONTENT_DATA)); } @@ -495,7 +564,11 @@ class LoadListener extends Handler implements EventHandler { if (Config.LOGV) { Log.v(LOGTAG, "LoadListener.endData(): url: " + url()); } + sendMessageInternal(obtainMessage(MSG_CONTENT_FINISHED)); + } + // Handle the end of data. + private void handleEndData() { if (mCancelled) return; switch (mStatusCode) { @@ -505,17 +578,13 @@ class LoadListener extends Handler implements EventHandler { case HTTP_FOUND: case HTTP_SEE_OTHER: case HTTP_TEMPORARY_REDIRECT: - if (mMethod == null && mRequestHandle == null) { - Log.e(LOGTAG, "LoadListener.endData(): method is null!"); - Log.e(LOGTAG, "LoadListener.endData(): url = " + url()); - } // 301, 302, 303, and 307 - redirect if (mStatusCode == HTTP_TEMPORARY_REDIRECT) { if (mRequestHandle != null && mRequestHandle.getMethod().equals("POST")) { sendMessageInternal(obtainMessage( MSG_LOCATION_CHANGED_REQUEST)); - } else if (mMethod != null && mMethod.equals("POST")) { + } else if (mMethod != null && mMethod.equals("POST")) { sendMessageInternal(obtainMessage( MSG_LOCATION_CHANGED_REQUEST)); } else { @@ -558,9 +627,14 @@ class LoadListener extends Handler implements EventHandler { default: break; } - - sendMessageInternal(obtainMessage(MSG_CONTENT_FINISHED)); detachRequestHandle(); + tearDown(); + } + + /* This method is called from CacheLoader when the initial request is + * serviced by the Cache. */ + /* package */ void setCacheLoader(CacheLoader c) { + mCacheLoader = c; } /** @@ -574,9 +648,16 @@ class LoadListener extends Handler implements EventHandler { CacheResult result = CacheManager.getCacheFile(url(), headers); + // Go ahead and set the cache loader to null in case the result is + // null. + mCacheLoader = null; + if (result != null) { - CacheLoader cacheLoader = - new CacheLoader(this, result); + // The contents of the cache may need to be revalidated so just + // remember the cache loader in the case that the server responds + // positively to the cached content. This is also used to detect if + // a redirect came from the cache. + mCacheLoader = new CacheLoader(this, result); // If I got a cachedUrl and the revalidation header was not // added, then the cached content valid, we should use it. @@ -589,14 +670,8 @@ class LoadListener extends Handler implements EventHandler { "and usable: " + url()); } // Load the cached file - cacheLoader.load(); + mCacheLoader.load(); return true; - } else { - // The contents of the cache need to be revalidated - // so just provide the listener with the cache loader - // in the case that the server response positively to - // the cached content. - setCacheLoader(cacheLoader); } } return false; @@ -615,7 +690,11 @@ class LoadListener extends Handler implements EventHandler { " primary error: " + error.getPrimaryError() + " certificate: " + error.getCertificate()); } + sendMessageInternal(obtainMessage(MSG_SSL_ERROR, error)); + } + // Handle the ssl error on the WebCore thread. + private void handleSslError(SslError error) { if (!mCancelled) { mSslError = error; Network.getInstance(mContext).handleSslErrorRequest(this); @@ -704,14 +783,6 @@ class LoadListener extends Handler implements EventHandler { } } - /** - * Set the CacheLoader for the case where we might want to load from cache - * @param result - */ - void setCacheLoader(CacheLoader result) { - mCacheLoader = result; - } - /** * This is called when a request can be satisfied by the cache, however, * the cache result could be a redirect. In this case we need to issue @@ -1002,6 +1073,11 @@ class LoadListener extends Handler implements EventHandler { clearNativeLoader(); } + // This count is transferred from RequestHandle to LoadListener when + // loading from the cache so that we can detect redirect loops that switch + // between the network and the cache. + private int mCacheRedirectCount; + /* * Perform the actual redirection. This involves setting up the new URL, * informing WebCore and then telling the Network to start loading again. @@ -1014,6 +1090,14 @@ class LoadListener extends Handler implements EventHandler { return; } + // Do the same check for a redirect loop that + // RequestHandle.setupRedirect does. + if (mCacheRedirectCount >= RequestHandle.MAX_REDIRECT_COUNT) { + handleError(EventHandler.ERROR_REDIRECT_LOOP, mContext.getString( + R.string.httpErrorRedirectLoop)); + return; + } + String redirectTo = mHeaders.getLocation(); if (redirectTo != null) { int nativeResponse = createNativeResponse(); @@ -1031,7 +1115,7 @@ class LoadListener extends Handler implements EventHandler { return; } else if (!URLUtil.isNetworkUrl(redirectTo)) { final String text = mContext - .getString(com.android.internal.R.string.open_permission_deny) + .getString(R.string.open_permission_deny) + "\n" + redirectTo; nativeAddData(text.getBytes(), text.length()); nativeFinished(); @@ -1051,36 +1135,58 @@ class LoadListener extends Handler implements EventHandler { mCacheResult = null; } + // This will strip the anchor setUrl(redirectTo); // Redirect may be in the cache if (mRequestHeaders == null) { mRequestHeaders = new HashMap(); } + boolean fromCache = false; + if (mCacheLoader != null) { + // This is a redirect from the cache loader. Increment the + // redirect count to avoid redirect loops. + mCacheRedirectCount++; + fromCache = true; + } if (!checkCache(mRequestHeaders)) { // mRequestHandle can be null when the request was satisfied // by the cache, and the cache returned a redirect if (mRequestHandle != null) { - mRequestHandle.setupRedirect(redirectTo, mStatusCode, + mRequestHandle.setupRedirect(mUrl, mStatusCode, mRequestHeaders); } else { - String method = mMethod; - - if (method == null) { + // If the original request came from the cache, there is no + // RequestHandle, we have to create a new one through + // Network.requestURL. + Network network = Network.getInstance(getContext()); + if (!network.requestURL(mMethod, mRequestHeaders, + mPostData, this, mIsHighPriority)) { + // Signal a bad url error if we could not load the + // redirection. + handleError(EventHandler.ERROR_BAD_URL, + mContext.getString(R.string.httpErrorBadUrl)); return; } - - Network network = Network.getInstance(getContext()); - network.requestURL(method, mRequestHeaders, - mPostData, this, mIsHighPriority); } + if (fromCache) { + // If we are coming from a cache load, we need to transfer + // the redirect count to the new (or old) RequestHandle to + // keep the redirect count in sync. + mRequestHandle.setRedirectCount(mCacheRedirectCount); + } + } else if (!fromCache) { + // Switching from network to cache means we need to grab the + // redirect count from the RequestHandle to keep the count in + // sync. Add 1 to account for the current redirect. + mCacheRedirectCount = mRequestHandle.getRedirectCount() + 1; } + // Clear the buffered data since the redirect is valid. + mDataBuilder.clear(); } else { - // With a null redirect, commit the original headers, the buffered - // data, and then finish the load. commitHeaders(); commitLoad(); - nativeFinished(); + tearDown(); } if (Config.LOGV) { @@ -1167,14 +1273,16 @@ class LoadListener extends Handler implements EventHandler { quoted = !quoted; } else { if (!quoted) { - if (header.startsWith( - HttpAuthHeader.BASIC_TOKEN, i)) { + if (header.regionMatches(true, i, + HttpAuthHeader.BASIC_TOKEN, 0, + HttpAuthHeader.BASIC_TOKEN.length())) { pos[posLen++] = i; continue; } - if (header.startsWith( - HttpAuthHeader.DIGEST_TOKEN, i)) { + if (header.regionMatches(true, i, + HttpAuthHeader.DIGEST_TOKEN, 0, + HttpAuthHeader.DIGEST_TOKEN.length())) { pos[posLen++] = i; continue; } @@ -1186,8 +1294,9 @@ class LoadListener extends Handler implements EventHandler { if (posLen > 0) { // consider all digest schemes first (if any) for (int i = 0; i < posLen; i++) { - if (header.startsWith(HttpAuthHeader.DIGEST_TOKEN, - pos[i])) { + if (header.regionMatches(true, pos[i], + HttpAuthHeader.DIGEST_TOKEN, 0, + HttpAuthHeader.DIGEST_TOKEN.length())) { String sub = header.substring(pos[i], (i + 1 < posLen ? pos[i + 1] : headerLen)); @@ -1201,7 +1310,9 @@ class LoadListener extends Handler implements EventHandler { // ...then consider all basic schemes (if any) for (int i = 0; i < posLen; i++) { - if (header.startsWith(HttpAuthHeader.BASIC_TOKEN, pos[i])) { + if (header.regionMatches(true, pos[i], + HttpAuthHeader.BASIC_TOKEN, 0, + HttpAuthHeader.BASIC_TOKEN.length())) { String sub = header.substring(pos[i], (i + 1 < posLen ? pos[i + 1] : headerLen)); @@ -1235,19 +1346,16 @@ class LoadListener extends Handler implements EventHandler { */ void setUrl(String url) { if (url != null) { - if (URLUtil.isDataUrl(url)) { - // Don't strip anchor as that is a valid part of the URL - mUrl = url; - } else { - mUrl = URLUtil.stripAnchor(url); - } mUri = null; - if (URLUtil.isNetworkUrl(mUrl)) { + if (URLUtil.isNetworkUrl(url)) { + mUrl = URLUtil.stripAnchor(url); try { mUri = new WebAddress(mUrl); } catch (ParseException e) { e.printStackTrace(); } + } else { + mUrl = url; } } } @@ -1262,9 +1370,8 @@ class LoadListener extends Handler implements EventHandler { // type (implying text/plain). if (URLUtil.isDataUrl(mUrl) && mMimeType.length() != 0) { cancel(); - final String text = mContext.getString( - com.android.internal.R.string.httpErrorBadUrl); - error(EventHandler.ERROR_BAD_URL, text); + final String text = mContext.getString(R.string.httpErrorBadUrl); + handleError(EventHandler.ERROR_BAD_URL, text); } else { // Note: This is ok because this is used only for the main content // of frames. If no content-type was specified, it is fine to diff --git a/core/java/android/webkit/MimeTypeMap.java b/core/java/android/webkit/MimeTypeMap.java index 685e3528f7fac8c99633c72de68ac1315b5fd1fd..c9cc20817c4fddb125585cb4c69e88d7bc4d790b 100644 --- a/core/java/android/webkit/MimeTypeMap.java +++ b/core/java/android/webkit/MimeTypeMap.java @@ -480,6 +480,7 @@ public /* package */ class MimeTypeMap { sMimeTypeMap.loadEntry("video/mpeg", "mpg", false); sMimeTypeMap.loadEntry("video/mpeg", "mpe", false); sMimeTypeMap.loadEntry("video/mp4", "mp4", false); + sMimeTypeMap.loadEntry("video/mpeg", "VOB", false); sMimeTypeMap.loadEntry("video/quicktime", "qt", false); sMimeTypeMap.loadEntry("video/quicktime", "mov", false); sMimeTypeMap.loadEntry("video/vnd.mpegurl", "mxu", false); diff --git a/core/java/android/webkit/PluginContentLoader.java b/core/java/android/webkit/PluginContentLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..206959980355771186eea7d14d35ec5d4c41a4c3 --- /dev/null +++ b/core/java/android/webkit/PluginContentLoader.java @@ -0,0 +1,96 @@ +/* + * 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. + */ + +package android.webkit; + +import android.net.http.Headers; + +import java.io.InputStream; +import java.util.*; + +import org.apache.http.util.CharArrayBuffer; + +/** + * This class is a concrete implementation of StreamLoader that uses a + * PluginData object as the source for the stream. + */ +class PluginContentLoader extends StreamLoader { + + private PluginData mData; // Content source + + /** + * Constructs a PluginDataLoader for use when loading content from + * a plugin. + * + * @param loadListener LoadListener to pass the content to + * @param data PluginData used as the source for the content. + */ + PluginContentLoader(LoadListener loadListener, PluginData data) { + super(loadListener); + mData = data; + } + + @Override + protected boolean setupStreamAndSendStatus() { + mDataStream = mData.getInputStream(); + mContentLength = mData.getContentLength(); + mHandler.status(1, 1, mData.getStatusCode(), "OK"); + return true; + } + + @Override + protected void buildHeaders(Headers headers) { + // Crate a CharArrayBuffer with an arbitrary initial capacity. + CharArrayBuffer buffer = new CharArrayBuffer(100); + Iterator> responseHeadersIt = + mData.getHeaders().entrySet().iterator(); + while (responseHeadersIt.hasNext()) { + Map.Entry entry = responseHeadersIt.next(); + // Headers.parseHeader() expects lowercase keys, so keys + // such as "Accept-Ranges" will fail to parse. + // + // UrlInterceptHandler instances supply a mapping of + // lowercase key to [ unmodified key, value ], so for + // Headers.parseHeader() to succeed, we need to construct + // a string using the key (i.e. entry.getKey()) and the + // element denoting the header value in the + // [ unmodified key, value ] pair (i.e. entry.getValue()[1). + // + // The reason why UrlInterceptHandler instances supply such a + // mapping in the first place is historical. Early versions of + // the Gears plugin used java.net.HttpURLConnection, which always + // returned headers names as capitalized strings. When these were + // fed back into webkit, they failed to parse. + // + // Mewanwhile, Gears was modified to use Apache HTTP library + // instead, so this design is now obsolete. Changing it however, + // would require changes to the Gears C++ codebase and QA-ing and + // submitting a new binary to the Android tree. Given the + // timelines for the next Android release, we will not do this + // for now. + // + // TODO: fix C++ Gears to remove the need for this + // design. + String keyValue = entry.getKey() + ": " + entry.getValue()[1]; + buffer.ensureCapacity(keyValue.length()); + buffer.append(keyValue); + // Parse it into the header container. + headers.parseHeader(buffer); + // Clear the buffer + buffer.clear(); + } + } +} diff --git a/core/java/android/webkit/PluginData.java b/core/java/android/webkit/PluginData.java new file mode 100644 index 0000000000000000000000000000000000000000..2b539fe0a76ef9c1f28cfb22a7e2a7b29247ab92 --- /dev/null +++ b/core/java/android/webkit/PluginData.java @@ -0,0 +1,116 @@ +/* + * 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. + */ + +package android.webkit; + +import java.io.InputStream; +import java.util.Map; + +/** + * This class encapsulates the content generated by a plugin. The + * data itself is meant to be loaded into webkit via the + * PluginContentLoader class, which needs to be able to construct an + * HTTP response. For this, it needs a stream with the response body, + * the length of the body, the response headers, and the response + * status code. The PluginData class is the container for all these + * parts. + * + */ +public final class PluginData { + /** + * The content stream. + */ + private InputStream mStream; + /** + * The content length. + */ + private long mContentLength; + /** + * The associated HTTP response headers stored as a map of + * lowercase header name to [ unmodified header name, header value]. + * TODO: This design was always a hack. Remove (involves updating + * the Gears C++ side). + */ + private Map mHeaders; + + /** + * The index of the header value in the above mapping. + */ + private int mHeaderValueIndex; + /** + * The associated HTTP response code. + */ + private int mStatusCode; + + /** + * Creates a PluginData instance. + * + * @param stream The stream that supplies content for the plugin. + * @param length The length of the plugin content. + * @param headers The response headers. Map of + * lowercase header name to [ unmodified header name, header value] + * @param length The HTTP response status code. + */ + public PluginData( + InputStream stream, + long length, + Map headers, + int code) { + mStream = stream; + mContentLength = length; + mHeaders = headers; + mStatusCode = code; + } + + /** + * Returns the input stream that contains the plugin content. + * + * @return An InputStream instance with the plugin content. + */ + public InputStream getInputStream() { + return mStream; + } + + /** + * Returns the length of the plugin content. + * + * @return the length of the plugin content. + */ + public long getContentLength() { + return mContentLength; + } + + /** + * Returns the HTTP response headers associated with the plugin + * content. + * + * @return A Map containing all headers. The + * mapping is 'lowercase header name' to ['unmodified header + * name', header value]. + */ + public Map getHeaders() { + return mHeaders; + } + + /** + * Returns the HTTP status code for the response. + * + * @return The HTTP statue code, e.g 200. + */ + public int getStatusCode() { + return mStatusCode; + } +} diff --git a/core/java/android/webkit/TextDialog.java b/core/java/android/webkit/TextDialog.java index b7b40b17059a5689e7a561a107487b9976c3c554..9de97c92267b03d7272c02469e210582d585444d 100644 --- a/core/java/android/webkit/TextDialog.java +++ b/core/java/android/webkit/TextDialog.java @@ -25,18 +25,13 @@ import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RectShape; -import android.os.Handler; -import android.os.Message; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.text.Spannable; import android.text.TextPaint; import android.text.TextUtils; -import android.text.method.MetaKeyKeyListener; import android.text.method.MovementMethod; -import android.text.method.PasswordTransformationMethod; -import android.text.method.TextKeyListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.view.KeyCharacterMap; @@ -44,8 +39,6 @@ import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; -import android.view.View.MeasureSpec; -import android.view.ViewConfiguration; import android.widget.AbsoluteLayout.LayoutParams; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; @@ -69,10 +62,8 @@ import java.util.ArrayList; // on the enter key. The method for blocking unmatched key ups prevents // the shift key from working properly. private boolean mGotEnterDown; - // Determines whether we allow calls to requestRectangleOnScreen to - // propagate. We only want to scroll if the user is typing. If the - // user is simply navigating through a textfield, we do not want to - // scroll. + // mScrollToAccommodateCursor being set to false prevents us from scrolling + // the cursor on screen when using the trackball to select a textfield. private boolean mScrollToAccommodateCursor; private int mMaxLength; // Keep track of the text before the change so we know whether we actually @@ -86,22 +77,6 @@ import java.util.ArrayList; // FIXME: This can be replaced with TextView.NO_FILTERS if that // is made public/protected. private static final InputFilter[] NO_FILTERS = new InputFilter[0]; - // The time of the last enter down, so we know whether to perform a long - // press. - private long mDownTime; - - private boolean mTrackballDown = false; - private static int LONGPRESS = 1; - private Handler mHandler = new Handler() { - public void handleMessage(Message msg) { - if (msg.what == LONGPRESS) { - if (mTrackballDown) { - performLongClick(); - mTrackballDown = false; - } - } - } - }; /** * Create a new TextDialog. @@ -136,6 +111,7 @@ import java.util.ArrayList; // that other applications that use embedded WebViews will properly // display the text in textfields. setTextColor(Color.BLACK); + setImeOptions(EditorInfo.IME_ACTION_NONE); } @Override @@ -156,38 +132,33 @@ import java.util.ArrayList; return true; } - // For single-line textfields, return key should not be handled - // here. Instead, the WebView is passed the key up, so it may fire a - // submit/onClick. - // Center key should always be passed to a potential onClick - if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode) - || KeyEvent.KEYCODE_DPAD_CENTER == keyCode) { + if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode)) { if (isPopupShowing()) { - super.dispatchKeyEvent(event); - return true; + return super.dispatchKeyEvent(event); } - if (down) { - if (event.getRepeatCount() == 0) { - mGotEnterDown = true; - mDownTime = event.getEventTime(); - // Send the keydown when the up comes, so that we have - // a chance to handle a long press. - } else if (mGotEnterDown && event.getEventTime() - mDownTime > - ViewConfiguration.getLongPressTimeout()) { - performLongClick(); - mGotEnterDown = false; - } - } else if (mGotEnterDown) { - mGotEnterDown = false; - if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) { - mWebView.shortPressOnTextField(); - return true; - } + if (!down) { + // Hide the keyboard, since the user has just submitted this + // form. The submission happens thanks to the two calls + // to sendDomEvent. + InputMethodManager.getInstance(mContext) + .hideSoftInputFromWindow(getWindowToken(), 0); sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); sendDomEvent(event); } - return true; + return super.dispatchKeyEvent(event); + } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) { + // Note that this handles center key and trackball. + if (isPopupShowing()) { + return super.dispatchKeyEvent(event); + } + // Center key should be passed to a potential onClick + if (!down) { + mWebView.shortPressOnTextField(); + } + // Pass to super to handle longpress. + return super.dispatchKeyEvent(event); } + // Ensure there is a layout so arrow keys are handled properly. if (getLayout() == null) { measure(mWidthSpec, mHeightSpec); @@ -224,9 +195,8 @@ import java.util.ArrayList; case KeyEvent.KEYCODE_DPAD_DOWN: isArrowKey = true; break; - case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: - // For multi-line text boxes, newlines and dpad center will + // For multi-line text boxes, newlines will // trigger onTextChanged for key down (which will send both // key up and key down) but not key up. mGotEnterDown = true; @@ -268,7 +238,7 @@ import java.util.ArrayList; // with WebCore's notion of the current selection, reset the selection // to what it was before the key event. Selection.setSelection(text, oldStart, oldEnd); - // Ignore the key up event for newlines or dpad center. This prevents + // Ignore the key up event for newlines. This prevents // multiple newlines in the native textarea. if (mGotEnterDown && !down) { return true; @@ -289,6 +259,25 @@ import java.util.ArrayList; return false; } + /** + * Create a fake touch up event at (x,y) with respect to this TextDialog. + * This is used by WebView to act as though a touch event which happened + * before we placed the TextDialog actually hit it, so that it can place + * the cursor accordingly. + */ + /* package */ void fakeTouchEvent(float x, float y) { + // We need to ensure that there is a Layout, since the Layout is used + // in determining where to place the cursor. + if (getLayout() == null) { + measure(mWidthSpec, mHeightSpec); + } + // Create a fake touch up, which is used to place the cursor. + MotionEvent ev = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, + x, y, 0); + onTouchEvent(ev); + ev.recycle(); + } + /** * Determine whether this TextDialog currently represents the node * represented by ptr. @@ -371,27 +360,8 @@ import java.util.ArrayList; if (isPopupShowing()) { return super.onTrackballEvent(event); } - int action = event.getAction(); - switch (action) { - case MotionEvent.ACTION_DOWN: - if (!mTrackballDown) { - mTrackballDown = true; - mHandler.sendEmptyMessageDelayed(LONGPRESS, - ViewConfiguration.getLongPressTimeout()); - } - return true; - case MotionEvent.ACTION_UP: - if (mTrackballDown) { - mWebView.shortPressOnTextField(); - mTrackballDown = false; - mHandler.removeMessages(LONGPRESS); - } - return true; - case MotionEvent.ACTION_CANCEL: - mTrackballDown = false; - return true; - case MotionEvent.ACTION_MOVE: - // fall through + if (event.getAction() != MotionEvent.ACTION_MOVE) { + return false; } Spannable text = (Spannable) getText(); MovementMethod move = getMovementMethod(); @@ -405,6 +375,12 @@ import java.util.ArrayList; //mWebView.setSelection(start, end); return true; } + // If the user is in a textfield, and the movement method is not + // handling the trackball events, it means they are at the end of the + // field and continuing to move the trackball. In this case, we should + // not scroll the cursor on screen bc the user may be attempting to + // scroll the page, possibly in the opposite direction of the cursor. + mScrollToAccommodateCursor = false; return false; } @@ -416,9 +392,19 @@ import java.util.ArrayList; // hide the soft keyboard when the edit text is out of focus InputMethodManager.getInstance(mContext).hideSoftInputFromWindow( getWindowToken(), 0); - mHandler.removeMessages(LONGPRESS); mWebView.removeView(this); mWebView.requestFocus(); + mScrollToAccommodateCursor = false; + } + + /* package */ void enableScrollOnScreen(boolean enable) { + mScrollToAccommodateCursor = enable; + } + + /* package */ void bringIntoView() { + if (getLayout() != null) { + bringPointIntoView(Selection.getSelectionEnd(getText())); + } } @Override @@ -437,8 +423,15 @@ import java.util.ArrayList; mWebView.passToJavaScript(getText().toString(), event); } + /** + * Always use this instead of setAdapter, as this has features specific to + * the TextDialog. + */ public void setAdapterCustom(AutoCompleteAdapter adapter) { - adapter.setTextView(this); + if (adapter != null) { + setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); + adapter.setTextView(this); + } super.setAdapter(adapter); } @@ -480,15 +473,10 @@ import java.util.ArrayList; * @param inPassword True if the textfield is a password field. */ /* package */ void setInPassword(boolean inPassword) { - PasswordTransformationMethod method; if (inPassword) { - method = PasswordTransformationMethod.getInstance(); - } else { - method = null; + setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. + TYPE_TEXT_VARIATION_PASSWORD); } - setTransformationMethod(method); - setInputType(inPassword ? EditorInfo.TYPE_TEXT_VARIATION_PASSWORD : - EditorInfo.TYPE_CLASS_TEXT); } /* package */ void setMaxLength(int maxLength) { @@ -539,7 +527,6 @@ import java.util.ArrayList; // Set up a measure spec so a layout can always be recreated. mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); - mScrollToAccommodateCursor = false; requestFocus(); } @@ -547,19 +534,19 @@ import java.util.ArrayList; * Set whether this is a single-line textfield or a multi-line textarea. * Textfields scroll horizontally, and do not handle the enter key. * Textareas behave oppositely. + * Do NOT call this after calling setInPassword(true). This will result in + * removing the password input type. */ public void setSingleLine(boolean single) { - if (mSingle != single) { - TextKeyListener.Capitalize cap; - if (single) { - cap = TextKeyListener.Capitalize.NONE; - } else { - cap = TextKeyListener.Capitalize.SENTENCES; - } - setKeyListener(TextKeyListener.getInstance(!single, cap)); - mSingle = single; - setHorizontallyScrolling(single); + int inputType = EditorInfo.TYPE_CLASS_TEXT; + if (!single) { + inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE + | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES + | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; } + mSingle = single; + setHorizontallyScrolling(single); + setInputType(inputType); } /** diff --git a/core/java/android/webkit/UrlInterceptHandler.java b/core/java/android/webkit/UrlInterceptHandler.java index e1c9d61b518fb1dd9a1aa7c2cb266930fd13647c..9216413c4a753ff9b4c1bde8e91aa012791448aa 100644 --- a/core/java/android/webkit/UrlInterceptHandler.java +++ b/core/java/android/webkit/UrlInterceptHandler.java @@ -17,6 +17,7 @@ package android.webkit; import android.webkit.CacheManager.CacheResult; +import android.webkit.PluginData; import java.util.Map; public interface UrlInterceptHandler { @@ -29,6 +30,20 @@ public interface UrlInterceptHandler { * @param url URL string. * @param headers The headers associated with the request. May be null. * @return The CacheResult containing the surrogate response. + * @Deprecated Use PluginData getPluginData(String url, + * Map headers); instead */ + @Deprecated public CacheResult service(String url, Map headers); + + /** + * Given an URL, returns the PluginData which contains the + * surrogate response for the request, or null if the handler is + * not interested. + * + * @param url URL string. + * @param headers The headers associated with the request. May be null. + * @return The PluginData containing the surrogate response. + */ + public PluginData getPluginData(String url, Map headers); } diff --git a/core/java/android/webkit/UrlInterceptRegistry.java b/core/java/android/webkit/UrlInterceptRegistry.java index a218191db27de5df30a9b0d95d4966c887844ba3..6051f290dffe1e53de0fda7fd6c7ddfea8e7cdff 100644 --- a/core/java/android/webkit/UrlInterceptRegistry.java +++ b/core/java/android/webkit/UrlInterceptRegistry.java @@ -17,6 +17,7 @@ package android.webkit; import android.webkit.CacheManager.CacheResult; +import android.webkit.PluginData; import android.webkit.UrlInterceptHandler; import java.util.Iterator; @@ -82,17 +83,21 @@ public final class UrlInterceptRegistry { UrlInterceptHandler handler) { return getHandlers().remove(handler); } - + /** * Given an url, returns the CacheResult of the first * UrlInterceptHandler interested, or null if none are. - * + * * @return A CacheResult containing surrogate content. + * @Deprecated Use PluginData getPluginData( String url, + * Map headers) instead. */ + @Deprecated public static synchronized CacheResult getSurrogate( String url, Map headers) { - if (urlInterceptDisabled()) + if (urlInterceptDisabled()) { return null; + } Iterator iter = getHandlers().listIterator(); while (iter.hasNext()) { UrlInterceptHandler handler = (UrlInterceptHandler) iter.next(); @@ -103,4 +108,27 @@ public final class UrlInterceptRegistry { } return null; } + + /** + * Given an url, returns the PluginData of the first + * UrlInterceptHandler interested, or null if none are or if + * intercepts are disabled. + * + * @return A PluginData instance containing surrogate content. + */ + public static synchronized PluginData getPluginData( + String url, Map headers) { + if (urlInterceptDisabled()) { + return null; + } + Iterator iter = getHandlers().listIterator(); + while (iter.hasNext()) { + UrlInterceptHandler handler = (UrlInterceptHandler) iter.next(); + PluginData data = handler.getPluginData(url, headers); + if (data != null) { + return data; + } + } + return null; + } } diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java index 308b6aa76f646465876f7b4cb1b2ecf18bc3d2e2..44f382cfc0d52dd3cb53f4c6a7a6f3a2e5e0eeff 100644 --- a/core/java/android/webkit/WebSettings.java +++ b/core/java/android/webkit/WebSettings.java @@ -20,6 +20,8 @@ import android.content.Context; import android.os.Build; import android.os.Handler; import android.os.Message; +import android.provider.Checkin; + import java.lang.SecurityException; import android.content.pm.PackageManager; @@ -136,7 +138,7 @@ public class WebSettings { private int mDefaultFixedFontSize = 13; private boolean mLoadsImagesAutomatically = true; private boolean mBlockNetworkImage = false; - private boolean mBlockNetworkLoads = false; + private boolean mBlockNetworkLoads; private boolean mJavaScriptEnabled = false; private boolean mPluginsEnabled = false; private boolean mJavaScriptCanOpenWindowsAutomatically = false; @@ -250,7 +252,9 @@ public class WebSettings { mUserAgent = getCurrentUserAgent(); mUseDefaultUserAgent = true; - verifyNetworkAccess(); + mBlockNetworkLoads = mContext.checkPermission( + "android.permission.INTERNET", android.os.Process.myPid(), + android.os.Process.myUid()) != PackageManager.PERMISSION_GRANTED; } /** @@ -320,10 +324,15 @@ public class WebSettings { buffer.append("en"); } - final String device = Build.DEVICE; - if (device.length() > 0) { + final String model = Build.MODEL; + if (model.length() > 0) { buffer.append("; "); - buffer.append(device); + buffer.append(model); + } + final String id = Build.ID; + if (id.length() > 0) { + buffer.append(" Build/"); + buffer.append(id); } final String base = mContext.getResources().getText( com.android.internal.R.string.web_user_agent).toString(); @@ -407,6 +416,10 @@ public class WebSettings { * @see WebSettings.TextSize */ public synchronized void setTextSize(TextSize t) { + if (WebView.mLogEvent && mTextSize != t ) { + Checkin.updateStats(mContext.getContentResolver(), + Checkin.Stats.Tag.BROWSER_TEXT_SIZE_CHANGE, 1, 0.0); + } mTextSize = t; postSync(); } @@ -827,7 +840,7 @@ public class WebSettings { private void verifyNetworkAccess() { if (!mBlockNetworkLoads) { if (mContext.checkPermission("android.permission.INTERNET", - android.os.Process.myPid(), 0) != + android.os.Process.myPid(), android.os.Process.myUid()) != PackageManager.PERMISSION_GRANTED) { throw new SecurityException ("Permission denied - " + diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java index c7ba498392f61dab00de2d0bd231474412993684..d4040404094df51036a85fe0951e64bee2d5706a 100644 --- a/core/java/android/webkit/WebView.java +++ b/core/java/android/webkit/WebView.java @@ -21,7 +21,6 @@ import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; -import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; @@ -38,13 +37,14 @@ import android.os.Handler; import android.os.Message; import android.os.ServiceManager; import android.os.SystemClock; +import android.provider.Checkin; import android.text.IClipboard; import android.text.Selection; import android.text.Spannable; import android.util.AttributeSet; import android.util.Config; +import android.util.EventLog; import android.util.Log; -import android.view.animation.AlphaAnimation; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; @@ -64,10 +64,9 @@ import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; -import android.widget.RelativeLayout; import android.widget.Scroller; import android.widget.Toast; -import android.widget.ZoomControls; +import android.widget.ZoomButtonsController; import android.widget.AdapterView.OnItemClickListener; import java.io.File; @@ -207,60 +206,6 @@ public class WebView extends AbsoluteLayout static final boolean DEBUG = false; static final boolean LOGV_ENABLED = DEBUG ? Config.LOGD : Config.LOGV; - private class ExtendedZoomControls extends RelativeLayout { - public ExtendedZoomControls(Context context, AttributeSet attrs) { - super(context, attrs); - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - inflater.inflate(com.android.internal.R.layout.zoom_magnify, this - , true); - mZoomControls = (ZoomControls) findViewById - (com.android.internal.R.id.zoomControls); - mZoomMagnify = (ImageView) findViewById - (com.android.internal.R.id.zoomMagnify); - } - - public void show(boolean showZoom, boolean canZoomOut) { - mZoomControls.setVisibility(showZoom ? View.VISIBLE : View.GONE); - mZoomMagnify.setVisibility(canZoomOut ? View.VISIBLE : View.GONE); - fade(View.VISIBLE, 0.0f, 1.0f); - } - - public void hide() { - fade(View.GONE, 1.0f, 0.0f); - } - - private void fade(int visibility, float startAlpha, float endAlpha) { - AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha); - anim.setDuration(500); - startAnimation(anim); - setVisibility(visibility); - } - - public void setIsZoomMagnifyEnabled(boolean isEnabled) { - mZoomMagnify.setEnabled(isEnabled); - } - - public boolean hasFocus() { - return mZoomControls.hasFocus() || mZoomMagnify.hasFocus(); - } - - public void setOnZoomInClickListener(OnClickListener listener) { - mZoomControls.setOnZoomInClickListener(listener); - } - - public void setOnZoomOutClickListener(OnClickListener listener) { - mZoomControls.setOnZoomOutClickListener(listener); - } - - public void setOnZoomMagnifyClickListener(OnClickListener listener) { - mZoomMagnify.setOnClickListener(listener); - } - - ZoomControls mZoomControls; - ImageView mZoomMagnify; - } - /** * Transportation object for returning WebView across thread boundaries. */ @@ -358,6 +303,11 @@ public class WebView extends AbsoluteLayout // Whether to forward the touch events to WebCore private boolean mForwardTouchEvents = false; + // Whether to prevent drag during touch. The initial value depends on + // mForwardTouchEvents. If WebCore wants touch events, we assume it will + // take control of touch events unless it says no for touch down event. + private boolean mPreventDrag; + // If updateTextEntry gets called while we are out of focus, use this // variable to remember to do it next time we gain focus. private boolean mNeedsUpdateTextEntry = false; @@ -368,26 +318,20 @@ public class WebView extends AbsoluteLayout /** * Customizable constant */ - // pre-computed square of ViewConfiguration.getTouchSlop() - private static final int TOUCH_SLOP_SQUARE = - ViewConfiguration.getTouchSlop() * ViewConfiguration.getTouchSlop(); + // pre-computed square of ViewConfiguration.getScaledTouchSlop() + private int mTouchSlopSquare; + // pre-computed density adjusted navigation slop + private int mNavSlop; // This should be ViewConfiguration.getTapTimeout() // But system time out is 100ms, which is too short for the browser. // In the browser, if it switches out of tap too soon, jump tap won't work. private static final int TAP_TIMEOUT = 200; - // The duration in milliseconds we will wait to see if it is a double tap. - // With a limited survey, the time between the first tap up and the second - // tap down in the double tap case is around 70ms - 120ms. - private static final int DOUBLE_TAP_TIMEOUT = 200; // This should be ViewConfiguration.getLongPressTimeout() // But system time out is 500ms, which is too short for the browser. // With a short timeout, it's difficult to treat trigger a short press. private static final int LONG_PRESS_TIMEOUT = 1000; // needed to avoid flinging after a pause of no movement private static final int MIN_FLING_TIME = 250; - // The time that the Zoom Controls are visible before fading away - private static final long ZOOM_CONTROLS_TIMEOUT = - ViewConfiguration.getZoomControlsTimeout(); // The amount of content to overlap between two screens when going through // pages with the space bar, in pixels. private static final int PAGE_SCROLL_OVERLAP = 24; @@ -422,10 +366,6 @@ public class WebView extends AbsoluteLayout private boolean mWrapContent; - // The View containing the zoom controls - private ExtendedZoomControls mZoomControls; - private Runnable mZoomControlRunnable; - // true if we should call webcore to draw the content, false means we have // requested something but it isn't ready to draw yet. private WebViewCore.FocusData mFocusData; @@ -436,7 +376,6 @@ public class WebView extends AbsoluteLayout private static final int NEVER_REMEMBER_PASSWORD = 2; private static final int SWITCH_TO_SHORTPRESS = 3; private static final int SWITCH_TO_LONGPRESS = 4; - private static final int RELEASE_SINGLE_TAP = 5; private static final int UPDATE_TEXT_ENTRY_ADAPTER = 6; private static final int SWITCH_TO_ENTER = 7; private static final int RESUME_WEBCORE_UPDATE = 8; @@ -460,19 +399,54 @@ public class WebView extends AbsoluteLayout static final int LONG_PRESS_ENTER = 23; static final int PREVENT_TOUCH_ID = 24; static final int WEBCORE_NEED_TOUCH_EVENTS = 25; + // obj=Rect in doc coordinates + static final int INVAL_RECT_MSG_ID = 26; + + static final String[] HandlerDebugString = { + "REMEMBER_PASSWORD", // = 1; + "NEVER_REMEMBER_PASSWORD", // = 2; + "SWITCH_TO_SHORTPRESS", // = 3; + "SWITCH_TO_LONGPRESS", // = 4; + "5", + "UPDATE_TEXT_ENTRY_ADAPTER", // = 6; + "SWITCH_TO_ENTER", // = 7; + "RESUME_WEBCORE_UPDATE", // = 8; + "9", + "SCROLL_TO_MSG_ID", // = 10; + "SCROLL_BY_MSG_ID", // = 11; + "SPAWN_SCROLL_TO_MSG_ID", // = 12; + "SYNC_SCROLL_TO_MSG_ID", // = 13; + "NEW_PICTURE_MSG_ID", // = 14; + "UPDATE_TEXT_ENTRY_MSG_ID", // = 15; + "WEBCORE_INITIALIZED_MSG_ID", // = 16; + "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 17; + "DID_FIRST_LAYOUT_MSG_ID", // = 18; + "RECOMPUTE_FOCUS_MSG_ID", // = 19; + "NOTIFY_FOCUS_SET_MSG_ID", // = 20; + "MARK_NODE_INVALID_ID", // = 21; + "UPDATE_CLIPBOARD", // = 22; + "LONG_PRESS_ENTER", // = 23; + "PREVENT_TOUCH_ID", // = 24; + "WEBCORE_NEED_TOUCH_EVENTS", // = 25; + "INVAL_RECT_MSG_ID" // = 26; + }; // width which view is considered to be fully zoomed out - static final int ZOOM_OUT_WIDTH = 1024; + static final int ZOOM_OUT_WIDTH = 1008; - private static final float DEFAULT_MAX_ZOOM_SCALE = 4; + private static final float DEFAULT_MAX_ZOOM_SCALE = 4.0f; private static final float DEFAULT_MIN_ZOOM_SCALE = 0.25f; // scale limit, which can be set through viewport meta tag in the web page private float mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; private float mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; + private boolean mMinZoomScaleFixed = false; // initial scale in percent. 0 means using default. private int mInitialScale = 0; + // set to true temporarily while the zoom control is being dragged + private boolean mPreviewZoomOnly = false; + // computed scale and inverse, from mZoomWidth. private float mActualScale = 1; private float mInvActualScale = 1; @@ -496,6 +470,13 @@ public class WebView extends AbsoluteLayout // Used to match key downs and key ups private boolean mGotKeyDown; + /* package */ static boolean mLogEvent = true; + private static final int EVENT_LOG_ZOOM_LEVEL_CHANGE = 70101; + private static final int EVENT_LOG_DOUBLE_TAP_DURATION = 70102; + + // for event log + private long mLastTouchUpTime = 0; + /** * URI scheme for telephone number */ @@ -591,6 +572,41 @@ public class WebView extends AbsoluteLayout } } + private ZoomButtonsController mZoomButtonsController; + private ImageView mZoomOverviewButton; + private ImageView mZoomFitPageButton; + + // These keep track of the center point of the zoom. They are used to + // determine the point around which we should zoom. + private float mZoomCenterX; + private float mZoomCenterY; + + private ZoomButtonsController.OnZoomListener mZoomListener = + new ZoomButtonsController.OnZoomListener() { + + public void onCenter(int x, int y) { + // Don't translate when the control is invoked, hence we do nothing + // in this callback + } + + public void onVisibilityChanged(boolean visible) { + if (visible) { + switchOutDrawHistory(); + updateZoomButtonsEnabled(); + } + } + + public void onZoom(boolean zoomIn) { + if (zoomIn) { + zoomIn(); + } else { + zoomOut(); + } + + updateZoomButtonsEnabled(); + } + }; + /** * Construct a new WebView with a Context object. * @param context A Context object used to access application assets. @@ -618,11 +634,6 @@ public class WebView extends AbsoluteLayout super(context, attrs, defStyle); init(); - TypedArray a = context.obtainStyledAttributes( - com.android.internal.R.styleable.View); - initializeScrollbars(a); - a.recycle(); - mCallbackProxy = new CallbackProxy(context, this); mWebViewCore = new WebViewCore(context, this, mCallbackProxy); mDatabase = WebViewDatabase.getInstance(context); @@ -632,6 +643,49 @@ public class WebView extends AbsoluteLayout mFocusData.mX = 0; mFocusData.mY = 0; mScroller = new Scroller(context); + + initZoomController(context); + } + + private void initZoomController(Context context) { + // Create the buttons controller + mZoomButtonsController = new ZoomButtonsController(this); + mZoomButtonsController.setOnZoomListener(mZoomListener); + + // Create the accessory buttons + LayoutInflater inflater = + (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + ViewGroup container = mZoomButtonsController.getContainer(); + inflater.inflate(com.android.internal.R.layout.zoom_browser_accessory_buttons, container); + mZoomOverviewButton = + (ImageView) container.findViewById(com.android.internal.R.id.zoom_page_overview); + mZoomOverviewButton.setOnClickListener( + new View.OnClickListener() { + public void onClick(View v) { + mZoomButtonsController.setVisible(false); + zoomScrollOut(); + if (mLogEvent) { + Checkin.updateStats(mContext.getContentResolver(), + Checkin.Stats.Tag.BROWSER_ZOOM_OVERVIEW, 1, 0.0); + } + } + }); + mZoomFitPageButton = + (ImageView) container.findViewById(com.android.internal.R.id.zoom_fit_page); + mZoomFitPageButton.setOnClickListener( + new View.OnClickListener() { + public void onClick(View v) { + zoomWithPreview(1f); + updateZoomButtonsEnabled(); + } + }); + } + + private void updateZoomButtonsEnabled() { + mZoomButtonsController.setZoomInEnabled(mActualScale < mMaxZoomScale); + mZoomButtonsController.setZoomOutEnabled(mActualScale > mMinZoomScale); + mZoomFitPageButton.setEnabled(mActualScale != 1); + mZoomOverviewButton.setEnabled(canZoomScrollOut()); } private void init() { @@ -641,9 +695,13 @@ public class WebView extends AbsoluteLayout setClickable(true); setLongClickable(true); - // should be conditional on if we're in the browser activity? - setHorizontalScrollBarEnabled(true); - setVerticalScrollBarEnabled(true); + final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); + mTouchSlopSquare = slop * slop; + mMinLockSnapReverseDistance = slop; + // use one line height, 16 based on our current default font, for how + // far we allow a touch be away from the edge of a link + mNavSlop = (int) (16 * getContext().getResources() + .getDisplayMetrics().density); } /* package */ boolean onSavePassword(String schemePlusHost, String username, @@ -748,7 +806,7 @@ public class WebView extends AbsoluteLayout * to. */ private int getViewWidth() { - if (mOverlayVerticalScrollbar) { + if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { return getWidth(); } else { return getWidth() - getVerticalScrollbarWidth(); @@ -760,7 +818,7 @@ public class WebView extends AbsoluteLayout * to. */ private int getViewHeight() { - if (mOverlayHorizontalScrollbar) { + if (!isHorizontalScrollBarEnabled() || mOverlayHorizontalScrollbar) { return getHeight(); } else { return getHeight() - getHorizontalScrollbarHeight(); @@ -832,7 +890,6 @@ public class WebView extends AbsoluteLayout */ public void destroy() { clearTextEntry(); - getViewTreeObserver().removeOnGlobalFocusChangeListener(this); if (mWebViewCore != null) { // Set the handlers to null before destroying WebViewCore so no // more messages will be posted. @@ -1265,7 +1322,7 @@ public class WebView extends AbsoluteLayout nativeClearFocus(-1, -1); if (top) { // go to the top of the document - return pinScrollTo(mScrollX, 0, true); + return pinScrollTo(mScrollX, 0, true, 0); } // Page up int h = getHeight(); @@ -1276,7 +1333,7 @@ public class WebView extends AbsoluteLayout y = -h / 2; } mUserScroll = true; - return mScroller.isFinished() ? pinScrollBy(0, y, true) + return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) : extendScroll(y); } @@ -1291,7 +1348,7 @@ public class WebView extends AbsoluteLayout } nativeClearFocus(-1, -1); if (bottom) { - return pinScrollTo(mScrollX, mContentHeight, true); + return pinScrollTo(mScrollX, mContentHeight, true, 0); } // Page down. int h = getHeight(); @@ -1302,7 +1359,7 @@ public class WebView extends AbsoluteLayout y = h / 2; } mUserScroll = true; - return mScroller.isFinished() ? pinScrollBy(0, y, true) + return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) : extendScroll(y); } @@ -1375,13 +1432,7 @@ public class WebView extends AbsoluteLayout return; } clearTextEntry(); - ExtendedZoomControls zoomControls = (ExtendedZoomControls) - getZoomControls(); - zoomControls.show(true, canZoomScrollOut()); - zoomControls.requestFocus(); - mPrivateHandler.removeCallbacks(mZoomControlRunnable); - mPrivateHandler.postDelayed(mZoomControlRunnable, - ZOOM_CONTROLS_TIMEOUT); + mZoomButtonsController.setVisible(true); } /** @@ -1493,7 +1544,8 @@ public class WebView extends AbsoluteLayout private static int pinLoc(int x, int viewMax, int docMax) { // Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax); if (docMax < viewMax) { // the doc has room on the sides for "blank" - x = -(viewMax - docMax) >> 1; + // pin the short document to the top/left of the screen + x = 0; // Log.d(LOGTAG, "--- center " + x); } else if (x < 0) { x = 0; @@ -1585,12 +1637,14 @@ public class WebView extends AbsoluteLayout if (mDrawHistory) { // If history Picture is drawn, don't update scroll. They will // be updated when we get out of that mode. - if (scale != mActualScale) { + if (scale != mActualScale && !mPreviewZoomOnly) { mCallbackProxy.onScaleChanged(mActualScale, scale); } mActualScale = scale; mInvActualScale = 1 / scale; - sendViewSizeZoom(); + if (!mPreviewZoomOnly) { + sendViewSizeZoom(); + } } else { // update our scroll so we don't appear to jump // i.e. keep the center of the doc in the center of the view @@ -1598,11 +1652,11 @@ public class WebView extends AbsoluteLayout int oldX = mScrollX; int oldY = mScrollY; float ratio = scale * mInvActualScale; // old inverse - float sx = ratio * oldX + (ratio - 1) * getViewWidth() * 0.5f; - float sy = ratio * oldY + (ratio - 1) * getViewHeight() * 0.5f; + float sx = ratio * oldX + (ratio - 1) * mZoomCenterX; + float sy = ratio * oldY + (ratio - 1) * mZoomCenterY; // now update our new scale and inverse - if (scale != mActualScale) { + if (scale != mActualScale && !mPreviewZoomOnly) { mCallbackProxy.onScaleChanged(mActualScale, scale); } mActualScale = scale; @@ -1614,8 +1668,10 @@ public class WebView extends AbsoluteLayout mScrollX = pinLocX(Math.round(sx)); mScrollY = pinLocY(Math.round(sy)); - sendViewSizeZoom(); - sendOurVisibleRect(); + if (!mPreviewZoomOnly) { + sendViewSizeZoom(); + sendOurVisibleRect(); + } } } } @@ -1817,8 +1873,8 @@ public class WebView extends AbsoluteLayout */ public void clearFormData() { if (inEditingMode()) { - ArrayAdapter adapter = null; - mTextEntry.setAdapter(adapter); + AutoCompleteAdapter adapter = null; + mTextEntry.setAdapterCustom(adapter); } } @@ -1913,7 +1969,7 @@ public class WebView extends AbsoluteLayout nativeSetFindIsDown(); // Now that the dialog has been removed, ensure that we scroll to a // location that is not beyond the end of the page. - pinScrollTo(mScrollX, mScrollY, false); + pinScrollTo(mScrollX, mScrollY, false, 0); invalidate(); } @@ -1956,13 +2012,13 @@ public class WebView extends AbsoluteLayout // helper to pin the scrollBy parameters (already in view coordinates) // returns true if the scroll was changed - private boolean pinScrollBy(int dx, int dy, boolean animate) { - return pinScrollTo(mScrollX + dx, mScrollY + dy, animate); + private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { + return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); } // helper to pin the scrollTo parameters (already in view coordinates) // returns true if the scroll was changed - private boolean pinScrollTo(int x, int y, boolean animate) { + private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { x = pinLocX(x); y = pinLocY(y); int dx = x - mScrollX; @@ -1976,7 +2032,7 @@ public class WebView extends AbsoluteLayout // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); mScroller.startScroll(mScrollX, mScrollY, dx, dy, - computeDuration(dx, dy)); + animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); invalidate(); } else { mScroller.abortAnimation(); // just in case @@ -1987,7 +2043,7 @@ public class WebView extends AbsoluteLayout // Scale from content to view coordinates, and pin. // Also called by jni webview.cpp - private void setContentScrollBy(int cx, int cy) { + private void setContentScrollBy(int cx, int cy, boolean animate) { if (mDrawHistory) { // disallow WebView to change the scroll position as History Picture // is used in the view system. @@ -2011,10 +2067,10 @@ public class WebView extends AbsoluteLayout // vertical scroll? // Log.d(LOGTAG, "setContentScrollBy cy=" + cy); if (cy == 0 && cx != 0) { - pinScrollBy(cx, 0, true); + pinScrollBy(cx, 0, animate, 0); } } else { - pinScrollBy(cx, cy, true); + pinScrollBy(cx, cy, animate, 0); } } @@ -2034,7 +2090,7 @@ public class WebView extends AbsoluteLayout int vy = contentToView(cy); // Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + // vx + " " + vy + "]"); - pinScrollTo(vx, vy, false); + pinScrollTo(vx, vy, false, 0); if (mScrollX != vx || mScrollY != vy) { return true; } else { @@ -2051,7 +2107,7 @@ public class WebView extends AbsoluteLayout } int vx = contentToView(cx); int vy = contentToView(cy); - pinScrollTo(vx, vy, true); + pinScrollTo(vx, vy, true, 0); } /** @@ -2140,8 +2196,19 @@ public class WebView extends AbsoluteLayout /** * Use this function to bind an object to Javascript so that the * methods can be accessed from Javascript. - * IMPORTANT, the object that is bound runs in another thread and - * not in the thread that it was constructed in. + *

          IMPORTANT: + *

            + *
          • Using addJavascriptInterface() allows JavaScript to control your + * application. This can be a very useful feature or a dangerous security + * issue. When the HTML in the WebView is untrustworthy (for example, part + * or all of the HTML is provided by some person or process), then an + * attacker could inject HTML that will execute your code and possibly any + * code of the attacker's choosing.
            + * Do not use addJavascriptInterface() unless all of the HTML in this + * WebView was written by you.
          • + *
          • The Java object that is bound runs in another thread and not in + * the thread that it was constructed in.
          • + *

          * @param obj The class instance to bind to Javascript * @param interfaceName The name to used to expose the class in Javascript */ @@ -2224,7 +2291,8 @@ public class WebView extends AbsoluteLayout // state. // If mNativeClass is 0, we should not reach here, so we do not // need to check it again. - nativeRecordButtons(mTouchMode == TOUCH_SHORTPRESS_START_MODE + nativeRecordButtons(hasFocus() && hasWindowFocus(), + mTouchMode == TOUCH_SHORTPRESS_START_MODE || mTrackballDown || mGotEnterDown, false); drawCoreAndFocusRing(canvas, mBackgroundColor, mDrawFocusRing); } @@ -2273,10 +2341,12 @@ public class WebView extends AbsoluteLayout invalidate(); } else { zoomScale = mZoomScale; + // set mZoomScale to be 0 as we have done animation + mZoomScale = 0; } float scale = (mActualScale - zoomScale) * mInvActualScale; - float tx = scale * ((getLeft() + getRight()) * 0.5f + mScrollX); - float ty = scale * ((getTop() + getBottom()) * 0.5f + mScrollY); + float tx = scale * (mZoomCenterX + mScrollX); + float ty = scale * (mZoomCenterY + mScrollY); // this block pins the translate to "legal" bounds. This makes the // animation a bit non-obvious, but it means we won't pop when the @@ -2566,11 +2636,8 @@ public class WebView extends AbsoluteLayout private void startZoomScrollOut() { setHorizontalScrollBarEnabled(false); setVerticalScrollBarEnabled(false); - if (mZoomControlRunnable != null) { - mPrivateHandler.removeCallbacks(mZoomControlRunnable); - } - if (mZoomControls != null) { - mZoomControls.hide(); + if (mZoomButtonsController.isVisible()) { + mZoomButtonsController.setVisible(false); } int width = getViewWidth(); int height = getViewHeight(); @@ -2773,6 +2840,7 @@ public class WebView extends AbsoluteLayout * @param end End of selection to delete. */ /* package */ void deleteSelection(int start, int end) { + mTextGeneration++; mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, start, end, new WebViewCore.FocusData(mFocusData)); } @@ -2793,12 +2861,20 @@ public class WebView extends AbsoluteLayout InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mTextEntry, 0); + mTextEntry.enableScrollOnScreen(true); + // Now we need to fake a touch event to place the cursor where the + // user touched. + AbsoluteLayout.LayoutParams lp = (AbsoluteLayout.LayoutParams) + mTextEntry.getLayoutParams(); + if (lp != null) { + // Take the last touch and adjust for the location of the + // TextDialog. + float x = mLastTouchX + (float) (mScrollX - lp.x); + float y = mLastTouchY + (float) (mScrollY - lp.y); + mTextEntry.fakeTouchEvent(x, y); + } } - // Used to register the global focus change listener one time to avoid - // multiple references to WebView - private boolean mGlobalFocusChangeListenerAdded; - private void updateTextEntry() { if (mTextEntry == null) { mTextEntry = new TextDialog(mContext, WebView.this); @@ -2831,9 +2907,6 @@ public class WebView extends AbsoluteLayout // Note that sendOurVisibleRect calls viewToContent, so the coordinates // should be in content coordinates. if (!Rect.intersects(node.mBounds, visibleRect)) { - if (alreadyThere) { - mTextEntry.remove(); - } // Node is not on screen, so do not bother. return; } @@ -2886,21 +2959,32 @@ public class WebView extends AbsoluteLayout } } mTextEntry.setMaxLength(maxLength); - ArrayAdapter adapter = null; - mTextEntry.setAdapter(adapter); - mTextEntry.setInPassword(node.mIsPassword); + AutoCompleteAdapter adapter = null; + mTextEntry.setAdapterCustom(adapter); mTextEntry.setSingleLine(node.mIsTextField); + mTextEntry.setInPassword(node.mIsPassword); if (null == text) { mTextEntry.setText("", 0, 0); } else { - mTextEntry.setText(text, 0, text.length()); + // Change to true to enable the old style behavior, where + // entering a textfield/textarea always set the selection to the + // whole field. This was desirable for the case where the user + // intends to scroll past the field using the trackball. + // However, it causes a problem when replying to emails - the + // user expects the cursor to be at the beginning of the + // textarea. Testing out a new behavior, where textfields set + // selection at the end, and textareas at the beginning. + if (false) { + mTextEntry.setText(text, 0, text.length()); + } else if (node.mIsTextField) { + int length = text.length(); + mTextEntry.setText(text, length, length); + } else { + mTextEntry.setText(text, 0, 0); + } } mTextEntry.requestFocus(); } - if (!mGlobalFocusChangeListenerAdded) { - getViewTreeObserver().addOnGlobalFocusChangeListener(this); - mGlobalFocusChangeListenerAdded = true; - } } private class UpdateTextEntryAdapter implements Runnable { @@ -2980,6 +3064,9 @@ public class WebView extends AbsoluteLayout mSelectX = mScrollX + (int) mLastTouchX; mSelectY = mScrollY + (int) mLastTouchY; } + int contentX = viewToContent((int) mLastTouchX + mScrollX); + int contentY = viewToContent((int) mLastTouchY + mScrollY); + nativeClearFocus(contentX, contentY); } if (keyCode >= KeyEvent.KEYCODE_DPAD_UP @@ -3001,7 +3088,9 @@ public class WebView extends AbsoluteLayout mGotEnterDown = true; mPrivateHandler.sendMessageDelayed(mPrivateHandler .obtainMessage(LONG_PRESS_ENTER), LONG_PRESS_TIMEOUT); - nativeRecordButtons(true, true); + // Already checked mNativeClass, so we do not need to check it + // again. + nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); return true; } // Bubble up the key event as WebView doesn't handle it @@ -3031,8 +3120,8 @@ public class WebView extends AbsoluteLayout (keyCode == KeyEvent.KEYCODE_7) ? 1 : 0, 0); break; case KeyEvent.KEYCODE_9: - debugDump(); - break; + nativeInstrumentReport(); + return true; } } @@ -3167,7 +3256,11 @@ public class WebView extends AbsoluteLayout * @hide */ public void emulateShiftHeld() { + mExtendSelection = false; mShiftIsPressed = true; + int contentX = viewToContent((int) mLastTouchX + mScrollX); + int contentY = viewToContent((int) mLastTouchY + mScrollY); + nativeClearFocus(contentX, contentY); } private boolean commitCopy() { @@ -3182,6 +3275,7 @@ public class WebView extends AbsoluteLayout mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection); copiedSomething = true; } + mExtendSelection = false; } mShiftIsPressed = false; if (mTouchMode == TOUCH_SELECT_MODE) { @@ -3210,29 +3304,31 @@ public class WebView extends AbsoluteLayout ViewGroup p = (ViewGroup) parent; p.setOnHierarchyChangeListener(null); } + + // Clean up the zoom controller + mZoomButtonsController.setVisible(false); + ZoomButtonsController.finishZoomTutorial(mContext, false); } // Implementation for OnHierarchyChangeListener public void onChildViewAdded(View parent, View child) {} - // When we are removed, remove this as a global focus change listener. public void onChildViewRemoved(View p, View child) { if (child == this) { - p.getViewTreeObserver().removeOnGlobalFocusChangeListener(this); - mGlobalFocusChangeListenerAdded = false; + if (inEditingMode()) { + clearTextEntry(); + mNeedsUpdateTextEntry = true; + } } } - - // Use this to know when the textview has lost focus, and something other - // than the webview has gained focus. Stop drawing the focus ring, remove - // the TextView, and set a flag to put it back when we regain focus. + + /** + * @deprecated WebView should not have implemented + * ViewTreeObserver.OnGlobalFocusChangeListener. This method + * does nothing now. + */ + @Deprecated public void onGlobalFocusChanged(View oldFocus, View newFocus) { - if (oldFocus == mTextEntry && newFocus != this) { - mDrawFocusRing = false; - mTextEntry.updateCachedTextfield(); - removeView(mTextEntry); - mNeedsUpdateTextEntry = true; - } } // To avoid drawing the focus ring, and remove the TextView when our window @@ -3248,21 +3344,33 @@ public class WebView extends AbsoluteLayout if (mNeedsUpdateTextEntry) { updateTextEntry(); } + if (mNativeClass != 0) { + nativeRecordButtons(true, false, true); + } } else { // If our window gained focus, but we do not have it, do not // draw the focus ring. mDrawFocusRing = false; + // We do not call nativeRecordButtons here because we assume + // that when we lost focus, or window focus, it got called with + // false for the first parameter } } else { - // If our window has lost focus, stop drawing the focus ring, and - // remove the TextView if displayed, and flag it to be added when - // we regain focus. - mDrawFocusRing = false; + if (!mZoomButtonsController.isVisible()) { + /* + * The zoom controls come in their own window, so our window + * loses focus. Our policy is to not draw the focus ring if + * our window is not focused, but this is an exception since + * the user can still navigate the web page with the zoom + * controls showing. + */ + // If our window has lost focus, stop drawing the focus ring + mDrawFocusRing = false; + } mGotKeyDown = false; mShiftIsPressed = false; - if (inEditingMode()) { - clearTextEntry(); - mNeedsUpdateTextEntry = true; + if (mNativeClass != 0) { + nativeRecordButtons(false, false, true); } } invalidate(); @@ -3284,12 +3392,22 @@ public class WebView extends AbsoluteLayout updateTextEntry(); mNeedsUpdateTextEntry = false; } + if (mNativeClass != 0) { + nativeRecordButtons(true, false, true); + } + //} else { + // The WebView has gained focus while we do not have + // windowfocus. When our window lost focus, we should have + // called nativeRecordButtons(false...) } } else { // When we lost focus, unless focus went to the TextView (which is // true if we are in editing mode), stop drawing the focus ring. if (!inEditingMode()) { mDrawFocusRing = false; + if (mNativeClass != 0) { + nativeRecordButtons(false, false, true); + } } mGotKeyDown = false; } @@ -3300,6 +3418,15 @@ public class WebView extends AbsoluteLayout @Override protected void onSizeChanged(int w, int h, int ow, int oh) { super.onSizeChanged(w, h, ow, oh); + // Center zooming to the center of the screen. + mZoomCenterX = getViewWidth() * .5f; + mZoomCenterY = getViewHeight() * .5f; + + // update mMinZoomScale if the minimum zoom scale is not fixed + if (!mMinZoomScaleFixed) { + mMinZoomScale = (float) getViewWidth() + / Math.max(ZOOM_OUT_WIDTH, mContentWidth); + } // we always force, in case our height changed, in which case we still // want to send the notification over to webkit @@ -3346,9 +3473,8 @@ public class WebView extends AbsoluteLayout // 3. If there is a same direction back and forth, lock it. // adjustable parameters + private int mMinLockSnapReverseDistance; private static final float MAX_SLOPE_FOR_DIAG = 1.5f; - private static final int MIN_LOCK_SNAP_REVERSE_DISTANCE = - ViewConfiguration.getTouchSlop(); private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; @Override @@ -3387,11 +3513,14 @@ public class WebView extends AbsoluteLayout WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData(); ted.mAction = action; ted.mX = viewToContent((int) x + mScrollX); - ted.mY = viewToContent((int) y + mScrollY);; + ted.mY = viewToContent((int) y + mScrollY); mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); mLastSentTouchTime = eventTime; } + int deltaX = (int) (mLastTouchX - x); + int deltaY = (int) (mLastTouchY - y); + switch (action) { case MotionEvent.ACTION_DOWN: { if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN @@ -3418,7 +3547,13 @@ public class WebView extends AbsoluteLayout mTouchSelection = mExtendSelection = true; } else { mTouchMode = TOUCH_INIT_MODE; + mPreventDrag = mForwardTouchEvents; + if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { + EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION, + (eventTime - mLastTouchUpTime), eventTime); + } } + // Trigger the link if (mTouchMode == TOUCH_INIT_MODE) { mPrivateHandler.sendMessageDelayed(mPrivateHandler .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT); @@ -3445,9 +3580,6 @@ public class WebView extends AbsoluteLayout } mVelocityTracker.addMovement(ev); - int deltaX = (int) (mLastTouchX - x); - int deltaY = (int) (mLastTouchY - y); - if (mTouchMode != TOUCH_DRAG_MODE) { if (mTouchMode == TOUCH_SELECT_MODE) { mSelectX = mScrollX + (int) x; @@ -3460,8 +3592,8 @@ public class WebView extends AbsoluteLayout invalidate(); break; } - if ((deltaX * deltaX + deltaY * deltaY) - < TOUCH_SLOP_SQUARE) { + if (mPreventDrag || (deltaX * deltaX + deltaY * deltaY) + < mTouchSlopSquare) { break; } @@ -3496,6 +3628,12 @@ public class WebView extends AbsoluteLayout mWebViewCore .sendMessage(EventHub.SET_SNAP_ANCHOR, 0, 0); } + if (getSettings().supportZoom() + && !mZoomButtonsController.isVisible() + && (canZoomScrollOut() || + mMinZoomScale < mMaxZoomScale)) { + mZoomButtonsController.setVisible(true); + } } // do pan @@ -3519,9 +3657,9 @@ public class WebView extends AbsoluteLayout // reverse direction means lock in the snap mode if ((ax > MAX_SLOPE_FOR_DIAG * ay) && ((mSnapPositive && - deltaX < -MIN_LOCK_SNAP_REVERSE_DISTANCE) + deltaX < -mMinLockSnapReverseDistance) || (!mSnapPositive && - deltaX > MIN_LOCK_SNAP_REVERSE_DISTANCE))) { + deltaX > mMinLockSnapReverseDistance))) { mSnapScrollMode = SNAP_X_LOCK; } } else { @@ -3533,9 +3671,9 @@ public class WebView extends AbsoluteLayout // reverse direction means lock in the snap mode if ((ay > MAX_SLOPE_FOR_DIAG * ax) && ((mSnapPositive && - deltaY < -MIN_LOCK_SNAP_REVERSE_DISTANCE) + deltaY < -mMinLockSnapReverseDistance) || (!mSnapPositive && - deltaY > MIN_LOCK_SNAP_REVERSE_DISTANCE))) { + deltaY > mMinLockSnapReverseDistance))) { mSnapScrollMode = SNAP_Y_LOCK; } } @@ -3557,18 +3695,6 @@ public class WebView extends AbsoluteLayout mLastTouchTime = eventTime; mUserScroll = true; } - - boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; - boolean showMagnify = canZoomScrollOut(); - if (mZoomControls != null && (showPlusMinus || showMagnify)) { - if (mZoomControls.getVisibility() == View.VISIBLE) { - mPrivateHandler.removeCallbacks(mZoomControlRunnable); - } else { - mZoomControls.show(showPlusMinus, showMagnify); - } - mPrivateHandler.postDelayed(mZoomControlRunnable, - ZOOM_CONTROLS_TIMEOUT); - } if (done) { // return false to indicate that we can't pan out of the // view space @@ -3577,22 +3703,19 @@ public class WebView extends AbsoluteLayout break; } case MotionEvent.ACTION_UP: { + mLastTouchUpTime = eventTime; switch (mTouchMode) { case TOUCH_INIT_MODE: // tap + case TOUCH_SHORTPRESS_START_MODE: + case TOUCH_SHORTPRESS_MODE: mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); - if (getSettings().supportZoom()) { - mPrivateHandler.sendMessageDelayed(mPrivateHandler - .obtainMessage(RELEASE_SINGLE_TAP), - DOUBLE_TAP_TIMEOUT); - } else { - // do short press now - mTouchMode = TOUCH_DONE_MODE; - doShortPress(); - } + mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); + mTouchMode = TOUCH_DONE_MODE; + doShortPress(); break; case TOUCH_SELECT_MODE: commitCopy(); - mTouchSelection = mExtendSelection = false; + mTouchSelection = false; break; case SCROLL_ZOOM_ANIMATION_IN: case SCROLL_ZOOM_ANIMATION_OUT: @@ -3616,28 +3739,6 @@ public class WebView extends AbsoluteLayout invalidate(); } break; - case TOUCH_SHORTPRESS_START_MODE: - case TOUCH_SHORTPRESS_MODE: { - mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); - if (eventTime - mLastTouchTime < TAP_TIMEOUT - && getSettings().supportZoom()) { - // Note: window manager will not release ACTION_UP - // until all the previous action events are - // returned. If GC happens, it can cause - // SWITCH_TO_SHORTPRESS message fired before - // ACTION_UP sent even time stamp of ACTION_UP is - // less than the tap time out. We need to treat this - // as tap instead of short press. - mTouchMode = TOUCH_INIT_MODE; - mPrivateHandler.sendMessageDelayed(mPrivateHandler - .obtainMessage(RELEASE_SINGLE_TAP), - DOUBLE_TAP_TIMEOUT); - } else { - mTouchMode = TOUCH_DONE_MODE; - doShortPress(); - } - break; - } case TOUCH_DRAG_MODE: // if the user waits a while w/o moving before the // up, we don't want to do a fling @@ -3678,7 +3779,6 @@ public class WebView extends AbsoluteLayout } mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); - mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); mTouchMode = TOUCH_DONE_MODE; int contentX = viewToContent((int) mLastTouchX + mScrollX); int contentY = viewToContent((int) mLastTouchY + mScrollY); @@ -3705,6 +3805,7 @@ public class WebView extends AbsoluteLayout private static final int TRACKBALL_WAIT = 100; private static final int TRACKBALL_SCALE = 400; private static final int TRACKBALL_SCROLL_COUNT = 5; + private static final int TRACKBALL_MOVE_COUNT = 10; private static final int TRACKBALL_MULTIPLIER = 3; private static final int SELECT_CURSOR_OFFSET = 16; private int mSelectX = 0; @@ -3740,7 +3841,7 @@ public class WebView extends AbsoluteLayout mPrivateHandler.removeMessages(SWITCH_TO_ENTER); mTrackballDown = true; if (mNativeClass != 0) { - nativeRecordButtons(true, true); + nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); } if (time - mLastFocusTime <= TRACKBALL_TIMEOUT && !mLastFocusBounds.equals(nativeGetFocusRingBounds())) { @@ -3751,6 +3852,7 @@ public class WebView extends AbsoluteLayout + " time=" + time + " mLastFocusTime=" + mLastFocusTime); } + if (isInTouchMode()) requestFocusFromTouch(); return false; // let common code in onKeyDown at it } if (ev.getAction() == MotionEvent.ACTION_UP) { @@ -3759,7 +3861,11 @@ public class WebView extends AbsoluteLayout mTrackballDown = false; mTrackballUpTime = time; if (mShiftIsPressed) { - mExtendSelection = true; + if (mExtendSelection) { + commitCopy(); + } else { + mExtendSelection = true; + } } if (LOGV_ENABLED) { Log.v(LOGTAG, "onTrackballEvent up ev=" + ev @@ -3836,7 +3942,7 @@ public class WebView extends AbsoluteLayout int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET : 0; - pinScrollBy(scrollX, scrollY, true); + pinScrollBy(scrollX, scrollY, true, 0); Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); requestRectangleOnScreen(select); invalidate(); @@ -3942,6 +4048,7 @@ public class WebView extends AbsoluteLayout KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : KeyEvent.KEYCODE_DPAD_RIGHT; + count = Math.min(count, TRACKBALL_MOVE_COUNT); if (LOGV_ENABLED) { Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode + " count=" + count @@ -3971,7 +4078,7 @@ public class WebView extends AbsoluteLayout yMove = 0; } if (xMove != 0 || yMove != 0) { - pinScrollBy(xMove, yMove, true); + pinScrollBy(xMove, yMove, true, 0); } mUserScroll = true; } @@ -4044,43 +4151,30 @@ public class WebView extends AbsoluteLayout } } + // TODO: deprecate /** * Returns a view containing zoom controls i.e. +/- buttons. The caller is * in charge of installing this view to the view hierarchy. This view will * become visible when the user starts scrolling via touch and fade away if * the user does not interact with it. + *

          + * From 1.5, WebView change to use ZoomButtonsController. This will return + * an invisible dummy view for backwards compatibility. */ public View getZoomControls() { - if (!getSettings().supportZoom()) { - Log.w(LOGTAG, "This WebView doesn't support zoom."); - return null; - } - if (mZoomControls == null) { - mZoomControls = createZoomControls(); - - /* - * need to be set to VISIBLE first so that getMeasuredHeight() in - * {@link #onSizeChanged()} can return the measured value for proper - * layout. - */ - mZoomControls.setVisibility(View.VISIBLE); - mZoomControlRunnable = new Runnable() { - public void run() { - - /* Don't dismiss the controls if the user has - * focus on them. Wait and check again later. - */ - if (!mZoomControls.hasFocus()) { - mZoomControls.hide(); - } else { - mPrivateHandler.removeCallbacks(mZoomControlRunnable); - mPrivateHandler.postDelayed(mZoomControlRunnable, - ZOOM_CONTROLS_TIMEOUT); - } - } - }; - } - return mZoomControls; + return mZoomButtonsController.getDummyZoomControls(); + } + + /** + * Gets the {@link ZoomButtonsController} which can be used to add + * additional buttons to the zoom controls window. + * + * @return The instance of {@link ZoomButtonsController} used by this class, + * or null if it is unavailable. + * @hide pending API council + */ + public ZoomButtonsController getZoomButtonsController() { + return mZoomButtonsController; } /** @@ -4103,38 +4197,6 @@ public class WebView extends AbsoluteLayout return zoomWithPreview(mActualScale * 0.8f); } - private ExtendedZoomControls createZoomControls() { - ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext - , null); - zoomControls.setOnZoomInClickListener(new OnClickListener() { - public void onClick(View v) { - // reset time out - mPrivateHandler.removeCallbacks(mZoomControlRunnable); - mPrivateHandler.postDelayed(mZoomControlRunnable, - ZOOM_CONTROLS_TIMEOUT); - zoomIn(); - } - }); - zoomControls.setOnZoomOutClickListener(new OnClickListener() { - public void onClick(View v) { - // reset time out - mPrivateHandler.removeCallbacks(mZoomControlRunnable); - mPrivateHandler.postDelayed(mZoomControlRunnable, - ZOOM_CONTROLS_TIMEOUT); - zoomOut(); - } - }); - zoomControls.setOnZoomMagnifyClickListener(new OnClickListener() { - public void onClick(View v) { - mPrivateHandler.removeCallbacks(mZoomControlRunnable); - mPrivateHandler.postDelayed(mZoomControlRunnable, - ZOOM_CONTROLS_TIMEOUT); - zoomScrollOut(); - } - }); - return zoomControls; - } - private void updateSelection() { if (mNativeClass == 0) { return; @@ -4142,9 +4204,8 @@ public class WebView extends AbsoluteLayout // mLastTouchX and mLastTouchY are the point in the current viewport int contentX = viewToContent((int) mLastTouchX + mScrollX); int contentY = viewToContent((int) mLastTouchY + mScrollY); - int contentSize = ViewConfiguration.getTouchSlop(); - Rect rect = new Rect(contentX - contentSize, contentY - contentSize, - contentX + contentSize, contentY + contentSize); + Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, + contentX + mNavSlop, contentY + mNavSlop); // If we were already focused on a textfield, update its cache. if (inEditingMode()) { mTextEntry.updateCachedTextfield(); @@ -4157,8 +4218,7 @@ public class WebView extends AbsoluteLayout View v = mTextEntry; int x = viewToContent((v.getLeft() + v.getRight()) >> 1); int y = viewToContent((v.getTop() + v.getBottom()) >> 1); - int contentSize = ViewConfiguration.getTouchSlop(); - nativeMotionUp(x, y, contentSize, true); + nativeMotionUp(x, y, mNavSlop, true); } } @@ -4167,22 +4227,25 @@ public class WebView extends AbsoluteLayout return; } switchOutDrawHistory(); - // call uiOverride to check whether it is a special node, - // phone/email/address, which are not handled by WebKit - if (nativeUpdateFocusNode()) { - FocusNode node = mFocusNode; - if (!node.mIsTextField && !node.mIsTextArea) { - if (mCallbackProxy.uiOverrideUrlLoading(node.mText)) { - return; - } - } - playSoundEffect(SoundEffectConstants.CLICK); - } // mLastTouchX and mLastTouchY are the point in the current viewport int contentX = viewToContent((int) mLastTouchX + mScrollX); int contentY = viewToContent((int) mLastTouchY + mScrollY); - int contentSize = ViewConfiguration.getTouchSlop(); - nativeMotionUp(contentX, contentY, contentSize, true); + if (nativeMotionUp(contentX, contentY, mNavSlop, true)) { + if (mLogEvent) { + Checkin.updateStats(mContext.getContentResolver(), + Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0); + } + } + if (nativeUpdateFocusNode() && !mFocusNode.mIsTextField + && !mFocusNode.mIsTextArea) { + playSoundEffect(SoundEffectConstants.CLICK); + } + } + + // Called by JNI to handle a touch on a node representing an email address, + // address, or phone number + private void overrideLoading(String url) { + mCallbackProxy.uiOverrideUrlLoading(url); } @Override @@ -4309,7 +4372,7 @@ public class WebView extends AbsoluteLayout } if ((scrollYDelta | scrollXDelta) != 0) { - return pinScrollBy(scrollXDelta, scrollYDelta, !immediate); + return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); } return false; @@ -4322,6 +4385,7 @@ public class WebView extends AbsoluteLayout arg.put("replace", replace); arg.put("start", new Integer(newStart)); arg.put("end", new Integer(newEnd)); + mTextGeneration++; mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); } @@ -4357,6 +4421,11 @@ public class WebView extends AbsoluteLayout class PrivateHandler extends Handler { @Override public void handleMessage(Message msg) { + if (LOGV_ENABLED) { + Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what + > INVAL_RECT_MSG_ID ? Integer.toString(msg.what) + : HandlerDebugString[msg.what - REMEMBER_PASSWORD]); + } switch (msg.what) { case REMEMBER_PASSWORD: { mDatabase.setUsernamePassword( @@ -4385,11 +4454,6 @@ public class WebView extends AbsoluteLayout updateTextEntry(); break; } - case RELEASE_SINGLE_TAP: { - mTouchMode = TOUCH_DONE_MODE; - doShortPress(); - break; - } case SWITCH_TO_ENTER: if (LOGV_ENABLED) Log.v(LOGTAG, "SWITCH_TO_ENTER"); mTouchMode = TOUCH_DONE_MODE; @@ -4398,7 +4462,7 @@ public class WebView extends AbsoluteLayout , KeyEvent.KEYCODE_ENTER)); break; case SCROLL_BY_MSG_ID: - setContentScrollBy(msg.arg1, msg.arg2); + setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); break; case SYNC_SCROLL_TO_MSG_ID: if (mUserScroll) { @@ -4436,6 +4500,10 @@ public class WebView extends AbsoluteLayout 0, 0); } } + if (!mMinZoomScaleFixed) { + mMinZoomScale = (float) getViewWidth() + / Math.max(ZOOM_OUT_WIDTH, draw.mWidthHeight.x); + } // We update the layout (i.e. request a layout from the // view system) if the last view size that we sent to // WebCore matches the view size of the picture we just @@ -4494,8 +4562,10 @@ public class WebView extends AbsoluteLayout int minScale = (Integer) scaleLimit.get("minScale"); if (minScale == 0) { mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; + mMinZoomScaleFixed = false; } else { mMinZoomScale = (float) (minScale / 100.0); + mMinZoomScaleFixed = true; } int maxScale = (Integer) scaleLimit.get("maxScale"); if (maxScale == 0) { @@ -4544,6 +4614,15 @@ public class WebView extends AbsoluteLayout } break; case UPDATE_TEXT_ENTRY_MSG_ID: + // this is sent after finishing resize in WebViewCore. Make + // sure the text edit box is still on the screen. + boolean alreadyThere = inEditingMode(); + if (alreadyThere && nativeUpdateFocusNode()) { + FocusNode node = mFocusNode; + if (node.mIsTextField || node.mIsTextArea) { + mTextEntry.bringIntoView(); + } + } updateTextEntry(); break; case RECOMPUTE_FOCUS_MSG_ID: @@ -4551,6 +4630,17 @@ public class WebView extends AbsoluteLayout nativeRecomputeFocus(); } break; + case INVAL_RECT_MSG_ID: { + Rect r = (Rect)msg.obj; + if (r == null) { + invalidate(); + } else { + // we need to scale r from content into view coords, + // which viewInvalidate() does for us + viewInvalidate(r.left, r.top, r.right, r.bottom); + } + break; + } case UPDATE_TEXT_ENTRY_ADAPTER: HashMap data = (HashMap) msg.obj; if (mTextEntry.isSameTextField(msg.arg1)) { @@ -4595,12 +4685,12 @@ public class WebView extends AbsoluteLayout break; case PREVENT_TOUCH_ID: - // update may have already been paused by touch; restore since - // this effectively aborts touch and skips logic in touch up - if (mTouchMode == TOUCH_DRAG_MODE) { - WebViewCore.resumeUpdate(mWebViewCore); + if (msg.arg1 == MotionEvent.ACTION_DOWN) { + mPreventDrag = msg.arg2 == 1; + if (mPreventDrag) { + mTouchMode = TOUCH_DONE_MODE; + } } - mTouchMode = TOUCH_DONE_MODE; break; default: @@ -4764,8 +4854,16 @@ public class WebView extends AbsoluteLayout }); if (mSelection != -1) { listView.setSelection(mSelection); + listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + listView.setItemChecked(mSelection, true); } } + dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { + public void onCancel(DialogInterface dialog) { + mWebViewCore.sendMessage( + EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); + } + }); dialog.show(); } } @@ -4910,11 +5008,11 @@ public class WebView extends AbsoluteLayout // FIXME: Necessary because ScrollView/ListView do not scroll left/right int maxH = Math.min(viewFocus.right - visRect.right, maxXScroll); if (maxH > 0) { - pinScrollBy(maxH, 0, true); + pinScrollBy(maxH, 0, true, 0); } else { maxH = Math.max(viewFocus.left - visRect.left, -maxXScroll); if (maxH < 0) { - pinScrollBy(maxH, 0, true); + pinScrollBy(maxH, 0, true, 0); } } if (mLastFocusBounds.isEmpty()) return keyHandled; @@ -4967,8 +5065,10 @@ public class WebView extends AbsoluteLayout private native boolean nativeUpdateFocusNode(); private native Rect nativeGetFocusRingBounds(); private native Rect nativeGetNavBounds(); + private native void nativeInstrumentReport(); private native void nativeMarkNodeInvalid(int node); - private native void nativeMotionUp(int x, int y, int slop, boolean isClick); + // return true if the page has been scrolled + private native boolean nativeMotionUp(int x, int y, int slop, boolean isClick); // returns false if it handled the key private native boolean nativeMoveFocus(int keyCode, int count, boolean noScroll); @@ -4976,8 +5076,8 @@ public class WebView extends AbsoluteLayout private native void nativeRecomputeFocus(); // Like many other of our native methods, you must make sure that // mNativeClass is not null before calling this method. - private native void nativeRecordButtons(boolean pressed, - boolean invalidate); + private native void nativeRecordButtons(boolean focused, + boolean pressed, boolean invalidate); private native void nativeResetFocus(); private native void nativeResetNavClipBounds(); private native void nativeSelectBestAt(Rect rect); diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java index 323b44d923460d9dd1cb1086b6f7ea3b94d6f7c1..3e4daf711a44c45dfb8abcaacf2ad06e62342e43 100644 --- a/core/java/android/webkit/WebViewCore.java +++ b/core/java/android/webkit/WebViewCore.java @@ -317,7 +317,7 @@ final class WebViewCore { should this be called nativeSetViewPortSize? */ private native void nativeSetSize(int width, int height, int screenWidth, - float scale); + float scale, int realScreenWidth, int screenHeight); private native int nativeGetContentMinPrefWidth(); @@ -330,8 +330,7 @@ final class WebViewCore { String currentText, int keyCode, int keyValue, boolean down, boolean cap, boolean fn, boolean sym); - private native void nativeSaveDocumentState(int frame, int node, int x, - int y); + private native void nativeSaveDocumentState(int frame); private native void nativeSetFinalFocus(int framePtr, int nodePtr, int x, int y, boolean block); @@ -502,6 +501,51 @@ final class WebViewCore { int mY; } + static final String[] HandlerDebugString = { + "LOAD_URL", // = 100; + "STOP_LOADING", // = 101; + "RELOAD", // = 102; + "KEY_DOWN", // = 103; + "KEY_UP", // = 104; + "VIEW_SIZE_CHANGED", // = 105; + "GO_BACK_FORWARD", // = 106; + "SET_SCROLL_OFFSET", // = 107; + "RESTORE_STATE", // = 108; + "PAUSE_TIMERS", // = 109; + "RESUME_TIMERS", // = 110; + "CLEAR_CACHE", // = 111; + "CLEAR_HISTORY", // = 112; + "SET_SELECTION", // = 113; + "REPLACE_TEXT", // = 114; + "PASS_TO_JS", // = 115; + "SET_GLOBAL_BOUNDS", // = 116; + "UPDATE_CACHE_AND_TEXT_ENTRY", // = 117; + "CLICK", // = 118; + "119", + "DOC_HAS_IMAGES", // = 120; + "SET_SNAP_ANCHOR", // = 121; + "DELETE_SELECTION", // = 122; + "LISTBOX_CHOICES", // = 123; + "SINGLE_LISTBOX_CHOICE", // = 124; + "125", + "SET_BACKGROUND_COLOR", // = 126; + "UNBLOCK_FOCUS", // = 127; + "SAVE_DOCUMENT_STATE", // = 128; + "GET_SELECTION", // = 129; + "WEBKIT_DRAW", // = 130; + "SYNC_SCROLL", // = 131; + "REFRESH_PLUGINS", // = 132; + "SPLIT_PICTURE_SET", // = 133; + "CLEAR_CONTENT", // = 134; + "SET_FINAL_FOCUS", // = 135; + "SET_KIT_FOCUS", // = 136; + "REQUEST_FOCUS_HREF", // = 137; + "ADD_JS_INTERFACE", // = 138; + "LOAD_DATA", // = 139; + "TOUCH_UP", // = 140; + "TOUCH_EVENT", // = 141; + }; + class EventHub { // Message Ids static final int LOAD_URL = 100; @@ -596,6 +640,11 @@ final class WebViewCore { mHandler = new Handler() { @Override public void handleMessage(Message msg) { + if (LOGV_ENABLED) { + Log.v(LOGTAG, msg.what < LOAD_URL || msg.what + > TOUCH_EVENT ? Integer.toString(msg.what) + : HandlerDebugString[msg.what - LOAD_URL]); + } switch (msg.what) { case WEBKIT_DRAW: webkitDraw(); @@ -777,8 +826,7 @@ final class WebViewCore { case SAVE_DOCUMENT_STATE: { FocusData fDat = (FocusData) msg.obj; - nativeSaveDocumentState(fDat.mFrame, fDat.mNode, - fDat.mX, fDat.mY); + nativeSaveDocumentState(fDat.mFrame); break; } @@ -799,12 +847,11 @@ final class WebViewCore { case TOUCH_EVENT: { TouchEventData ted = (TouchEventData) msg.obj; - if (nativeHandleTouchEvent(ted.mAction, ted.mX, - ted.mY)) { - Message.obtain(mWebView.mPrivateHandler, - WebView.PREVENT_TOUCH_ID) - .sendToTarget(); - } + Message.obtain( + mWebView.mPrivateHandler, + WebView.PREVENT_TOUCH_ID, ted.mAction, + nativeHandleTouchEvent(ted.mAction, ted.mX, + ted.mY) ? 1 : 0).sendToTarget(); break; } @@ -1137,6 +1184,10 @@ final class WebViewCore { // notify webkit that our virtual view size changed size (after inv-zoom) private void viewSizeChanged(int w, int h, float scale) { if (LOGV_ENABLED) Log.v(LOGTAG, "CORE onSizeChanged"); + if (w == 0) { + Log.w(LOGTAG, "skip viewSizeChanged as w is 0"); + return; + } if (mSettings.getUseWideViewPort() && (w < mViewportWidth || mViewportWidth == -1)) { int width = mViewportWidth; @@ -1160,9 +1211,10 @@ final class WebViewCore { width = Math.max(w, nativeGetContentMinPrefWidth()); } } - nativeSetSize(width, Math.round((float) width * h / w), w, scale); + nativeSetSize(width, Math.round((float) width * h / w), w, scale, + w, h); } else { - nativeSetSize(w, h, w, scale); + nativeSetSize(w, h, w, scale, w, h); } // Remember the current width and height boolean needInvalidate = (mCurrentViewWidth == 0); @@ -1327,7 +1379,9 @@ final class WebViewCore { for (int i = 0; i < size; i++) { list.getItemAtIndex(i).inflate(mBrowserFrame.mNativeFrame); } + mBrowserFrame.mLoadInitFromJava = true; list.restoreIndex(mBrowserFrame.mNativeFrame, index); + mBrowserFrame.mLoadInitFromJava = false; } //------------------------------------------------------------------------- @@ -1352,14 +1406,15 @@ final class WebViewCore { } // called by JNI - private void contentScrollBy(int dx, int dy) { + private void contentScrollBy(int dx, int dy, boolean animate) { if (!mBrowserFrame.firstLayoutDone()) { // Will this happen? If yes, we need to do something here. return; } if (mWebView != null) { Message.obtain(mWebView.mPrivateHandler, - WebView.SCROLL_BY_MSG_ID, dx, dy).sendToTarget(); + WebView.SCROLL_BY_MSG_ID, dx, dy, + new Boolean(animate)).sendToTarget(); } } @@ -1434,10 +1489,15 @@ final class WebViewCore { } } - // called by JNI + /* Called by JNI. The coordinates are in doc coordinates, so they need to + be scaled before they can be used by the view system, which happens + in WebView since it (and its thread) know the current scale factor. + */ private void sendViewInvalidate(int left, int top, int right, int bottom) { if (mWebView != null) { - mWebView.postInvalidate(left, top, right, bottom); + Message.obtain(mWebView.mPrivateHandler, + WebView.INVAL_RECT_MSG_ID, + new Rect(left, top, right, bottom)).sendToTarget(); } } diff --git a/core/java/android/webkit/WebViewDatabase.java b/core/java/android/webkit/WebViewDatabase.java index 96f36983343a51e3bb33e8935620d922e8e2e91d..1004e30ef5e623513282e74088215a92f0c9beb7 100644 --- a/core/java/android/webkit/WebViewDatabase.java +++ b/core/java/android/webkit/WebViewDatabase.java @@ -531,33 +531,34 @@ public class WebViewDatabase { * @param url The url * @return CacheResult The CacheManager.CacheResult */ - @SuppressWarnings("deprecation") CacheResult getCache(String url) { if (url == null || mCacheDatabase == null) { return null; } - CacheResult ret = null; - final String s = "SELECT filepath, lastmodify, etag, expires, mimetype, encoding, httpstatus, location, contentlength FROM cache WHERE url = "; - StringBuilder sb = new StringBuilder(256); - sb.append(s); - DatabaseUtils.appendEscapedSQLString(sb, url); - Cursor cursor = mCacheDatabase.rawQuery(sb.toString(), null); + Cursor cursor = mCacheDatabase.rawQuery("SELECT filepath, lastmodify, etag, expires, " + + "mimetype, encoding, httpstatus, location, contentlength " + + "FROM cache WHERE url = ?", + new String[] { url }); - if (cursor.moveToFirst()) { - ret = new CacheResult(); - ret.localPath = cursor.getString(0); - ret.lastModified = cursor.getString(1); - ret.etag = cursor.getString(2); - ret.expires = cursor.getLong(3); - ret.mimeType = cursor.getString(4); - ret.encoding = cursor.getString(5); - ret.httpStatusCode = cursor.getInt(6); - ret.location = cursor.getString(7); - ret.contentLength = cursor.getLong(8); + try { + if (cursor.moveToFirst()) { + CacheResult ret = new CacheResult(); + ret.localPath = cursor.getString(0); + ret.lastModified = cursor.getString(1); + ret.etag = cursor.getString(2); + ret.expires = cursor.getLong(3); + ret.mimeType = cursor.getString(4); + ret.encoding = cursor.getString(5); + ret.httpStatusCode = cursor.getInt(6); + ret.location = cursor.getString(7); + ret.contentLength = cursor.getLong(8); + return ret; + } + } finally { + if (cursor != null) cursor.close(); } - cursor.close(); - return ret; + return null; } /** @@ -565,16 +566,12 @@ public class WebViewDatabase { * * @param url The url */ - @SuppressWarnings("deprecation") void removeCache(String url) { if (url == null || mCacheDatabase == null) { return; } - StringBuilder sb = new StringBuilder(256); - sb.append("DELETE FROM cache WHERE url = "); - DatabaseUtils.appendEscapedSQLString(sb, url); - mCacheDatabase.execSQL(sb.toString()); + mCacheDatabase.execSQL("DELETE FROM cache WHERE url = ?", new String[] { url }); } /** diff --git a/core/java/android/webkit/gears/DesktopAndroid.java b/core/java/android/webkit/gears/DesktopAndroid.java index ee8ca498562be7a0fd46fa751448bc78e221971b..a7a144b1633c88196b1f23e698fa4bb15904ef0c 100644 --- a/core/java/android/webkit/gears/DesktopAndroid.java +++ b/core/java/android/webkit/gears/DesktopAndroid.java @@ -31,6 +31,7 @@ import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; +import android.provider.Browser; import android.util.Log; import android.webkit.WebView; @@ -78,7 +79,10 @@ public class DesktopAndroid { Intent viewWebPage = new Intent(Intent.ACTION_VIEW); viewWebPage.setData(Uri.parse(url)); - viewWebPage.addCategory(Intent.CATEGORY_BROWSABLE); + long urlHash = url.hashCode(); + long uniqueId = (urlHash << 32) | viewWebPage.hashCode(); + viewWebPage.putExtra(Browser.EXTRA_APPLICATION_ID, + Long.toString(uniqueId)); Intent intent = new Intent(ACTION_INSTALL_SHORTCUT); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, viewWebPage); diff --git a/core/java/android/webkit/gears/GearsPluginSettings.java b/core/java/android/webkit/gears/GearsPluginSettings.java deleted file mode 100644 index d36d3fb2d584bb8730adc327e81e26438ee79d16..0000000000000000000000000000000000000000 --- a/core/java/android/webkit/gears/GearsPluginSettings.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2008 The Android Open Source Project -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// 3. Neither the name of Google Inc. nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package android.webkit.gears; - -import android.content.ComponentName; -import android.content.Context; -import android.content.ServiceConnection; -import android.os.IBinder; -import android.util.Log; -import android.webkit.Plugin; -import android.webkit.Plugin.PreferencesClickHandler; - -/** - * Simple bridge class intercepting the click in the - * browser plugin list and calling the Gears settings - * dialog. - */ -public class GearsPluginSettings { - - private static final String TAG = "Gears-J-GearsPluginSettings"; - private Context context; - - public GearsPluginSettings(Plugin plugin) { - plugin.setClickHandler(new ClickHandler()); - } - - /** - * We do not need to call the dialog synchronously here (doing so - * actually cause a lot of problems as the main message loop is also - * blocked), which is why we simply call it via a thread. - */ - private class ClickHandler implements PreferencesClickHandler { - public void handleClickEvent(Context aContext) { - context = aContext; - Thread startService = new Thread(new StartService()); - startService.run(); - } - } - - private static native void runSettingsDialog(Context c); - - /** - * StartService is the runnable we use to open the dialog. - * We bind the service to serviceConnection; upon - * onServiceConnected the dialog will be called from the - * native side using the runSettingsDialog method. - */ - private class StartService implements Runnable { - public void run() { - HtmlDialogAndroid.bindToService(context, serviceConnection); - } - } - - /** - * ServiceConnection instance. - * onServiceConnected is called upon connection with the service; - * we can then safely open the dialog. - */ - private ServiceConnection serviceConnection = new ServiceConnection() { - public void onServiceConnected(ComponentName className, IBinder service) { - IGearsDialogService gearsDialogService = - IGearsDialogService.Stub.asInterface(service); - HtmlDialogAndroid.setGearsDialogService(gearsDialogService); - runSettingsDialog(context); - context.unbindService(serviceConnection); - HtmlDialogAndroid.setGearsDialogService(null); - } - public void onServiceDisconnected(ComponentName className) { - HtmlDialogAndroid.setGearsDialogService(null); - } - }; -} diff --git a/core/java/android/webkit/gears/HtmlDialogAndroid.java b/core/java/android/webkit/gears/HtmlDialogAndroid.java deleted file mode 100644 index 6209ab91394e1f072fc01221fc9626ae925c0b94..0000000000000000000000000000000000000000 --- a/core/java/android/webkit/gears/HtmlDialogAndroid.java +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2008 The Android Open Source Project -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// 3. Neither the name of Google Inc. nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package android.webkit.gears; - -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.ServiceConnection; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Log; -import android.webkit.CacheManager; - -import java.io.FileInputStream; -import java.io.IOException; - -/** - * Utility class to call a modal HTML dialog on Android - */ -public class HtmlDialogAndroid { - - private static final String TAG = "Gears-J-HtmlDialog"; - private static final String DIALOG_PACKAGE = "com.android.browser"; - private static final String DIALOG_SERVICE = DIALOG_PACKAGE - + ".GearsDialogService"; - private static final String DIALOG_INTERFACE = DIALOG_PACKAGE - + ".IGearsDialogService"; - - private static IGearsDialogService gearsDialogService; - - public static void setGearsDialogService(IGearsDialogService service) { - gearsDialogService = service; - } - - /** - * Bind to the GearsDialogService. - */ - public static boolean bindToService(Context context, - ServiceConnection serviceConnection) { - Intent dialogIntent = new Intent(); - dialogIntent.setClassName(DIALOG_PACKAGE, DIALOG_SERVICE); - dialogIntent.setAction(DIALOG_INTERFACE); - return context.bindService(dialogIntent, serviceConnection, - Context.BIND_AUTO_CREATE); - } - - /** - * Bind to the GearsDialogService synchronously. - * The service is started using our own defaultServiceConnection - * handler, and we wait until the handler notifies us. - */ - public void synchronousBindToService(Context context) { - try { - if (bindToService(context, defaultServiceConnection)) { - if (gearsDialogService == null) { - synchronized(defaultServiceConnection) { - defaultServiceConnection.wait(3000); // timeout after 3s - } - } - } - } catch (InterruptedException e) { - Log.e(TAG, "exception: " + e); - } - } - - /** - * Read the HTML content from the disk - */ - public String readHTML(String filePath) { - FileInputStream inputStream = null; - String content = ""; - try { - inputStream = new FileInputStream(filePath); - StringBuffer out = new StringBuffer(); - byte[] buffer = new byte[4096]; - for (int n; (n = inputStream.read(buffer)) != -1;) { - out.append(new String(buffer, 0, n)); - } - content = out.toString(); - } catch (IOException e) { - Log.e(TAG, "exception: " + e); - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - Log.e(TAG, "exception: " + e); - } - } - } - return content; - } - - /** - * Open an HTML dialog synchronously and waits for its completion. - * The dialog is accessed through the GearsDialogService provided by - * the Android Browser. - * We can be called either directly, and then gearsDialogService will - * not be set and we will bind to the service synchronously, and unbind - * after calling the service, or called indirectly via GearsPluginSettings. - * In the latter case, GearsPluginSettings does the binding/unbinding. - */ - public String showDialog(Context context, String htmlFilePath, - String arguments) { - - CacheManager.endCacheTransaction(); - - String ret = null; - boolean synchronousCall = false; - if (gearsDialogService == null) { - synchronousCall = true; - synchronousBindToService(context); - } - - try { - if (gearsDialogService != null) { - String htmlContent = readHTML(htmlFilePath); - if (htmlContent.length() > 0) { - ret = gearsDialogService.showDialog(htmlContent, arguments, - !synchronousCall); - } - } else { - Log.e(TAG, "Could not connect to the GearsDialogService!"); - } - if (synchronousCall) { - context.unbindService(defaultServiceConnection); - gearsDialogService = null; - } - } catch (RemoteException e) { - Log.e(TAG, "remote exception: " + e); - gearsDialogService = null; - } - - CacheManager.startCacheTransaction(); - - return ret; - } - - private ServiceConnection defaultServiceConnection = - new ServiceConnection() { - public void onServiceConnected(ComponentName className, IBinder service) { - synchronized (defaultServiceConnection) { - gearsDialogService = IGearsDialogService.Stub.asInterface(service); - defaultServiceConnection.notify(); - } - } - public void onServiceDisconnected(ComponentName className) { - gearsDialogService = null; - } - }; -} diff --git a/core/java/android/webkit/gears/HttpRequestAndroid.java b/core/java/android/webkit/gears/HttpRequestAndroid.java deleted file mode 100644 index 30f855f0c892b40522278f8f19d2b8aa419ca1d6..0000000000000000000000000000000000000000 --- a/core/java/android/webkit/gears/HttpRequestAndroid.java +++ /dev/null @@ -1,745 +0,0 @@ -// Copyright 2008, The Android Open Source Project -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// 3. Neither the name of Google Inc. nor the names of its contributors may be -// used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package android.webkit.gears; - -import android.net.http.Headers; -import android.os.Handler; -import android.os.Looper; -import android.os.Message; -import android.util.Log; -import android.webkit.CacheManager; -import android.webkit.CacheManager.CacheResult; -import android.webkit.CookieManager; - -import org.apache.http.conn.ssl.StrictHostnameVerifier; -import org.apache.http.impl.cookie.DateUtils; -import org.apache.http.util.CharArrayBuffer; - -import java.io.*; -import java.net.*; -import java.util.*; -import javax.net.ssl.*; - -/** - * Performs the underlying HTTP/HTTPS GET and POST requests. - *

          These are performed synchronously (blocking). The caller should - * ensure that it is in a background thread if asynchronous behavior - * is required. All data is pushed, so there is no need for JNI native - * callbacks. - *

          This uses the java.net.HttpURLConnection class to perform most - * of the underlying network activity. The Android brower's cache, - * android.webkit.CacheManager, is also used when caching is enabled, - * and updated with new data. The android.webkit.CookieManager is also - * queried and updated as necessary. - *

          The public interface is designed to be called by native code - * through JNI, and to simplify coding none of the public methods will - * surface a checked exception. Unchecked exceptions may still be - * raised but only if the system is in an ill state, such as out of - * memory. - *

          TODO: This isn't plumbed into LocalServer yet. Mutually - * dependent on LocalServer - will attach the two together once both - * are submitted. - */ -public final class HttpRequestAndroid { - /** Debug logging tag. */ - private static final String LOG_TAG = "Gears-J"; - /** HTTP response header line endings are CR-LF style. */ - private static final String HTTP_LINE_ENDING = "\r\n"; - /** Safe MIME type to use whenever it isn't specified. */ - private static final String DEFAULT_MIME_TYPE = "text/plain"; - /** Case-sensitive header keys */ - public static final String KEY_CONTENT_LENGTH = "Content-Length"; - public static final String KEY_EXPIRES = "Expires"; - public static final String KEY_LAST_MODIFIED = "Last-Modified"; - public static final String KEY_ETAG = "ETag"; - public static final String KEY_LOCATION = "Location"; - public static final String KEY_CONTENT_TYPE = "Content-Type"; - /** Number of bytes to send and receive on the HTTP connection in - * one go. */ - private static final int BUFFER_SIZE = 4096; - /** The first element of the String[] value in a headers map is the - * unmodified (case-sensitive) key. */ - public static final int HEADERS_MAP_INDEX_KEY = 0; - /** The second element of the String[] value in a headers map is the - * associated value. */ - public static final int HEADERS_MAP_INDEX_VALUE = 1; - - /** Enable/disable all logging in this class. */ - private static boolean logEnabled = false; - /** The underlying HTTP or HTTPS network connection. */ - private HttpURLConnection connection; - /** HTTP body stream, setup after connection. */ - private InputStream inputStream; - /** The complete response line e.g "HTTP/1.0 200 OK" */ - private String responseLine; - /** Request headers, as a lowercase key -> [ unmodified key, value ] map. */ - private Map requestHeaders = - new HashMap(); - /** Response headers, as a lowercase key -> [ unmodified key, value ] map. */ - private Map responseHeaders; - /** True if the child thread is in performing blocking IO. */ - private boolean inBlockingOperation = false; - /** True when the thread acknowledges the abort. */ - private boolean abortReceived = false; - /** The URL used for createCacheResult() */ - private String cacheResultUrl; - /** CacheResult being saved into, if inserting a new cache entry. */ - private CacheResult cacheResult; - /** Initialized by initChildThread(). Used to target abort(). */ - private Thread childThread; - - /** - * Convenience debug function. Calls Android logging mechanism. - * @param str String to log to the Android console. - */ - private static void log(String str) { - if (logEnabled) { - Log.i(LOG_TAG, str); - } - } - - /** - * Turn on/off logging in this class. - * @param on Logging enable state. - */ - public static void enableLogging(boolean on) { - logEnabled = on; - } - - /** - * Initialize childThread using the TLS value of - * Thread.currentThread(). Called on start up of the native child - * thread. - */ - public synchronized void initChildThread() { - childThread = Thread.currentThread(); - } - - /** - * Analagous to the native-side HttpRequest::open() function. This - * initializes an underlying java.net.HttpURLConnection, but does - * not go to the wire. On success, this enables a call to send() to - * initiate the transaction. - * - * @param method The HTTP method, e.g GET or POST. - * @param url The URL to open. - * @return True on success with a complete HTTP response. - * False on failure. - */ - public synchronized boolean open(String method, String url) { - if (logEnabled) - log("open " + method + " " + url); - // Reset the response between calls to open(). - inputStream = null; - responseLine = null; - responseHeaders = null; - if (!method.equals("GET") && !method.equals("POST")) { - log("Method " + method + " not supported"); - return false; - } - // Setup the connection. This doesn't go to the wire yet - it - // doesn't block. - try { - URL url_object = new URL(url); - // Check that the protocol is indeed HTTP(S). - String protocol = url_object.getProtocol(); - if (protocol == null) { - log("null protocol for URL " + url); - return false; - } - protocol = protocol.toLowerCase(); - if (!"http".equals(protocol) && !"https".equals(protocol)) { - log("Url has wrong protocol: " + url); - return false; - } - - connection = (HttpURLConnection) url_object.openConnection(); - connection.setRequestMethod(method); - // Manually follow redirects. - connection.setInstanceFollowRedirects(false); - // Manually cache. - connection.setUseCaches(false); - // Enable data output in POST method requests. - connection.setDoOutput(method.equals("POST")); - // Enable data input in non-HEAD method requests. - // TODO: HEAD requests not tested. - connection.setDoInput(!method.equals("HEAD")); - if (connection instanceof javax.net.ssl.HttpsURLConnection) { - // Verify the certificate matches the origin. - ((HttpsURLConnection) connection).setHostnameVerifier( - new StrictHostnameVerifier()); - } - return true; - } catch (IOException e) { - log("Got IOException in open: " + e.toString()); - return false; - } - } - - /** - * Interrupt a blocking IO operation. This will cause the child - * thread to expediently return from an operation if it was stuck at - * the time. Note that this inherently races, and unfortunately - * requires the caller to loop. - */ - public synchronized void interrupt() { - if (childThread == null) { - log("interrupt() called but no child thread"); - return; - } - synchronized (this) { - if (inBlockingOperation) { - log("Interrupting blocking operation"); - childThread.interrupt(); - } else { - log("Nothing to interrupt"); - } - } - } - - /** - * Set a header to send with the HTTP request. Will not take effect - * on a transaction already in progress. The key is associated - * case-insensitive, but stored case-sensitive. - * @param name The name of the header, e.g "Set-Cookie". - * @param value The value for this header, e.g "text/html". - */ - public synchronized void setRequestHeader(String name, String value) { - String[] mapValue = { name, value }; - requestHeaders.put(name.toLowerCase(), mapValue); - } - - /** - * Returns the value associated with the given request header. - * @param name The name of the request header, non-null, case-insensitive. - * @return The value associated with the request header, or null if - * not set, or error. - */ - public synchronized String getRequestHeader(String name) { - String[] value = requestHeaders.get(name.toLowerCase()); - if (value != null) { - return value[HEADERS_MAP_INDEX_VALUE]; - } else { - return null; - } - } - - /** - * Returns the value associated with the given response header. - * @param name The name of the response header, non-null, case-insensitive. - * @return The value associated with the response header, or null if - * not set or error. - */ - public synchronized String getResponseHeader(String name) { - if (responseHeaders != null) { - String[] value = responseHeaders.get(name.toLowerCase()); - if (value != null) { - return value[HEADERS_MAP_INDEX_VALUE]; - } else { - return null; - } - } else { - log("getResponseHeader() called but response not received"); - return null; - } - } - - /** - * Set a response header and associated value. The key is associated - * case-insensitively, but stored case-sensitively. - * @param name Case sensitive request header key. - * @param value The associated value. - */ - private void setResponseHeader(String name, String value) { - if (logEnabled) - log("Set response header " + name + ": " + value); - String mapValue[] = { name, value }; - responseHeaders.put(name.toLowerCase(), mapValue); - } - - /** - * Apply the contents of the Map requestHeaders to the connection - * object. Calls to setRequestHeader() after this will not affect - * the connection. - */ - private synchronized void applyRequestHeadersToConnection() { - Iterator it = requestHeaders.values().iterator(); - while (it.hasNext()) { - // Set the key case-sensitive. - String[] entry = it.next(); - connection.setRequestProperty( - entry[HEADERS_MAP_INDEX_KEY], - entry[HEADERS_MAP_INDEX_VALUE]); - } - } - - /** - * Return all response headers, separated by CR-LF line endings, and - * ending with a trailing blank line. This mimics the format of the - * raw response header up to but not including the body. - * @return A string containing the entire response header. - */ - public synchronized String getAllResponseHeaders() { - if (responseHeaders == null) { - log("getAllResponseHeaders() called but response not received"); - return null; - } - String result = new String(); - Iterator it = responseHeaders.values().iterator(); - while (it.hasNext()) { - String[] entry = it.next(); - // Output the "key: value" lines. - result += entry[HEADERS_MAP_INDEX_KEY] + ": " - + entry[HEADERS_MAP_INDEX_VALUE] + HTTP_LINE_ENDING; - } - result += HTTP_LINE_ENDING; - return result; - } - - /** - * Get the complete response line of the HTTP request. Only valid on - * completion of the transaction. - * @return The complete HTTP response line, e.g "HTTP/1.0 200 OK". - */ - public synchronized String getResponseLine() { - return responseLine; - } - - /** - * Get the cookie for the given URL. - * @param url The fully qualified URL. - * @return A string containing the cookie for the URL if it exists, - * or null if not. - */ - public static String getCookieForUrl(String url) { - // Get the cookie for this URL, set as a header - return CookieManager.getInstance().getCookie(url); - } - - /** - * Set the cookie for the given URL. - * @param url The fully qualified URL. - * @param cookie The new cookie value. - * @return A string containing the cookie for the URL if it exists, - * or null if not. - */ - public static void setCookieForUrl(String url, String cookie) { - // Get the cookie for this URL, set as a header - CookieManager.getInstance().setCookie(url, cookie); - } - - /** - * Perform a request using LocalServer if possible. Initializes - * class members so that receive() will obtain data from the stream - * provided by the response. - * @param url The fully qualified URL to try in LocalServer. - * @return True if the url was found and is now setup to receive. - * False if not found, with no side-effect. - */ - public synchronized boolean useLocalServerResult(String url) { - UrlInterceptHandlerGears handler = UrlInterceptHandlerGears.getInstance(); - if (handler == null) { - return false; - } - UrlInterceptHandlerGears.ServiceResponse serviceResponse = - handler.getServiceResponse(url, requestHeaders); - if (serviceResponse == null) { - log("No response in LocalServer"); - return false; - } - // LocalServer will handle this URL. Initialize stream and - // response. - inputStream = serviceResponse.getInputStream(); - responseLine = serviceResponse.getStatusLine(); - responseHeaders = serviceResponse.getResponseHeaders(); - if (logEnabled) - log("Got response from LocalServer: " + responseLine); - return true; - } - - /** - * Perform a request using the cache result if present. Initializes - * class members so that receive() will obtain data from the cache. - * @param url The fully qualified URL to try in the cache. - * @return True is the url was found and is now setup to receive - * from cache. False if not found, with no side-effect. - */ - public synchronized boolean useCacheResult(String url) { - // Try the browser's cache. CacheManager wants a Map. - Map cacheRequestHeaders = new HashMap(); - Iterator> it = - requestHeaders.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = it.next(); - cacheRequestHeaders.put( - entry.getKey(), - entry.getValue()[HEADERS_MAP_INDEX_VALUE]); - } - CacheResult cacheResult = - CacheManager.getCacheFile(url, cacheRequestHeaders); - if (cacheResult == null) { - if (logEnabled) - log("No CacheResult for " + url); - return false; - } - if (logEnabled) - log("Got CacheResult from browser cache"); - // Check for expiry. -1 is "never", otherwise milliseconds since 1970. - // Can be compared to System.currentTimeMillis(). - long expires = cacheResult.getExpires(); - if (expires >= 0 && System.currentTimeMillis() >= expires) { - log("CacheResult expired " - + (System.currentTimeMillis() - expires) - + " milliseconds ago"); - // Cache hit has expired. Do not return it. - return false; - } - // Setup the inputStream to come from the cache. - inputStream = cacheResult.getInputStream(); - if (inputStream == null) { - // Cache result may have gone away. - log("No inputStream for CacheResult " + url); - return false; - } - // Cache hit. Parse headers. - synthesizeHeadersFromCacheResult(cacheResult); - return true; - } - - /** - * Take the limited set of headers in a CacheResult and synthesize - * response headers. - * @param cacheResult A CacheResult to populate responseHeaders with. - */ - private void synthesizeHeadersFromCacheResult(CacheResult cacheResult) { - int statusCode = cacheResult.getHttpStatusCode(); - // The status message is informal, so we can greatly simplify it. - String statusMessage; - if (statusCode >= 200 && statusCode < 300) { - statusMessage = "OK"; - } else if (statusCode >= 300 && statusCode < 400) { - statusMessage = "MOVED"; - } else { - statusMessage = "UNAVAILABLE"; - } - // Synthesize the response line. - responseLine = "HTTP/1.1 " + statusCode + " " + statusMessage; - if (logEnabled) - log("Synthesized " + responseLine); - // Synthesize the returned headers from cache. - responseHeaders = new HashMap(); - String contentLength = Long.toString(cacheResult.getContentLength()); - setResponseHeader(KEY_CONTENT_LENGTH, contentLength); - long expires = cacheResult.getExpires(); - if (expires >= 0) { - // "Expires" header is valid and finite. Milliseconds since 1970 - // epoch, formatted as RFC-1123. - String expiresString = DateUtils.formatDate(new Date(expires)); - setResponseHeader(KEY_EXPIRES, expiresString); - } - String lastModified = cacheResult.getLastModified(); - if (lastModified != null) { - // Last modification time of the page. Passed end-to-end, but - // not used by us. - setResponseHeader(KEY_LAST_MODIFIED, lastModified); - } - String eTag = cacheResult.getETag(); - if (eTag != null) { - // Entity tag. A kind of GUID to identify identical resources. - setResponseHeader(KEY_ETAG, eTag); - } - String location = cacheResult.getLocation(); - if (location != null) { - // If valid, refers to the location of a redirect. - setResponseHeader(KEY_LOCATION, location); - } - String mimeType = cacheResult.getMimeType(); - if (mimeType == null) { - // Use a safe default MIME type when none is - // specified. "text/plain" is safe to render in the browser - // window (even if large) and won't be intepreted as anything - // that would cause execution. - mimeType = DEFAULT_MIME_TYPE; - } - String encoding = cacheResult.getEncoding(); - // Encoding may not be specified. No default. - String contentType = mimeType; - if (encoding != null && encoding.length() > 0) { - contentType += "; charset=" + encoding; - } - setResponseHeader(KEY_CONTENT_TYPE, contentType); - } - - /** - * Create a CacheResult for this URL. This enables the repsonse body - * to be sent in calls to appendCacheResult(). - * @param url The fully qualified URL to add to the cache. - * @param responseCode The response code returned for the request, e.g 200. - * @param mimeType The MIME type of the body, e.g "text/plain". - * @param encoding The encoding, e.g "utf-8". Use "" for unknown. - */ - public synchronized boolean createCacheResult( - String url, int responseCode, String mimeType, String encoding) { - if (logEnabled) - log("Making cache entry for " + url); - // Take the headers and parse them into a format needed by - // CacheManager. - Headers cacheHeaders = new Headers(); - Iterator> it = - responseHeaders.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = it.next(); - // Headers.parseHeader() expects lowercase keys. - String keyValue = entry.getKey() + ": " - + entry.getValue()[HEADERS_MAP_INDEX_VALUE]; - CharArrayBuffer buffer = new CharArrayBuffer(keyValue.length()); - buffer.append(keyValue); - // Parse it into the header container. - cacheHeaders.parseHeader(buffer); - } - cacheResult = CacheManager.createCacheFile( - url, responseCode, cacheHeaders, mimeType, true); - if (cacheResult != null) { - if (logEnabled) - log("Saving into cache"); - cacheResult.setEncoding(encoding); - cacheResultUrl = url; - return true; - } else { - log("Couldn't create cacheResult"); - return false; - } - } - - /** - * Add data from the response body to the CacheResult created with - * createCacheResult(). - * @param data A byte array of the next sequential bytes in the - * response body. - * @param bytes The number of bytes to write from the start of - * the array. - * @return True if all bytes successfully written, false on failure. - */ - public synchronized boolean appendCacheResult(byte[] data, int bytes) { - if (cacheResult == null) { - log("appendCacheResult() called without a CacheResult initialized"); - return false; - } - try { - cacheResult.getOutputStream().write(data, 0, bytes); - } catch (IOException ex) { - log("Got IOException writing cache data: " + ex); - return false; - } - return true; - } - - /** - * Save the completed CacheResult into the CacheManager. This must - * have been created first with createCacheResult(). - * @return Returns true if the entry has been successfully saved. - */ - public synchronized boolean saveCacheResult() { - if (cacheResult == null || cacheResultUrl == null) { - log("Tried to save cache result but createCacheResult not called"); - return false; - } - if (logEnabled) - log("Saving cache result"); - CacheManager.saveCacheFile(cacheResultUrl, cacheResult); - cacheResult = null; - cacheResultUrl = null; - return true; - } - - /** - * Perform an HTTP request on the network. The underlying - * HttpURLConnection is connected to the remote server and the - * response headers are received. - * @return True if the connection succeeded and headers have been - * received. False on connection failure. - */ - public boolean connectToRemote() { - synchronized (this) { - // Transfer a snapshot of our internally maintained map of request - // headers to the connection object. - applyRequestHeadersToConnection(); - // Note blocking I/O so abort() can interrupt us. - inBlockingOperation = true; - } - boolean success; - try { - if (logEnabled) - log("Connecting to remote"); - connection.connect(); - if (logEnabled) - log("Connected"); - success = true; - } catch (IOException e) { - log("Got IOException in connect(): " + e.toString()); - success = false; - } finally { - synchronized (this) { - // No longer blocking. - inBlockingOperation = false; - } - } - return success; - } - - /** - * Receive all headers from the server and populate - * responseHeaders. This converts from the slightly odd format - * returned by java.net.HttpURLConnection to a simpler - * java.util.Map. - * @return True if headers are successfully received, False on - * connection error. - */ - public synchronized boolean parseHeaders() { - responseHeaders = new HashMap(); - /* HttpURLConnection contains a null terminated list of - * key->value response pairs. If the key is null, then the value - * contains the complete status line. If both key and value are - * null for an index, we've reached the end. - */ - for (int i = 0; ; ++i) { - String key = connection.getHeaderFieldKey(i); - String value = connection.getHeaderField(i); - if (logEnabled) - log("header " + key + " -> " + value); - if (key == null && value == null) { - // End of list. - break; - } else if (key == null) { - // The pair with null key has the complete status line in - // the value, e.g "HTTP/1.0 200 OK". - responseLine = value; - } else if (value != null) { - // If key and value are non-null, this is a response pair, e.g - // "Content-Length" -> "5". Use setResponseHeader() to - // correctly deal with case-insensitivity of the key. - setResponseHeader(key, value); - } else { - // The key is non-null but value is null. Unexpected - // condition. - return false; - } - } - return true; - } - - /** - * Receive the next sequential bytes of the response body after - * successful connection. This will receive up to the size of the - * provided byte array. If there is no body, this will return 0 - * bytes on the first call after connection. - * @param buf A pre-allocated byte array to receive data into. - * @return The number of bytes from the start of the array which - * have been filled, 0 on EOF, or negative on error. - */ - public int receive(byte[] buf) { - if (inputStream == null) { - // If this is the first call, setup the InputStream. This may - // fail if there were headers, but no body returned by the - // server. - try { - inputStream = connection.getInputStream(); - } catch (IOException inputException) { - log("Failed to connect InputStream: " + inputException); - // Not unexpected. For example, 404 response return headers, - // and sometimes a body with a detailed error. Try the error - // stream. - inputStream = connection.getErrorStream(); - if (inputStream == null) { - // No error stream either. Treat as a 0 byte response. - log("No InputStream"); - return 0; // EOF. - } - } - } - synchronized (this) { - // Note blocking I/O so abort() can interrupt us. - inBlockingOperation = true; - } - int ret; - try { - int got = inputStream.read(buf); - if (got > 0) { - // Got some bytes, not EOF. - ret = got; - } else { - // EOF. - inputStream.close(); - ret = 0; - } - } catch (IOException e) { - // An abort() interrupts us by calling close() on our stream. - log("Got IOException in inputStream.read(): " + e.toString()); - ret = -1; - } finally { - synchronized (this) { - // No longer blocking. - inBlockingOperation = false; - } - } - return ret; - } - - /** - * For POST method requests, send a stream of data provided by the - * native side in repeated callbacks. - * @param data A byte array containing the data to sent, or null - * if indicating EOF. - * @param bytes The number of bytes from the start of the array to - * send, or 0 if indicating EOF. - * @return True if all bytes were successfully sent, false on error. - */ - public boolean sendPostData(byte[] data, int bytes) { - synchronized (this) { - // Note blocking I/O so abort() can interrupt us. - inBlockingOperation = true; - } - boolean success; - try { - OutputStream outputStream = connection.getOutputStream(); - if (data == null && bytes == 0) { - outputStream.close(); - } else { - outputStream.write(data, 0, bytes); - } - success = true; - } catch (IOException e) { - log("Got IOException in post: " + e.toString()); - success = false; - } finally { - synchronized (this) { - // No longer blocking. - inBlockingOperation = false; - } - } - return success; - } -} diff --git a/core/java/android/webkit/gears/IGearsDialogService.java b/core/java/android/webkit/gears/IGearsDialogService.java deleted file mode 100644 index 82a3bd97f23000ee765dc7a7db69af2ba97208e0..0000000000000000000000000000000000000000 --- a/core/java/android/webkit/gears/IGearsDialogService.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * This file is auto-generated. DO NOT MODIFY. - * Original file: android.webkit.gears/IGearsDialogService.aidl - */ -package android.webkit.gears; -import java.lang.String; -import android.os.RemoteException; -import android.os.IBinder; -import android.os.IInterface; -import android.os.Binder; -import android.os.Parcel; -public interface IGearsDialogService extends android.os.IInterface -{ -/** Local-side IPC implementation stub class. */ -public static abstract class Stub extends android.os.Binder implements android.webkit.gears.IGearsDialogService -{ -private static final java.lang.String DESCRIPTOR = "com.android.browser.IGearsDialogService"; -/** Construct the stub at attach it to the interface. */ -public Stub() -{ -this.attachInterface(this, DESCRIPTOR); -} -/** - * Cast an IBinder object into an IGearsDialogService interface, - * generating a proxy if needed. - */ -public static android.webkit.gears.IGearsDialogService asInterface(android.os.IBinder obj) -{ -if ((obj==null)) { -return null; -} -android.webkit.gears.IGearsDialogService in = (android.webkit.gears.IGearsDialogService)obj.queryLocalInterface(DESCRIPTOR); -if ((in!=null)) { -return in; -} -return new android.webkit.gears.IGearsDialogService.Stub.Proxy(obj); -} -public android.os.IBinder asBinder() -{ -return this; -} -public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException -{ -switch (code) -{ -case INTERFACE_TRANSACTION: -{ -reply.writeString(DESCRIPTOR); -return true; -} -case TRANSACTION_showDialog: -{ -data.enforceInterface(DESCRIPTOR); -java.lang.String _arg0; -_arg0 = data.readString(); -java.lang.String _arg1; -_arg1 = data.readString(); -boolean _arg2; -_arg2 = (0!=data.readInt()); -java.lang.String _result = this.showDialog(_arg0, _arg1, _arg2); -reply.writeNoException(); -reply.writeString(_result); -return true; -} -} -return super.onTransact(code, data, reply, flags); -} -private static class Proxy implements android.webkit.gears.IGearsDialogService -{ -private android.os.IBinder mRemote; -Proxy(android.os.IBinder remote) -{ -mRemote = remote; -} -public android.os.IBinder asBinder() -{ -return mRemote; -} -public java.lang.String getInterfaceDescriptor() -{ -return DESCRIPTOR; -} -public java.lang.String showDialog(java.lang.String htmlContent, java.lang.String dialogArguments, boolean inSettings) throws android.os.RemoteException -{ -android.os.Parcel _data = android.os.Parcel.obtain(); -android.os.Parcel _reply = android.os.Parcel.obtain(); -java.lang.String _result; -try { -_data.writeInterfaceToken(DESCRIPTOR); -_data.writeString(htmlContent); -_data.writeString(dialogArguments); -_data.writeInt(((inSettings)?(1):(0))); -mRemote.transact(Stub.TRANSACTION_showDialog, _data, _reply, 0); -_reply.readException(); -_result = _reply.readString(); -} -finally { -_reply.recycle(); -_data.recycle(); -} -return _result; -} -} -static final int TRANSACTION_showDialog = (IBinder.FIRST_CALL_TRANSACTION + 0); -} -public java.lang.String showDialog(java.lang.String htmlContent, java.lang.String dialogArguments, boolean inSettings) throws android.os.RemoteException; -} diff --git a/core/java/android/webkit/gears/UrlInterceptHandlerGears.java b/core/java/android/webkit/gears/UrlInterceptHandlerGears.java index 288240ea8e2ace367bb167c65fbf2c5841c6a461..43104bf293e3664ac6c9fdd5df236a5394573192 100644 --- a/core/java/android/webkit/gears/UrlInterceptHandlerGears.java +++ b/core/java/android/webkit/gears/UrlInterceptHandlerGears.java @@ -25,16 +25,14 @@ package android.webkit.gears; -import android.net.http.Headers; import android.util.Log; -import android.webkit.CacheManager; import android.webkit.CacheManager.CacheResult; import android.webkit.Plugin; +import android.webkit.PluginData; import android.webkit.UrlInterceptRegistry; import android.webkit.UrlInterceptHandler; import android.webkit.WebView; -import org.apache.http.impl.cookie.DateUtils; import org.apache.http.util.CharArrayBuffer; import java.io.*; @@ -53,22 +51,16 @@ public class UrlInterceptHandlerGears implements UrlInterceptHandler { private static final String LOG_TAG = "Gears-J"; /** Buffer size for reading/writing streams. */ private static final int BUFFER_SIZE = 4096; - /** - * Number of milliseconds to expire LocalServer temporary entries in - * the browser's cache. Somewhat arbitrarily chosen as a compromise - * between being a) long enough not to expire during page load and - * b) short enough to evict entries during a session. */ - private static final int CACHE_EXPIRY_MS = 60000; // 1 minute. /** Enable/disable all logging in this class. */ private static boolean logEnabled = false; /** The unmodified (case-sensitive) key in the headers map is the * same index as used by HttpRequestAndroid. */ public static final int HEADERS_MAP_INDEX_KEY = - HttpRequestAndroid.HEADERS_MAP_INDEX_KEY; + ApacheHttpRequestAndroid.HEADERS_MAP_INDEX_KEY; /** The associated value in the headers map is the same index as * used by HttpRequestAndroid. */ public static final int HEADERS_MAP_INDEX_VALUE = - HttpRequestAndroid.HEADERS_MAP_INDEX_VALUE; + ApacheHttpRequestAndroid.HEADERS_MAP_INDEX_VALUE; /** * Object passed to the native side, containing information about @@ -140,6 +132,8 @@ public class UrlInterceptHandlerGears implements UrlInterceptHandler { private String encoding; // The stream which contains the body when read(). private InputStream inputStream; + // The length of the content body. + private long contentLength; /** * Initialize members using an in-memory array to return the body. @@ -160,6 +154,7 @@ public class UrlInterceptHandlerGears implements UrlInterceptHandler { this.mimeType = mimeType; this.encoding = encoding; // Setup a stream to read out of the byte array. + this.contentLength = body.length; this.inputStream = new ByteArrayInputStream(body); } @@ -185,7 +180,9 @@ public class UrlInterceptHandlerGears implements UrlInterceptHandler { this.encoding = encoding; try { // Setup a stream to read out of a file on disk. - this.inputStream = new FileInputStream(new File(path)); + File file = new File(path); + this.contentLength = file.length(); + this.inputStream = new FileInputStream(file); return true; } catch (java.io.FileNotFoundException ex) { log("File not found: " + path); @@ -274,6 +271,13 @@ public class UrlInterceptHandlerGears implements UrlInterceptHandler { public InputStream getInputStream() { return inputStream; } + + /** + * @return The length of the response body. + */ + public long getContentLength() { + return contentLength; + } } /** @@ -319,44 +323,32 @@ public class UrlInterceptHandlerGears implements UrlInterceptHandler { UrlInterceptRegistry.unregisterHandler(this); } - /** - * Copy the entire InputStream to OutputStream. - * @param inputStream The stream to read from. - * @param outputStream The stream to write to. - * @return True if the entire stream copied successfully, false on error. - */ - private boolean copyStream(InputStream inputStream, - OutputStream outputStream) { - try { - // Temporary buffer to copy stream through. - byte[] buf = new byte[BUFFER_SIZE]; - for (;;) { - // Read up to BUFFER_SIZE bytes. - int bytes = inputStream.read(buf); - if (bytes < 0) { - break; - } - // Write the number of bytes we just read. - outputStream.write(buf, 0, bytes); - } - } catch (IOException ex) { - log("Got IOException copying stream: " + ex); - return false; + /** + * Given an URL, returns the CacheResult which contains the + * surrogate response for the request, or null if the handler is + * not interested. + * + * @param url URL string. + * @param headers The headers associated with the request. May be null. + * @return The CacheResult containing the surrogate response. + * @Deprecated Use PluginData getPluginData(String url, + * Map headers); instead + */ + @Deprecated + public CacheResult service(String url, Map headers) { + throw new UnsupportedOperationException("unimplemented"); } - return true; - } /** - * Given an URL, returns a CacheResult which contains the response - * for the request. This implements the UrlInterceptHandler interface. + * Given an URL, returns a PluginData instance which contains the + * response for the request. This implements the UrlInterceptHandler + * interface. * - * @param url The fully qualified URL being requested. + * @param url The fully qualified URL being requested. * @param requestHeaders The request headers for this URL. - * @return If a response can be crafted, a CacheResult initialized - * to return the surrogate response. If this URL cannot - * be serviced, returns null. + * @return a PluginData object. */ - public CacheResult service(String url, Map requestHeaders) { + public PluginData getPluginData(String url, Map requestHeaders) { // Thankfully the browser does call us with case-sensitive // headers. We just need to map it case-insensitive. Map lowercaseRequestHeaders = @@ -374,86 +366,10 @@ public class UrlInterceptHandlerGears implements UrlInterceptHandler { // No result for this URL. return null; } - // Translate the ServiceResponse to a CacheResult. - // Translate http -> gears, https -> gearss, so we don't overwrite - // existing entries. - String gearsUrl = "gears" + url.substring("http".length()); - // Set the result to expire, so that entries don't pollute the - // browser's cache for too long. - long now_ms = System.currentTimeMillis(); - String expires = DateUtils.formatDate(new Date(now_ms + CACHE_EXPIRY_MS)); - response.setResponseHeader(HttpRequestAndroid.KEY_EXPIRES, expires); - // The browser is only interested in a small subset of headers, - // contained in a Headers object. Iterate the map of all headers - // and add them to Headers. - Headers headers = new Headers(); - Iterator> responseHeadersIt = - response.getResponseHeaders().entrySet().iterator(); - while (responseHeadersIt.hasNext()) { - Map.Entry entry = responseHeadersIt.next(); - // Headers.parseHeader() expects lowercase keys. - String keyValue = entry.getKey() + ": " - + entry.getValue()[HEADERS_MAP_INDEX_VALUE]; - CharArrayBuffer buffer = new CharArrayBuffer(keyValue.length()); - buffer.append(keyValue); - // Parse it into the header container. - headers.parseHeader(buffer); - } - CacheResult cacheResult = CacheManager.createCacheFile( - gearsUrl, - response.getStatusCode(), - headers, - response.getMimeType(), - true); // forceCache - - if (cacheResult == null) { - // With the no-cache policy we could end up - // with a null result - return null; - } - - // Set encoding if specified. - String encoding = response.getEncoding(); - if (encoding != null) { - cacheResult.setEncoding(encoding); - } - // Copy the response body to the CacheResult. This handles all - // combinations of memory vs on-disk on both sides. - InputStream inputStream = response.getInputStream(); - OutputStream outputStream = cacheResult.getOutputStream(); - boolean copied = copyStream(inputStream, outputStream); - // Close the input and output streams to relinquish their - // resources earlier. - try { - inputStream.close(); - } catch (IOException ex) { - log("IOException closing InputStream: " + ex); - copied = false; - } - try { - outputStream.close(); - } catch (IOException ex) { - log("IOException closing OutputStream: " + ex); - copied = false; - } - if (!copied) { - log("copyStream of local result failed"); - return null; - } - // Save the entry into the browser's cache. - CacheManager.saveCacheFile(gearsUrl, cacheResult); - // Get it back from the cache, this time properly initialized to - // be used for input. - cacheResult = CacheManager.getCacheFile(gearsUrl, null); - if (cacheResult != null) { - log("Returning surrogate result"); - return cacheResult; - } else { - // Not an expected condition, but handle gracefully. Perhaps out - // of memory or disk? - Log.e(LOG_TAG, "Lost CacheResult between save and get. Can't serve.\n"); - return null; - } + return new PluginData(response.getInputStream(), + response.getContentLength(), + response.getResponseHeaders(), + response.getStatusCode()); } /** diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java index 19ec77d89a6077ee69f5bb5eb010f87e3b3bce5a..bd4bba8f57bff6a5fd90b33aa93c0813f775ed47 100644 --- a/core/java/android/widget/AbsListView.java +++ b/core/java/android/widget/AbsListView.java @@ -17,7 +17,6 @@ package android.widget; import android.content.Context; -import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; @@ -28,9 +27,11 @@ import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.text.Editable; +import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.Gravity; +import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; @@ -40,7 +41,9 @@ import android.view.ViewConfiguration; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.ViewTreeObserver; -import android.view.WindowManagerImpl; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.view.inputmethod.InputMethodManager; import android.view.ContextMenu.ContextMenuInfo; import com.android.internal.R; @@ -369,7 +372,6 @@ public abstract class AbsListView extends AdapterView implements Te private int mLastTouchMode = TOUCH_MODE_UNKNOWN; - // TODO: REMOVE WHEN WE'RE DONE WITH PROFILING private static final boolean PROFILE_SCROLLING = false; private boolean mScrollProfilingStarted = false; @@ -423,6 +425,10 @@ public abstract class AbsListView extends AdapterView implements Te */ private FastScroller mFastScroller; + private int mTouchSlop; + + private float mDensityScale; + /** * Interface definition for a callback to be invoked when the list or grid * has been scrolled. @@ -558,6 +564,15 @@ public abstract class AbsListView extends AdapterView implements Te public boolean isFastScrollEnabled() { return mFastScrollEnabled; } + + /** + * If fast scroll is visible, then don't draw the vertical scrollbar. + * @hide + */ + @Override + protected boolean isVerticalScrollBarHidden() { + return mFastScroller != null && mFastScroller.isVisible(); + } /** * When smooth scrollbar is enabled, the position and size of the scrollbar thumb @@ -696,6 +711,9 @@ public abstract class AbsListView extends AdapterView implements Te setWillNotDraw(false); setAlwaysDrawnWithCacheEnabled(false); setScrollingCacheEnabled(true); + + mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop(); + mDensityScale = getContext().getResources().getDisplayMetrics().density; } private void useDefaultSelector() { @@ -877,15 +895,22 @@ public abstract class AbsListView extends AdapterView implements Te mSyncMode = SYNC_FIRST_POSITION; } - // Don't restore the type filter window when there is no keyboard - int keyboardHidden = getContext().getResources().getConfiguration().keyboardHidden; - if (keyboardHidden != Configuration.KEYBOARDHIDDEN_YES) { - String filterText = ss.filter; - setFilterText(filterText); - } + setFilterText(ss.filter); + requestLayout(); } + private boolean acceptFilter() { + if (!mTextFilterEnabled || !(getAdapter() instanceof Filterable) || + ((Filterable) getAdapter()).getFilter() == null) { + return false; + } + final Context context = mContext; + final InputMethodManager inputManager = (InputMethodManager) + context.getSystemService(Context.INPUT_METHOD_SERVICE); + return !inputManager.isFullscreenMode(); + } + /** * Sets the initial value for the text filter. * @param filterText The text to use for the filter. @@ -893,7 +918,8 @@ public abstract class AbsListView extends AdapterView implements Te * @see #setTextFilterEnabled */ public void setFilterText(String filterText) { - if (mTextFilterEnabled && filterText != null && filterText.length() > 0) { + // TODO: Should we check for acceptFilter()? + if (mTextFilterEnabled && !TextUtils.isEmpty(filterText)) { createTextFilter(false); // This is going to call our listener onTextChanged, but we might not // be ready to bring up a window yet @@ -913,6 +939,18 @@ public abstract class AbsListView extends AdapterView implements Te } } + /** + * Returns the list's text filter, if available. + * @return the list's text filter or null if filtering isn't enabled + * @hide pending API Council approval + */ + public CharSequence getTextFilter() { + if (mTextFilterEnabled && mTextFilter != null) { + return mTextFilter.getText(); + } + return null; + } + @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); @@ -944,6 +982,18 @@ public abstract class AbsListView extends AdapterView implements Te mSelectorRect.setEmpty(); invalidate(); } + + /** + * The list is empty and we need to change the layout, so *really* clear everything out. + * @hide - for AutoCompleteTextView & SearchDialog only + */ + /* package */ void resetListAndClearViews() { + rememberSyncState(); + removeAllViewsInLayout(); + mRecycler.clear(); + mRecycler.setViewTypeCount(mAdapter.getViewTypeCount()); + requestLayout(); + } @Override protected int computeVerticalScrollExtent() { @@ -1063,6 +1113,24 @@ public abstract class AbsListView extends AdapterView implements Te mInLayout = false; } + /** + * @hide + */ + @Override + protected boolean setFrame(int left, int top, int right, int bottom) { + final boolean changed = super.setFrame(left, top, right, bottom); + + // Reposition the popup when the frame has changed. This includes + // translating the widget, not just changing its dimension. The + // filter popup needs to follow the widget. + if (mFiltered && changed && getWindowVisibility() == View.VISIBLE && mPopup != null && + mPopup.isShowing()) { + positionPopup(); + } + + return changed; + } + protected void layoutChildren() { } @@ -1366,7 +1434,10 @@ public abstract class AbsListView extends AdapterView implements Te final View v = getChildAt(mSelectedPosition - mFirstPosition); - if (v != null) v.setPressed(true); + if (v != null) { + if (v.hasFocusable()) return; + v.setPressed(true); + } setPressed(true); final boolean longClickable = isLongClickable(); @@ -1610,6 +1681,9 @@ public abstract class AbsListView extends AdapterView implements Te mContextMenuInfo = createContextMenuInfo(child, longPressPosition, longPressId); handled = super.showContextMenuForChild(AbsListView.this); } + if (handled) { + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + } return handled; } @@ -1758,8 +1832,7 @@ public abstract class AbsListView extends AdapterView implements Te // Check if we have moved far enough that it looks more like a // scroll than a tap final int distance = Math.abs(deltaY); - int touchSlop = ViewConfiguration.getTouchSlop(); - if (distance > touchSlop) { + if (distance > mTouchSlop) { createScrollingCache(); mTouchMode = TOUCH_MODE_SCROLL; mMotionCorrection = deltaY; @@ -1979,8 +2052,9 @@ public abstract class AbsListView extends AdapterView implements Te velocityTracker.computeCurrentVelocity(1000); int initialVelocity = (int)velocityTracker.getYVelocity(); - if ((Math.abs(initialVelocity) > ViewConfiguration.getMinimumFlingVelocity()) && - (getChildCount() > 0)){ + if ((Math.abs(initialVelocity) > + ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) && + (getChildCount() > 0)) { if (mFlingRunnable == null) { mFlingRunnable = new FlingRunnable(); } @@ -2571,10 +2645,12 @@ public abstract class AbsListView extends AdapterView implements Te clearScrollingCache(); mSpecificTop = selectedTop; selectedPos = lookForSelectablePosition(selectedPos, down); - if (selectedPos >= 0) { + if (selectedPos >= firstPosition && selectedPos <= getLastVisiblePosition()) { mLayoutMode = LAYOUT_SPECIFIC; setSelectionInt(selectedPos); invokeOnItemScrollListener(); + } else { + selectedPos = INVALID_POSITION; } reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); @@ -2711,17 +2787,28 @@ public abstract class AbsListView extends AdapterView implements Te private void showPopup() { // Make sure we have a window before showing the popup if (getWindowVisibility() == View.VISIBLE) { - int screenHeight = WindowManagerImpl.getDefault().getDefaultDisplay().getHeight(); - final int[] xy = new int[2]; - getLocationOnScreen(xy); - int bottomGap = screenHeight - xy[1] - getHeight() + 20; - mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, - xy[0], bottomGap); + createTextFilter(true); + positionPopup(); // Make sure we get focus if we are showing the popup checkFocus(); } } + private void positionPopup() { + int screenHeight = getResources().getDisplayMetrics().heightPixels; + final int[] xy = new int[2]; + getLocationOnScreen(xy); + // TODO: The 20 below should come from the theme and be expressed in dip + // TODO: And the gravity should be defined in the theme as well + final int bottomGap = screenHeight - xy[1] - getHeight() + (int) (mDensityScale * 20); + if (!mPopup.isShowing()) { + mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, + xy[0], bottomGap); + } else { + mPopup.update(xy[0], bottomGap, -1, -1); + } + } + /** * What is the distance between the source and destination rectangles given the direction of * focus navigation between them? The direction basically helps figure out more quickly what is @@ -2783,8 +2870,7 @@ public abstract class AbsListView extends AdapterView implements Te * @return True if the text filter handled the event, false otherwise. */ boolean sendToTextFilter(int keyCode, int count, KeyEvent event) { - if (!mTextFilterEnabled || !(getAdapter() instanceof Filterable) || - ((Filterable) getAdapter()).getFilter() == null) { + if (!acceptFilter()) { return false; } @@ -2839,6 +2925,30 @@ public abstract class AbsListView extends AdapterView implements Te return handled; } + /** + * Return an InputConnection for editing of the filter text. + */ + @Override + public InputConnection onCreateInputConnection(EditorInfo outAttrs) { + if (isTextFilterEnabled()) { + // XXX we need to have the text filter created, so we can get an + // InputConnection to proxy to. Unfortunately this means we pretty + // much need to make it as soon as a list view gets focus. + createTextFilter(false); + return mTextFilter.onCreateInputConnection(outAttrs); + } + return null; + } + + /** + * For filtering we proxy an input connection to an internal text editor, + * and this allows the proxying to happen. + */ + @Override + public boolean checkInputConnectionProxy(View view) { + return view == mTextFilter; + } + /** * Creates the window for the text filter and populates it with an EditText field; * @@ -2848,13 +2958,19 @@ public abstract class AbsListView extends AdapterView implements Te if (mPopup == null) { Context c = getContext(); PopupWindow p = new PopupWindow(c); - LayoutInflater layoutInflater = (LayoutInflater) c - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater layoutInflater = (LayoutInflater) + c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mTextFilter = (EditText) layoutInflater.inflate( com.android.internal.R.layout.typing_filter, null); + // For some reason setting this as the "real" input type changes + // the text view in some way that it doesn't work, and I don't + // want to figure out why this is. + mTextFilter.setRawInputType(EditorInfo.TYPE_CLASS_TEXT + | EditorInfo.TYPE_TEXT_VARIATION_FILTER); mTextFilter.addTextChangedListener(this); p.setFocusable(false); p.setTouchable(false); + p.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); p.setContentView(mTextFilter); p.setWidth(LayoutParams.WRAP_CONTENT); p.setHeight(LayoutParams.WRAP_CONTENT); @@ -2915,7 +3031,7 @@ public abstract class AbsListView extends AdapterView implements Te * filtering as the text changes. */ public void onTextChanged(CharSequence s, int start, int before, int count) { - if (mPopup != null) { + if (mPopup != null && isTextFilterEnabled()) { int length = s.length(); boolean showing = mPopup.isShowing(); if (!showing && length > 0) { @@ -3070,6 +3186,14 @@ public abstract class AbsListView extends AdapterView implements Te */ int viewType; + /** + * When this boolean is set, the view has been added to the AbsListView + * at least once. It is used to know whether headers/footers have already + * been added to the list view and whether they should be treated as + * recycled views or not. + */ + boolean recycledHeaderFooter; + public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } @@ -3203,7 +3327,7 @@ public abstract class AbsListView extends AdapterView implements Te if (lp != null && lp.viewType != AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { // Note: We do place AdapterView.ITEM_VIEW_TYPE_IGNORE in active views. // However, we will NOT place them into scrap views. - activeViews[i] = getChildAt(i); + activeViews[i] = child; } } } diff --git a/core/java/android/widget/AbsSeekBar.java b/core/java/android/widget/AbsSeekBar.java index 9ebfa8656688ac7c683d3fcfceacb15614b46957..37d5bfeee7b88878b4c410417786f573368cb1ca 100644 --- a/core/java/android/widget/AbsSeekBar.java +++ b/core/java/android/widget/AbsSeekBar.java @@ -40,9 +40,15 @@ public abstract class AbsSeekBar extends ProgressBar { * Whether this is user seekable. */ boolean mIsUserSeekable = true; + + /** + * On key presses (right or left), the amount to increment/decrement the + * progress. + */ + private int mKeyProgressIncrement = 1; private static final int NO_ALPHA = 0xFF; - float mDisabledAlpha; + private float mDisabledAlpha; public AbsSeekBar(Context context) { super(context); @@ -101,6 +107,39 @@ public abstract class AbsSeekBar extends ProgressBar { invalidate(); } + /** + * Sets the amount of progress changed via the arrow keys. + * + * @param increment The amount to increment or decrement when the user + * presses the arrow keys. + */ + public void setKeyProgressIncrement(int increment) { + mKeyProgressIncrement = increment < 0 ? -increment : increment; + } + + /** + * Returns the amount of progress changed via the arrow keys. + *

          + * By default, this will be a value that is derived from the max progress. + * + * @return The amount to increment or decrement when the user presses the + * arrow keys. This will be positive. + */ + public int getKeyProgressIncrement() { + return mKeyProgressIncrement; + } + + @Override + public synchronized void setMax(int max) { + super.setMax(max); + + if ((mKeyProgressIncrement == 0) || (getMax() / mKeyProgressIncrement > 20)) { + // It will take the user too long to change this via keys, change it + // to something more reasonable + setKeyProgressIncrement(Math.max(1, Math.round((float) getMax() / 20))); + } + } + @Override protected boolean verifyDrawable(Drawable who) { return who == mThumb || super.verifyDrawable(who); @@ -316,12 +355,12 @@ public abstract class AbsSeekBar extends ProgressBar { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: if (progress <= 0) break; - setProgress(progress - 1, true); + setProgress(progress - mKeyProgressIncrement, true); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (progress >= getMax()) break; - setProgress(progress + 1, true); + setProgress(progress + mKeyProgressIncrement, true); return true; } diff --git a/core/java/android/widget/Adapter.java b/core/java/android/widget/Adapter.java index e952dd5ed01049ca41ec0ec5470b22d431f7b156..f2b3e2ac917fe78bf00932635ebfb98520d9e630 100644 --- a/core/java/android/widget/Adapter.java +++ b/core/java/android/widget/Adapter.java @@ -116,7 +116,7 @@ public interface Adapter { * can be converted to the other in {@link #getView}. Note: Integers must be in the * range 0 to {@link #getViewTypeCount} - 1. {@link #IGNORE_ITEM_VIEW_TYPE} can * also be returned. - * @see IGNORE_ITEM_VIEW_TYPE + * @see #IGNORE_ITEM_VIEW_TYPE */ int getItemViewType(int position); diff --git a/core/java/android/widget/AnalogClock.java b/core/java/android/widget/AnalogClock.java index fbb010515801a5a28568132f1b66c0bc5bf80722..f847bc399b5a97237ae237ca4ca1ef649c0f5cbc 100644 --- a/core/java/android/widget/AnalogClock.java +++ b/core/java/android/widget/AnalogClock.java @@ -28,6 +28,7 @@ import android.os.Handler; import android.text.format.Time; import android.util.AttributeSet; import android.view.View; +import android.widget.RemoteViews.RemoteView; import java.util.TimeZone; @@ -35,6 +36,7 @@ import java.util.TimeZone; * This widget display an analogic clock with two hands for hours and * minutes. */ +@RemoteView public class AnalogClock extends View { private Time mCalendar; @@ -46,7 +48,6 @@ public class AnalogClock extends View { private int mDialHeight; private boolean mAttached; - private long mLastTime; private final Handler mHandler = new Handler(); private float mMinutes; @@ -94,7 +95,6 @@ public class AnalogClock extends View { protected void onAttachedToWindow() { super.onAttachedToWindow(); - onTimeChanged(); if (!mAttached) { mAttached = true; IntentFilter filter = new IntentFilter(); @@ -105,6 +105,15 @@ public class AnalogClock extends View { getContext().registerReceiver(mIntentReceiver, filter, null, mHandler); } + + // NOTE: It's safe to do these after registering the receiver since the receiver always runs + // in the main thread, therefore the receiver can't run before this method returns. + + // The time zone may have changed while the receiver wasn't registered, so update the Time + mCalendar = new Time(); + + // Make sure we update to the current time + onTimeChanged(); } @Override @@ -210,9 +219,7 @@ public class AnalogClock extends View { } private void onTimeChanged() { - long time = System.currentTimeMillis(); - mCalendar.set(time); - mLastTime = time; + mCalendar.setToNow(); int hour = mCalendar.hour; int minute = mCalendar.minute; @@ -229,8 +236,6 @@ public class AnalogClock extends View { if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) { String tz = intent.getStringExtra("time-zone"); mCalendar = new Time(TimeZone.getTimeZone(tz).getID()); - } else { - mCalendar = new Time(); } onTimeChanged(); diff --git a/core/java/android/widget/ArrayAdapter.java b/core/java/android/widget/ArrayAdapter.java index c65a3ceaf4ef6efa34f6f0ee7028107abe663074..c28210df6864a328195c268487b1d8d17556a402 100644 --- a/core/java/android/widget/ArrayAdapter.java +++ b/core/java/android/widget/ArrayAdapter.java @@ -25,6 +25,8 @@ import android.view.ViewGroup; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Comparator; +import java.util.Collections; /** * A ListAdapter that manages a ListView backed by an array of arbitrary @@ -226,6 +228,17 @@ public class ArrayAdapter extends BaseAdapter implements Filterable { if (mNotifyOnChange) notifyDataSetChanged(); } + /** + * Sorts the content of this adapter using the specified comparator. + * + * @param comparator The comparator used to sort the objects contained + * in this adapter. + */ + public void sort(Comparator comparator) { + Collections.sort(mObjects, comparator); + if (mNotifyOnChange) notifyDataSetChanged(); + } + /** * {@inheritDoc} */ diff --git a/core/java/android/widget/AutoCompleteTextView.java b/core/java/android/widget/AutoCompleteTextView.java index 7d5290175578700666d26f607371d53decb40dd2..e61354105e8e5b638e90fe254d6bad7adb40bf7d 100644 --- a/core/java/android/widget/AutoCompleteTextView.java +++ b/core/java/android/widget/AutoCompleteTextView.java @@ -78,6 +78,8 @@ import com.android.internal.R; * @attr ref android.R.styleable#AutoCompleteTextView_completionThreshold * @attr ref android.R.styleable#AutoCompleteTextView_completionHintView * @attr ref android.R.styleable#AutoCompleteTextView_dropDownSelector + * @attr ref android.R.styleable#AutoCompleteTextView_dropDownAnchor + * @attr ref android.R.styleable#AutoCompleteTextView_dropDownWidth */ public class AutoCompleteTextView extends EditText implements Filter.FilterListener { static final boolean DEBUG = false; @@ -96,6 +98,9 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe private DropDownListView mDropDownList; private int mDropDownVerticalOffset; private int mDropDownHorizontalOffset; + private int mDropDownAnchorId; + private View mDropDownAnchorView; // view is retrieved lazily from id once needed + private int mDropDownWidth; private Drawable mDropDownListHighlight; @@ -110,8 +115,14 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe private Validator mValidator = null; + private boolean mBlockCompletion; + private AutoCompleteTextView.ListSelectorHider mHideSelector; + // Indicates whether this AutoCompleteTextView is attached to a window or not + // The widget is attached to a window when mAttachCount > 0 + private int mAttachCount; + public AutoCompleteTextView(Context context) { this(context, null); } @@ -141,23 +152,29 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe a.getDimension(R.styleable.AutoCompleteTextView_dropDownVerticalOffset, 0.0f); mDropDownHorizontalOffset = (int) a.getDimension(R.styleable.AutoCompleteTextView_dropDownHorizontalOffset, 0.0f); + + // Get the anchor's id now, but the view won't be ready, so wait to actually get the + // view and store it in mDropDownAnchorView lazily in getDropDownAnchorView later. + // Defaults to NO_ID, in which case the getDropDownAnchorView method will simply return + // this TextView, as a default anchoring point. + mDropDownAnchorId = a.getResourceId(R.styleable.AutoCompleteTextView_dropDownAnchor, + View.NO_ID); + + // For dropdown width, the developer can specify a specific width, or FILL_PARENT + // (for full screen width) or WRAP_CONTENT (to match the width of the anchored view). + mDropDownWidth = a.getLayoutDimension(R.styleable.AutoCompleteTextView_dropDownWidth, + ViewGroup.LayoutParams.WRAP_CONTENT); mHintResource = a.getResourceId(R.styleable.AutoCompleteTextView_completionHintView, R.layout.simple_dropdown_hint); - // A little trickiness for backwards compatibility: if the app - // didn't specify an explicit content type, then we will fill in the - // auto complete flag for them. - int contentType = a.getInt( - R.styleable.AutoCompleteTextView_inputType, - EditorInfo.TYPE_NULL); - if (contentType == EditorInfo.TYPE_NULL) { - contentType = getInputType(); - if ((contentType&EditorInfo.TYPE_MASK_CLASS) - == EditorInfo.TYPE_CLASS_TEXT) { - contentType |= EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE; - setRawInputType(contentType); - } + // Always turn on the auto complete input type flag, since it + // makes no sense to use this widget without it. + int inputType = getInputType(); + if ((inputType&EditorInfo.TYPE_MASK_CLASS) + == EditorInfo.TYPE_CLASS_TEXT) { + inputType |= EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE; + setRawInputType(inputType); } a.recycle(); @@ -187,6 +204,49 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe public void setCompletionHint(CharSequence hint) { mHintText = hint; } + + /** + *

          Returns the current width for the auto-complete drop down list. This can + * be a fixed width, or {@link ViewGroup.LayoutParams#FILL_PARENT} to fill the screen, or + * {@link ViewGroup.LayoutParams#WRAP_CONTENT} to fit the width of its anchor view.

          + * + * @return the width for the drop down list + */ + public int getDropDownWidth() { + return mDropDownWidth; + } + + /** + *

          Sets the current width for the auto-complete drop down list. This can + * be a fixed width, or {@link ViewGroup.LayoutParams#FILL_PARENT} to fill the screen, or + * {@link ViewGroup.LayoutParams#WRAP_CONTENT} to fit the width of its anchor view.

          + * + * @param width the width to use + */ + public void setDropDownWidth(int width) { + mDropDownWidth = width; + } + + /** + *

          Returns the id for the view that the auto-complete drop down list is anchored to.

          + * + * @return the view's id, or {@link View#NO_ID} if none specified + */ + public int getDropDownAnchor() { + return mDropDownAnchorId; + } + + /** + *

          Sets the view to which the auto-complete drop down list should anchor. The view + * corresponding to this id will not be loaded until the next time it is needed to avoid + * loading a view which is not yet instantiated.

          + * + * @param id the id to anchor the drop down list view to + */ + public void setDropDownAnchor(int id) { + mDropDownAnchorId = id; + mDropDownAnchorView = null; + } /** *

          Returns the number of characters the user must type before the drop @@ -300,6 +360,15 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe /** *

          Changes the list of data used for auto completion. The provided list * must be a filterable list adapter.

          + * + *

          The caller is still responsible for managing any resources used by the adapter. + * Notably, when the AutoCompleteTextView is closed or released, the adapter is not notified. + * A common case is the use of {@link android.widget.CursorAdapter}, which + * contains a {@link android.database.Cursor} that must be closed. This can be done + * automatically (see + * {@link android.app.Activity#startManagingCursor(android.database.Cursor) + * startManagingCursor()}), + * or by manually closing the cursor when the AutoCompleteTextView is dismissed.

          * * @param adapter the adapter holding the auto completion data * @@ -368,7 +437,10 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe && keyCode != KeyEvent.KEYCODE_DPAD_CENTER))) { int curIndex = mDropDownList.getSelectedItemPosition(); boolean consumed; - if (keyCode == KeyEvent.KEYCODE_DPAD_UP && curIndex <= 0) { + final boolean below = !mPopup.isAboveAnchor(); + if ((below && keyCode == KeyEvent.KEYCODE_DPAD_UP && curIndex <= 0) || + (!below && keyCode == KeyEvent.KEYCODE_DPAD_DOWN && curIndex >= + mDropDownList.getAdapter().getCount() - 1)) { // When the selection is at the top, we block the key // event to prevent focus from moving. mDropDownList.hideSelector(); @@ -389,14 +461,6 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe // by ensuring it has focus and getting its window out // of touch mode. mDropDownList.requestFocusFromTouch(); - if (false) { - // Update whether the pop-up is in front of or behind - // the input method, depending on whether the user has - // moved down in it. - mPopup.setInputMethodMode(curIndex > 0 - ? PopupWindow.INPUT_METHOD_NOT_NEEDED - : PopupWindow.INPUT_METHOD_NEEDED); - } mPopup.update(); switch (keyCode) { @@ -409,13 +473,15 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe return true; } } else { - if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { + if (below && keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { // when the selection is at the bottom, we block the // event to avoid going to the next focusable widget Adapter adapter = mDropDownList.getAdapter(); if (adapter != null && curIndex == adapter.getCount() - 1) { return true; } + } else if (!below && keyCode == KeyEvent.KEYCODE_DPAD_UP && curIndex == 0) { + return true; } } } @@ -430,6 +496,10 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe boolean handled = super.onKeyDown(keyCode, event); mLastKeyCode = KeyEvent.KEYCODE_UNKNOWN; + if (handled && isPopupShowing() && mDropDownList != null) { + clearListSelection(); + } + return handled; } @@ -462,6 +532,8 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } void doBeforeTextChanged() { + if (mBlockCompletion) return; + // when text is changed, inserted or deleted, we attempt to show // the drop down mOpenBefore = isPopupShowing(); @@ -469,6 +541,8 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } void doAfterTextChanged() { + if (mBlockCompletion) return; + // if the list was open before the keystroke, but closed afterwards, // then something in the keystroke processing (an input filter perhaps) // called performCompletion() and we shouldn't do any more processing. @@ -555,6 +629,16 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe return ListView.INVALID_POSITION; } + /** + * We're changing the adapter and its views so really, really clear everything out + * @hide - for SearchDialog only + */ + public void resetListAndClearViews() { + if (mDropDownList != null) { + mDropDownList.resetListAndClearViews(); + } + } + /** *

          Starts filtering the content of the drop down list. The filtering * pattern is the content of the edit box. Subclasses should override this @@ -579,9 +663,13 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe performCompletion(null, -1, -1); } - @Override public void onCommitCompletion(CompletionInfo completion) { + @Override + public void onCommitCompletion(CompletionInfo completion) { if (isPopupShowing()) { + mBlockCompletion = true; replaceText(completion.getText()); + mBlockCompletion = false; + if (mItemClickListener != null) { final DropDownListView list = mDropDownList; // Note that we don't have a View here, so we will need to @@ -604,7 +692,10 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe Log.w(TAG, "performCompletion: no selected item"); return; } + + mBlockCompletion = true; replaceText(convertSelectionToString(selectedItem)); + mBlockCompletion = false; if (mItemClickListener != null) { final DropDownListView list = mDropDownList; @@ -620,6 +711,14 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe dismissDropDown(); } + + /** + * Identifies whether the view is currently performing a text completion, so subclasses + * can decide whether to respond to text changed events. + */ + public boolean isPerformingCompletion() { + return mBlockCompletion; + } /** *

          Performs the text completion by replacing the current text by the @@ -636,6 +735,8 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } public void onFilterComplete(int count) { + if (mAttachCount <= 0) return; + /* * This checks enoughToFilter() again because filtering requests * are asynchronous, so the result may come back after enough text @@ -670,9 +771,16 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } } + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + mAttachCount++; + } + @Override protected void onDetachedFromWindow() { dismissDropDown(); + mAttachCount--; super.onDetachedFromWindow(); } @@ -694,11 +802,23 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe boolean result = super.setFrame(l, t, r, b); if (mPopup.isShowing()) { - mPopup.update(this, getMeasuredWidth() - mPaddingLeft - mPaddingRight, -1); + mPopup.update(this, r - l, -1); } return result; } + + /** + *

          Used for lazy instantiation of the anchor view from the id we have. If the value of + * the id is NO_ID or we can't find a view for the given id, we return this TextView as + * the default anchoring point.

          + */ + private View getDropDownAnchorView() { + if (mDropDownAnchorView == null && mDropDownAnchorId != View.NO_ID) { + mDropDownAnchorView = getRootView().findViewById(mDropDownAnchorId); + } + return mDropDownAnchorView == null ? this : mDropDownAnchorView; + } /** *

          Displays the drop down on screen.

          @@ -706,16 +826,36 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe public void showDropDown() { int height = buildDropDown(); if (mPopup.isShowing()) { - mPopup.update(this, mDropDownHorizontalOffset, mDropDownVerticalOffset, - getMeasuredWidth() - mPaddingLeft - mPaddingRight, height); + int widthSpec; + if (mDropDownWidth == ViewGroup.LayoutParams.FILL_PARENT) { + // The call to PopupWindow's update method below can accept -1 for any + // value you do not want to update. + widthSpec = -1; + } else if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { + widthSpec = getDropDownAnchorView().getWidth(); + } else { + widthSpec = mDropDownWidth; + } + mPopup.update(getDropDownAnchorView(), mDropDownHorizontalOffset, + mDropDownVerticalOffset, widthSpec, height); } else { - mPopup.setWindowLayoutMode(0, ViewGroup.LayoutParams.WRAP_CONTENT); - mPopup.setWidth(getMeasuredWidth() - mPaddingLeft - mPaddingRight); + if (mDropDownWidth == ViewGroup.LayoutParams.FILL_PARENT) { + mPopup.setWindowLayoutMode(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + } else { + mPopup.setWindowLayoutMode(0, ViewGroup.LayoutParams.WRAP_CONTENT); + if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { + mPopup.setWidth(getDropDownAnchorView().getWidth()); + } else { + mPopup.setWidth(mDropDownWidth); + } + } mPopup.setHeight(height); mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); mPopup.setOutsideTouchable(true); mPopup.setTouchInterceptor(new PopupTouchIntercepter()); - mPopup.showAsDropDown(this, mDropDownHorizontalOffset, mDropDownVerticalOffset); + mPopup.showAsDropDown(getDropDownAnchorView(), + mDropDownHorizontalOffset, mDropDownVerticalOffset); mDropDownList.setSelection(ListView.INVALID_POSITION); mDropDownList.hideSelector(); mDropDownList.requestFocus(); @@ -739,7 +879,7 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe int N = mAdapter.getCount(); if (N > 20) N = 20; CompletionInfo[] completions = new CompletionInfo[N]; - for (int i=0; i 0) { + mItemCount = totalItemCount; + mLongList = mItemCount / visibleItemCount >= MIN_PAGES; + } + if (!mLongList) { + if (mState != STATE_NONE) { + setState(STATE_NONE); + } + return; + } if (totalItemCount - visibleItemCount > 0 && mState != STATE_DRAGGING ) { mThumbY = ((mList.getHeight() - mThumbH) * firstVisibleItem) / (totalItemCount - visibleItemCount); @@ -296,12 +312,17 @@ class FastScroller { // Non-existent letter while (section > 0) { section--; - prevIndex = mSectionIndexer.getPositionForSection(section); - if (prevIndex != index) { - prevSection = section; - sectionIndex = section; - break; - } + prevIndex = mSectionIndexer.getPositionForSection(section); + if (prevIndex != index) { + prevSection = section; + sectionIndex = section; + break; + } else if (section == 0) { + // When section reaches 0 here, sectionIndex must follow it. + // Assuming mSectionIndexer.getPositionForSection(0) == 0. + sectionIndex = 0; + break; + } } } // Find the next index, in case the assumed next index is not diff --git a/core/java/android/widget/Filter.java b/core/java/android/widget/Filter.java index 7f1601e581c8dcad726e61f9595ec38221f9f028..7e55c78a39b30fb9485a37f027b7e37c817ea645 100644 --- a/core/java/android/widget/Filter.java +++ b/core/java/android/widget/Filter.java @@ -20,6 +20,7 @@ import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; +import android.util.Log; /** *

          A filter constrains data with a filtering pattern.

          @@ -36,14 +37,16 @@ import android.os.Message; * @see android.widget.Filterable */ public abstract class Filter { + private static final String LOG_TAG = "Filter"; + private static final String THREAD_NAME = "Filter"; private static final int FILTER_TOKEN = 0xD0D0F00D; private static final int FINISH_TOKEN = 0xDEADBEEF; - + private Handler mThreadHandler; private Handler mResultHandler; - private String mConstraint; - private boolean mConstraintIsValid = false; + + private final Object mLock = new Object(); /** *

          Creates a new asynchronous filter.

          @@ -80,15 +83,7 @@ public abstract class Filter { * @see #publishResults(CharSequence, android.widget.Filter.FilterResults) */ public final void filter(CharSequence constraint, FilterListener listener) { - synchronized (this) { - String constraintAsString = constraint != null ? constraint.toString() : null; - if (mConstraintIsValid && ( - (constraintAsString == null && mConstraint == null) || - (constraintAsString != null && constraintAsString.equals(mConstraint)))) { - // nothing to do - return; - } - + synchronized (mLock) { if (mThreadHandler == null) { HandlerThread thread = new HandlerThread(THREAD_NAME); thread.start(); @@ -100,16 +95,13 @@ public abstract class Filter { RequestArguments args = new RequestArguments(); // make sure we use an immutable copy of the constraint, so that // it doesn't change while the filter operation is in progress - args.constraint = constraintAsString; + args.constraint = constraint != null ? constraint.toString() : null; args.listener = listener; message.obj = args; mThreadHandler.removeMessages(FILTER_TOKEN); mThreadHandler.removeMessages(FINISH_TOKEN); mThreadHandler.sendMessage(message); - - mConstraint = constraintAsString; - mConstraintIsValid = true; } } @@ -221,13 +213,16 @@ public abstract class Filter { RequestArguments args = (RequestArguments) msg.obj; try { args.results = performFiltering(args.constraint); + } catch (Exception e) { + args.results = new FilterResults(); + Log.w(LOG_TAG, "An exception occured during performFiltering()!", e); } finally { message = mResultHandler.obtainMessage(what); message.obj = args; message.sendToTarget(); } - synchronized (this) { + synchronized (mLock) { if (mThreadHandler != null) { Message finishMessage = mThreadHandler.obtainMessage(FINISH_TOKEN); mThreadHandler.sendMessageDelayed(finishMessage, 3000); @@ -235,7 +230,7 @@ public abstract class Filter { } break; case FINISH_TOKEN: - synchronized (this) { + synchronized (mLock) { if (mThreadHandler != null) { mThreadHandler.getLooper().quit(); mThreadHandler = null; diff --git a/core/java/android/widget/FrameLayout.java b/core/java/android/widget/FrameLayout.java index b4ed3bad9a5a5805c1cc6e664b7813e4fa866d55..8aafee2118f9c9e5e289160ab1d9f0c7641b3c93 100644 --- a/core/java/android/widget/FrameLayout.java +++ b/core/java/android/widget/FrameLayout.java @@ -93,6 +93,7 @@ public class FrameLayout extends ViewGroup { * * @attr ref android.R.styleable#FrameLayout_foregroundGravity */ + @android.view.RemotableViewMethod public void setForegroundGravity(int foregroundGravity) { if (mForegroundGravity != foregroundGravity) { if ((foregroundGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { @@ -348,6 +349,7 @@ public class FrameLayout extends ViewGroup { * * @attr ref android.R.styleable#FrameLayout_measureAllChildren */ + @android.view.RemotableViewMethod public void setMeasureAllChildren(boolean measureAll) { mMeasureAllChildren = measureAll; } diff --git a/core/java/android/widget/Gallery.java b/core/java/android/widget/Gallery.java index 7b9735c865edc9bf48b9f9a04fb6e2940760c22f..e7b303ada4d061a4b377746506964a9612f9c71b 100644 --- a/core/java/android/widget/Gallery.java +++ b/core/java/android/widget/Gallery.java @@ -27,6 +27,7 @@ import android.util.Config; import android.util.Log; import android.view.GestureDetector; import android.view.Gravity; +import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; @@ -180,7 +181,7 @@ public class Gallery extends AbsSpinner implements GestureDetector.OnGestureList public Gallery(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - mGestureDetector = new GestureDetector(this); + mGestureDetector = new GestureDetector(context, this); mGestureDetector.setIsLongpressEnabled(true); TypedArray a = context.obtainStyledAttributes( @@ -994,6 +995,7 @@ public class Gallery extends AbsSpinner implements GestureDetector.OnGestureList return; } + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); long id = getItemIdAtPosition(mDownTouchPosition); dispatchLongPress(mDownTouchView, mDownTouchPosition, id); } @@ -1086,6 +1088,10 @@ public class Gallery extends AbsSpinner implements GestureDetector.OnGestureList handled = super.showContextMenuForChild(this); } + if (handled) { + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + } + return handled; } diff --git a/core/java/android/widget/GridView.java b/core/java/android/widget/GridView.java index 38bfc7c17b44ba524186d9c6b7693749350bd30c..11fab8f96a22808443654f553fa1750f37dcc66c 100644 --- a/core/java/android/widget/GridView.java +++ b/core/java/android/widget/GridView.java @@ -924,32 +924,24 @@ public class GridView extends AbsListView { final int count = mItemCount; if (count > 0) { final View child = obtainView(0); - final int childViewType = mAdapter.getItemViewType(0); - AbsListView.LayoutParams lp = (AbsListView.LayoutParams) child.getLayoutParams(); - if (lp == null) { - lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + AbsListView.LayoutParams p = (AbsListView.LayoutParams)child.getLayoutParams(); + if (p == null) { + p = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); - child.setLayoutParams(lp); - } - lp.viewType = childViewType; - - final int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, - mListPadding.left + mListPadding.right, lp.width); - - int lpHeight = lp.height; - - int childHeightSpec; - if (lpHeight > 0) { - childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); - } else { - childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); + child.setLayoutParams(p); } + p.viewType = mAdapter.getItemViewType(0); + int childHeightSpec = getChildMeasureSpec( + MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0, p.height); + int childWidthSpec = getChildMeasureSpec( + MeasureSpec.makeMeasureSpec(mColumnWidth, MeasureSpec.EXACTLY), 0, p.width); child.measure(childWidthSpec, childHeightSpec); + childHeight = child.getMeasuredHeight(); - if (mRecycler.shouldRecycleViewType(childViewType)) { + if (mRecycler.shouldRecycleViewType(p.viewType)) { mRecycler.addScrapView(child); } } @@ -1337,11 +1329,8 @@ public class GridView extends AbsListView { */ @Override void setSelectionInt(int position) { - mBlockLayoutRequests = true; setNextSelectedPositionInt(position); layoutChildren(); - - mBlockLayoutRequests = false; } @Override diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java new file mode 100644 index 0000000000000000000000000000000000000000..652e30c72133ff76798ec1724ab26f0573ff97b8 --- /dev/null +++ b/core/java/android/widget/HorizontalScrollView.java @@ -0,0 +1,1197 @@ +/* + * 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. + */ + +package android.widget; + +import android.util.AttributeSet; +import android.graphics.Rect; +import android.view.View; +import android.view.VelocityTracker; +import android.view.ViewConfiguration; +import android.view.ViewGroup; +import android.view.KeyEvent; +import android.view.FocusFinder; +import android.view.MotionEvent; +import android.view.ViewParent; +import android.view.animation.AnimationUtils; +import android.content.Context; +import android.content.res.TypedArray; + +import java.util.List; + +/** + * Layout container for a view hierarchy that can be scrolled by the user, + * allowing it to be larger than the physical display. A HorizontalScrollView + * is a {@link FrameLayout}, meaning you should place one child in it + * containing the entire contents to scroll; this child may itself be a layout + * manager with a complex hierarchy of objects. A child that is often used + * is a {@link LinearLayout} in a horizontal orientation, presenting a horizontal + * array of top-level items that the user can scroll through. + * + *

          You should never use a HorizontalScrollView with a {@link ListView}, since + * ListView takes care of its own scrolling. Most importantly, doing this + * defeats all of the important optimizations in ListView for dealing with + * large lists, since it effectively forces the ListView to display its entire + * list of items to fill up the infinite container supplied by HorizontalScrollView. + * + *

          The {@link TextView} class also + * takes care of its own scrolling, so does not require a ScrollView, but + * using the two together is possible to achieve the effect of a text view + * within a larger container. + * + *

          HorizontalScrollView only supports horizontal scrolling. + */ +public class HorizontalScrollView extends FrameLayout { + private static final int ANIMATED_SCROLL_GAP = ScrollView.ANIMATED_SCROLL_GAP; + + private static final float MAX_SCROLL_FACTOR = ScrollView.MAX_SCROLL_FACTOR; + + + private long mLastScroll; + + private final Rect mTempRect = new Rect(); + private Scroller mScroller; + + /** + * Flag to indicate that we are moving focus ourselves. This is so the + * code that watches for focus changes initiated outside this ScrollView + * knows that it does not have to do anything. + */ + private boolean mScrollViewMovedFocus; + + /** + * Position of the last motion event. + */ + private float mLastMotionX; + + /** + * True when the layout has changed but the traversal has not come through yet. + * Ideally the view hierarchy would keep track of this for us. + */ + private boolean mIsLayoutDirty = true; + + /** + * The child to give focus to in the event that a child has requested focus while the + * layout is dirty. This prevents the scroll from being wrong if the child has not been + * laid out before requesting focus. + */ + private View mChildToScrollTo = null; + + /** + * True if the user is currently dragging this ScrollView around. This is + * not the same as 'is being flinged', which can be checked by + * mScroller.isFinished() (flinging begins when the user lifts his finger). + */ + private boolean mIsBeingDragged = false; + + /** + * Determines speed during touch scrolling + */ + private VelocityTracker mVelocityTracker; + + /** + * When set to true, the scroll view measure its child to make it fill the currently + * visible area. + */ + private boolean mFillViewport; + + /** + * Whether arrow scrolling is animated. + */ + private boolean mSmoothScrollingEnabled = true; + + private int mTouchSlop; + + public HorizontalScrollView(Context context) { + this(context, null); + } + + public HorizontalScrollView(Context context, AttributeSet attrs) { + this(context, attrs, com.android.internal.R.attr.horizontalScrollViewStyle); + } + + public HorizontalScrollView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + initScrollView(); + + TypedArray a = context.obtainStyledAttributes(attrs, + android.R.styleable.HorizontalScrollView, defStyle, 0); + + setFillViewport(a.getBoolean(android.R.styleable.HorizontalScrollView_fillViewport, false)); + + a.recycle(); + } + + @Override + protected float getLeftFadingEdgeStrength() { + if (getChildCount() == 0) { + return 0.0f; + } + + final int length = getHorizontalFadingEdgeLength(); + if (mScrollX < length) { + return mScrollX / (float) length; + } + + return 1.0f; + } + + @Override + protected float getRightFadingEdgeStrength() { + if (getChildCount() == 0) { + return 0.0f; + } + + final int length = getHorizontalFadingEdgeLength(); + final int rightEdge = getWidth() - mPaddingRight; + final int span = getChildAt(0).getRight() - mScrollX - rightEdge; + if (span < length) { + return span / (float) length; + } + + return 1.0f; + } + + /** + * @return The maximum amount this scroll view will scroll in response to + * an arrow event. + */ + public int getMaxScrollAmount() { + return (int) (MAX_SCROLL_FACTOR * (mRight - mLeft)); + } + + + private void initScrollView() { + mScroller = new Scroller(getContext()); + setFocusable(true); + setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); + setWillNotDraw(false); + mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); + } + + @Override + public void addView(View child) { + if (getChildCount() > 0) { + throw new IllegalStateException("HorizontalScrollView can host only one direct child"); + } + + super.addView(child); + } + + @Override + public void addView(View child, int index) { + if (getChildCount() > 0) { + throw new IllegalStateException("HorizontalScrollView can host only one direct child"); + } + + super.addView(child, index); + } + + @Override + public void addView(View child, ViewGroup.LayoutParams params) { + if (getChildCount() > 0) { + throw new IllegalStateException("HorizontalScrollView can host only one direct child"); + } + + super.addView(child, params); + } + + @Override + public void addView(View child, int index, ViewGroup.LayoutParams params) { + if (getChildCount() > 0) { + throw new IllegalStateException("HorizontalScrollView can host only one direct child"); + } + + super.addView(child, index, params); + } + + /** + * @return Returns true this HorizontalScrollView can be scrolled + */ + private boolean canScroll() { + View child = getChildAt(0); + if (child != null) { + int childWidth = child.getWidth(); + return getWidth() < childWidth + mPaddingLeft + mPaddingRight ; + } + return false; + } + + /** + * Indicates whether this ScrollView's content is stretched to fill the viewport. + * + * @return True if the content fills the viewport, false otherwise. + */ + public boolean isFillViewport() { + return mFillViewport; + } + + /** + * Indicates this ScrollView whether it should stretch its content width to fill + * the viewport or not. + * + * @param fillViewport True to stretch the content's width to the viewport's + * boundaries, false otherwise. + */ + public void setFillViewport(boolean fillViewport) { + if (fillViewport != mFillViewport) { + mFillViewport = fillViewport; + requestLayout(); + } + } + + /** + * @return Whether arrow scrolling will animate its transition. + */ + public boolean isSmoothScrollingEnabled() { + return mSmoothScrollingEnabled; + } + + /** + * Set whether arrow scrolling will animate its transition. + * @param smoothScrollingEnabled whether arrow scrolling will animate its transition + */ + public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) { + mSmoothScrollingEnabled = smoothScrollingEnabled; + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + + if (!mFillViewport) { + return; + } + + final int widthMode = MeasureSpec.getMode(widthMeasureSpec); + if (widthMode == MeasureSpec.UNSPECIFIED) { + return; + } + + final View child = getChildAt(0); + int width = getMeasuredWidth(); + if (child.getMeasuredHeight() < width) { + final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); + + int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, mPaddingTop + + mPaddingBottom, lp.height); + width -= mPaddingLeft; + width -= mPaddingRight; + int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } + } + + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + // Let the focused view and/or our descendants get the key first + boolean handled = super.dispatchKeyEvent(event); + if (handled) { + return true; + } + return executeKeyEvent(event); + } + + /** + * You can call this function yourself to have the scroll view perform + * scrolling from a key event, just as if the event had been dispatched to + * it by the view hierarchy. + * + * @param event The key event to execute. + * @return Return true if the event was handled, else false. + */ + public boolean executeKeyEvent(KeyEvent event) { + mTempRect.setEmpty(); + + if (!canScroll()) { + if (isFocused()) { + View currentFocused = findFocus(); + if (currentFocused == this) currentFocused = null; + View nextFocused = FocusFinder.getInstance().findNextFocus(this, + currentFocused, View.FOCUS_RIGHT); + return nextFocused != null && nextFocused != this && + nextFocused.requestFocus(View.FOCUS_RIGHT); + } + return false; + } + + boolean handled = false; + if (event.getAction() == KeyEvent.ACTION_DOWN) { + switch (event.getKeyCode()) { + case KeyEvent.KEYCODE_DPAD_LEFT: + if (!event.isAltPressed()) { + handled = arrowScroll(View.FOCUS_LEFT); + } else { + handled = fullScroll(View.FOCUS_LEFT); + } + break; + case KeyEvent.KEYCODE_DPAD_RIGHT: + if (!event.isAltPressed()) { + handled = arrowScroll(View.FOCUS_RIGHT); + } else { + handled = fullScroll(View.FOCUS_RIGHT); + } + break; + case KeyEvent.KEYCODE_SPACE: + pageScroll(event.isShiftPressed() ? View.FOCUS_LEFT : View.FOCUS_RIGHT); + break; + } + } + + return handled; + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent ev) { + /* + * This method JUST determines whether we want to intercept the motion. + * If we return true, onMotionEvent will be called and we do the actual + * scrolling there. + */ + + /* + * Shortcut the most recurring case: the user is in the dragging + * state and he is moving his finger. We want to intercept this + * motion. + */ + final int action = ev.getAction(); + if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { + return true; + } + + if (!canScroll()) { + mIsBeingDragged = false; + return false; + } + + final float x = ev.getX(); + + switch (action) { + case MotionEvent.ACTION_MOVE: + /* + * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check + * whether the user has moved far enough from his original down touch. + */ + + /* + * Locally do absolute value. mLastMotionX is set to the x value + * of the down event. + */ + final int xDiff = (int) Math.abs(x - mLastMotionX); + if (xDiff > mTouchSlop) { + mIsBeingDragged = true; + if (mParent != null) mParent.requestDisallowInterceptTouchEvent(true); + } + break; + + case MotionEvent.ACTION_DOWN: + /* Remember location of down touch */ + mLastMotionX = x; + + /* + * If being flinged and user touches the screen, initiate drag; + * otherwise don't. mScroller.isFinished should be false when + * being flinged. + */ + mIsBeingDragged = !mScroller.isFinished(); + break; + + case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_UP: + /* Release the drag */ + mIsBeingDragged = false; + break; + } + + /* + * The only time we want to intercept motion events is if we are in the + * drag mode. + */ + return mIsBeingDragged; + } + + @Override + public boolean onTouchEvent(MotionEvent ev) { + + if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { + // Don't handle edge touches immediately -- they may actually belong to one of our + // descendants. + return false; + } + + if (!canScroll()) { + return false; + } + + if (mVelocityTracker == null) { + mVelocityTracker = VelocityTracker.obtain(); + } + mVelocityTracker.addMovement(ev); + + final int action = ev.getAction(); + final float x = ev.getX(); + + switch (action) { + case MotionEvent.ACTION_DOWN: + /* + * If being flinged and user touches, stop the fling. isFinished + * will be false if being flinged. + */ + if (!mScroller.isFinished()) { + mScroller.abortAnimation(); + } + + // Remember where the motion event started + mLastMotionX = x; + break; + case MotionEvent.ACTION_MOVE: + // Scroll to follow the motion event + final int deltaX = (int) (mLastMotionX - x); + mLastMotionX = x; + + if (deltaX < 0) { + if (mScrollX > 0) { + scrollBy(deltaX, 0); + } + } else if (deltaX > 0) { + final int rightEdge = getWidth() - mPaddingRight; + final int availableToScroll = getChildAt(0).getRight() - mScrollX - rightEdge; + if (availableToScroll > 0) { + scrollBy(Math.min(availableToScroll, deltaX), 0); + } + } + break; + case MotionEvent.ACTION_UP: + final VelocityTracker velocityTracker = mVelocityTracker; + velocityTracker.computeCurrentVelocity(1000); + int initialVelocity = (int) velocityTracker.getXVelocity(); + + if ((Math.abs(initialVelocity) > + ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) && + getChildCount() > 0) { + fling(-initialVelocity); + } + + if (mVelocityTracker != null) { + mVelocityTracker.recycle(); + mVelocityTracker = null; + } + } + return true; + } + + /** + *

          + * Finds the next focusable component that fits in this View's bounds + * (excluding fading edges) pretending that this View's left is located at + * the parameter left. + *

          + * + * @param leftFocus look for a candidate is the one at the left of the bounds + * if leftFocus is true, or at the right of the bounds if leftFocus + * is false + * @param left the left offset of the bounds in which a focusable must be + * found (the fading edge is assumed to start at this position) + * @param preferredFocusable the View that has highest priority and will be + * returned if it is within my bounds (null is valid) + * @return the next focusable component in the bounds or null if none can be found + */ + private View findFocusableViewInMyBounds(final boolean leftFocus, + final int left, View preferredFocusable) { + /* + * The fading edge's transparent side should be considered for focus + * since it's mostly visible, so we divide the actual fading edge length + * by 2. + */ + final int fadingEdgeLength = getHorizontalFadingEdgeLength() / 2; + final int leftWithoutFadingEdge = left + fadingEdgeLength; + final int rightWithoutFadingEdge = left + getWidth() - fadingEdgeLength; + + if ((preferredFocusable != null) + && (preferredFocusable.getLeft() < rightWithoutFadingEdge) + && (preferredFocusable.getRight() > leftWithoutFadingEdge)) { + return preferredFocusable; + } + + return findFocusableViewInBounds(leftFocus, leftWithoutFadingEdge, + rightWithoutFadingEdge); + } + + /** + *

          + * Finds the next focusable component that fits in the specified bounds. + *

          + * + * @param leftFocus look for a candidate is the one at the left of the bounds + * if leftFocus is true, or at the right of the bounds if + * leftFocus is false + * @param left the left offset of the bounds in which a focusable must be + * found + * @param right the right offset of the bounds in which a focusable must + * be found + * @return the next focusable component in the bounds or null if none can + * be found + */ + private View findFocusableViewInBounds(boolean leftFocus, int left, int right) { + + List focusables = getFocusables(View.FOCUS_FORWARD); + View focusCandidate = null; + + /* + * A fully contained focusable is one where its left is below the bound's + * left, and its right is above the bound's right. A partially + * contained focusable is one where some part of it is within the + * bounds, but it also has some part that is not within bounds. A fully contained + * focusable is preferred to a partially contained focusable. + */ + boolean foundFullyContainedFocusable = false; + + int count = focusables.size(); + for (int i = 0; i < count; i++) { + View view = focusables.get(i); + int viewLeft = view.getLeft(); + int viewRight = view.getRight(); + + if (left < viewRight && viewLeft < right) { + /* + * the focusable is in the target area, it is a candidate for + * focusing + */ + + final boolean viewIsFullyContained = (left < viewLeft) && + (viewRight < right); + + if (focusCandidate == null) { + /* No candidate, take this one */ + focusCandidate = view; + foundFullyContainedFocusable = viewIsFullyContained; + } else { + final boolean viewIsCloserToBoundary = + (leftFocus && viewLeft < focusCandidate.getLeft()) || + (!leftFocus && viewRight > focusCandidate.getRight()); + + if (foundFullyContainedFocusable) { + if (viewIsFullyContained && viewIsCloserToBoundary) { + /* + * We're dealing with only fully contained views, so + * it has to be closer to the boundary to beat our + * candidate + */ + focusCandidate = view; + } + } else { + if (viewIsFullyContained) { + /* Any fully contained view beats a partially contained view */ + focusCandidate = view; + foundFullyContainedFocusable = true; + } else if (viewIsCloserToBoundary) { + /* + * Partially contained view beats another partially + * contained view if it's closer + */ + focusCandidate = view; + } + } + } + } + } + + return focusCandidate; + } + + /** + *

          Handles scrolling in response to a "page up/down" shortcut press. This + * method will scroll the view by one page left or right and give the focus + * to the leftmost/rightmost component in the new visible area. If no + * component is a good candidate for focus, this scrollview reclaims the + * focus.

          + * + * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} + * to go one page left or {@link android.view.View#FOCUS_RIGHT} + * to go one page right + * @return true if the key event is consumed by this method, false otherwise + */ + public boolean pageScroll(int direction) { + boolean right = direction == View.FOCUS_RIGHT; + int width = getWidth(); + + if (right) { + mTempRect.left = getScrollX() + width; + int count = getChildCount(); + if (count > 0) { + View view = getChildAt(count - 1); + if (mTempRect.left + width > view.getRight()) { + mTempRect.left = view.getRight() - width; + } + } + } else { + mTempRect.left = getScrollX() - width; + if (mTempRect.left < 0) { + mTempRect.left = 0; + } + } + mTempRect.right = mTempRect.left + width; + + return scrollAndFocus(direction, mTempRect.left, mTempRect.right); + } + + /** + *

          Handles scrolling in response to a "home/end" shortcut press. This + * method will scroll the view to the left or right and give the focus + * to the leftmost/rightmost component in the new visible area. If no + * component is a good candidate for focus, this scrollview reclaims the + * focus.

          + * + * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} + * to go the left of the view or {@link android.view.View#FOCUS_RIGHT} + * to go the right + * @return true if the key event is consumed by this method, false otherwise + */ + public boolean fullScroll(int direction) { + boolean right = direction == View.FOCUS_RIGHT; + int width = getWidth(); + + mTempRect.left = 0; + mTempRect.right = width; + + if (right) { + int count = getChildCount(); + if (count > 0) { + View view = getChildAt(count - 1); + mTempRect.right = view.getRight(); + mTempRect.left = mTempRect.right - width; + } + } + + return scrollAndFocus(direction, mTempRect.left, mTempRect.right); + } + + /** + *

          Scrolls the view to make the area defined by left and + * right visible. This method attempts to give the focus + * to a component visible in this area. If no component can be focused in + * the new visible area, the focus is reclaimed by this scrollview.

          + * + * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} + * to go left {@link android.view.View#FOCUS_RIGHT} to right + * @param left the left offset of the new area to be made visible + * @param right the right offset of the new area to be made visible + * @return true if the key event is consumed by this method, false otherwise + */ + private boolean scrollAndFocus(int direction, int left, int right) { + boolean handled = true; + + int width = getWidth(); + int containerLeft = getScrollX(); + int containerRight = containerLeft + width; + boolean goLeft = direction == View.FOCUS_LEFT; + + View newFocused = findFocusableViewInBounds(goLeft, left, right); + if (newFocused == null) { + newFocused = this; + } + + if (left >= containerLeft && right <= containerRight) { + handled = false; + } else { + int delta = goLeft ? (left - containerLeft) : (right - containerRight); + doScrollX(delta); + } + + if (newFocused != findFocus() && newFocused.requestFocus(direction)) { + mScrollViewMovedFocus = true; + mScrollViewMovedFocus = false; + } + + return handled; + } + + /** + * Handle scrolling in response to a left or right arrow click. + * + * @param direction The direction corresponding to the arrow key that was + * pressed + * @return True if we consumed the event, false otherwise + */ + public boolean arrowScroll(int direction) { + + View currentFocused = findFocus(); + if (currentFocused == this) currentFocused = null; + + View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); + + final int maxJump = getMaxScrollAmount(); + + if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump)) { + nextFocused.getDrawingRect(mTempRect); + offsetDescendantRectToMyCoords(nextFocused, mTempRect); + int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); + doScrollX(scrollDelta); + nextFocused.requestFocus(direction); + } else { + // no new focus + int scrollDelta = maxJump; + + if (direction == View.FOCUS_LEFT && getScrollX() < scrollDelta) { + scrollDelta = getScrollX(); + } else if (direction == View.FOCUS_RIGHT) { + + int daRight = getChildAt(getChildCount() - 1).getRight(); + + int screenRight = getScrollX() + getWidth(); + + if (daRight - screenRight < maxJump) { + scrollDelta = daRight - screenRight; + } + } + if (scrollDelta == 0) { + return false; + } + doScrollX(direction == View.FOCUS_RIGHT ? scrollDelta : -scrollDelta); + } + + if (currentFocused != null && currentFocused.isFocused() + && isOffScreen(currentFocused)) { + // previously focused item still has focus and is off screen, give + // it up (take it back to ourselves) + // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are + // sure to + // get it) + final int descendantFocusability = getDescendantFocusability(); // save + setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); + requestFocus(); + setDescendantFocusability(descendantFocusability); // restore + } + return true; + } + + /** + * @return whether the descendant of this scroll view is scrolled off + * screen. + */ + private boolean isOffScreen(View descendant) { + return !isWithinDeltaOfScreen(descendant, 0); + } + + /** + * @return whether the descendant of this scroll view is within delta + * pixels of being on the screen. + */ + private boolean isWithinDeltaOfScreen(View descendant, int delta) { + descendant.getDrawingRect(mTempRect); + offsetDescendantRectToMyCoords(descendant, mTempRect); + + return (mTempRect.right + delta) >= getScrollX() + && (mTempRect.left - delta) <= (getScrollX() + getWidth()); + } + + /** + * Smooth scroll by a X delta + * + * @param delta the number of pixels to scroll by on the X axis + */ + private void doScrollX(int delta) { + if (delta != 0) { + if (mSmoothScrollingEnabled) { + smoothScrollBy(delta, 0); + } else { + scrollBy(delta, 0); + } + } + } + + /** + * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. + * + * @param dx the number of pixels to scroll by on the X axis + * @param dy the number of pixels to scroll by on the Y axis + */ + public final void smoothScrollBy(int dx, int dy) { + long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; + if (duration > ANIMATED_SCROLL_GAP) { + mScroller.startScroll(mScrollX, mScrollY, dx, dy); + invalidate(); + } else { + if (!mScroller.isFinished()) { + mScroller.abortAnimation(); + } + scrollBy(dx, dy); + } + mLastScroll = AnimationUtils.currentAnimationTimeMillis(); + } + + /** + * Like {@link #scrollTo}, but scroll smoothly instead of immediately. + * + * @param x the position where to scroll on the X axis + * @param y the position where to scroll on the Y axis + */ + public final void smoothScrollTo(int x, int y) { + smoothScrollBy(x - mScrollX, y - mScrollY); + } + + /** + *

          The scroll range of a scroll view is the overall width of all of its + * children.

          + */ + @Override + protected int computeHorizontalScrollRange() { + int count = getChildCount(); + return count == 0 ? getWidth() : getChildAt(0).getRight(); + } + + + @Override + protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { + ViewGroup.LayoutParams lp = child.getLayoutParams(); + + int childWidthMeasureSpec; + int childHeightMeasureSpec; + + childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop + + mPaddingBottom, lp.height); + + childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } + + @Override + protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, + int parentHeightMeasureSpec, int heightUsed) { + final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); + + final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, + mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin + + heightUsed, lp.height); + final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( + lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } + + @Override + public void computeScroll() { + if (mScroller.computeScrollOffset()) { + // This is called at drawing time by ViewGroup. We don't want to + // re-show the scrollbars at this point, which scrollTo will do, + // so we replicate most of scrollTo here. + // + // It's a little odd to call onScrollChanged from inside the drawing. + // + // It is, except when you remember that computeScroll() is used to + // animate scrolling. So unless we want to defer the onScrollChanged() + // until the end of the animated scrolling, we don't really have a + // choice here. + // + // I agree. The alternative, which I think would be worse, is to post + // something and tell the subclasses later. This is bad because there + // will be a window where mScrollX/Y is different from what the app + // thinks it is. + // + int oldX = mScrollX; + int oldY = mScrollY; + int x = mScroller.getCurrX(); + int y = mScroller.getCurrY(); + if (getChildCount() > 0) { + View child = getChildAt(0); + mScrollX = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); + mScrollY = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); + } else { + mScrollX = x; + mScrollY = y; + } + if (oldX != mScrollX || oldY != mScrollY) { + onScrollChanged(mScrollX, mScrollY, oldX, oldY); + } + + // Keep on drawing until the animation has finished. + postInvalidate(); + } + } + + /** + * Scrolls the view to the given child. + * + * @param child the View to scroll to + */ + private void scrollToChild(View child) { + child.getDrawingRect(mTempRect); + + /* Offset from child's local coordinates to ScrollView coordinates */ + offsetDescendantRectToMyCoords(child, mTempRect); + + int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); + + if (scrollDelta != 0) { + scrollBy(scrollDelta, 0); + } + } + + /** + * If rect is off screen, scroll just enough to get it (or at least the + * first screen size chunk of it) on screen. + * + * @param rect The rectangle. + * @param immediate True to scroll immediately without animation + * @return true if scrolling was performed + */ + private boolean scrollToChildRect(Rect rect, boolean immediate) { + final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); + final boolean scroll = delta != 0; + if (scroll) { + if (immediate) { + scrollBy(delta, 0); + } else { + smoothScrollBy(delta, 0); + } + } + return scroll; + } + + /** + * Compute the amount to scroll in the X direction in order to get + * a rectangle completely on the screen (or, if taller than the screen, + * at least the first screen size chunk of it). + * + * @param rect The rect. + * @return The scroll delta. + */ + protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { + + int width = getWidth(); + int screenLeft = getScrollX(); + int screenRight = screenLeft + width; + + int fadingEdge = getHorizontalFadingEdgeLength(); + + // leave room for left fading edge as long as rect isn't at very left + if (rect.left > 0) { + screenLeft += fadingEdge; + } + + // leave room for right fading edge as long as rect isn't at very right + if (rect.right < getChildAt(0).getWidth()) { + screenRight -= fadingEdge; + } + + int scrollXDelta = 0; + + if (rect.right > screenRight && rect.left > screenLeft) { + // need to move right to get it in view: move right just enough so + // that the entire rectangle is in view (or at least the first + // screen size chunk). + + if (rect.width() > width) { + // just enough to get screen size chunk on + scrollXDelta += (rect.left - screenLeft); + } else { + // get entire rect at right of screen + scrollXDelta += (rect.right - screenRight); + } + + // make sure we aren't scrolling beyond the end of our content + int right = getChildAt(getChildCount() - 1).getRight(); + int distanceToRight = right - screenRight; + scrollXDelta = Math.min(scrollXDelta, distanceToRight); + + } else if (rect.left < screenLeft && rect.right < screenRight) { + // need to move right to get it in view: move right just enough so that + // entire rectangle is in view (or at least the first screen + // size chunk of it). + + if (rect.width() > width) { + // screen size chunk + scrollXDelta -= (screenRight - rect.right); + } else { + // entire rect at left + scrollXDelta -= (screenLeft - rect.left); + } + + // make sure we aren't scrolling any further than the left our content + scrollXDelta = Math.max(scrollXDelta, -getScrollX()); + } + return scrollXDelta; + } + + @Override + public void requestChildFocus(View child, View focused) { + if (!mScrollViewMovedFocus) { + if (!mIsLayoutDirty) { + scrollToChild(focused); + } else { + // The child may not be laid out yet, we can't compute the scroll yet + mChildToScrollTo = focused; + } + } + super.requestChildFocus(child, focused); + } + + + /** + * When looking for focus in children of a scroll view, need to be a little + * more careful not to give focus to something that is scrolled off screen. + * + * This is more expensive than the default {@link android.view.ViewGroup} + * implementation, otherwise this behavior might have been made the default. + */ + @Override + protected boolean onRequestFocusInDescendants(int direction, + Rect previouslyFocusedRect) { + + // convert from forward / backward notation to up / down / left / right + // (ugh). + if (direction == View.FOCUS_FORWARD) { + direction = View.FOCUS_RIGHT; + } else if (direction == View.FOCUS_BACKWARD) { + direction = View.FOCUS_LEFT; + } + + final View nextFocus = previouslyFocusedRect == null ? + FocusFinder.getInstance().findNextFocus(this, null, direction) : + FocusFinder.getInstance().findNextFocusFromRect(this, + previouslyFocusedRect, direction); + + if (nextFocus == null) { + return false; + } + + if (isOffScreen(nextFocus)) { + return false; + } + + return nextFocus.requestFocus(direction, previouslyFocusedRect); + } + + @Override + public boolean requestChildRectangleOnScreen(View child, Rect rectangle, + boolean immediate) { + // offset into coordinate space of this scroll view + rectangle.offset(child.getLeft() - child.getScrollX(), + child.getTop() - child.getScrollY()); + + return scrollToChildRect(rectangle, immediate); + } + + @Override + public void requestLayout() { + mIsLayoutDirty = true; + super.requestLayout(); + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + super.onLayout(changed, l, t, r, b); + mIsLayoutDirty = false; + // Give a child focus if it needs it + if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { + scrollToChild(mChildToScrollTo); + } + mChildToScrollTo = null; + + // Calling this with the present values causes it to re-clam them + scrollTo(mScrollX, mScrollY); + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + + View currentFocused = findFocus(); + if (null == currentFocused || this == currentFocused) + return; + + final int maxJump = mRight - mLeft; + + if (isWithinDeltaOfScreen(currentFocused, maxJump)) { + currentFocused.getDrawingRect(mTempRect); + offsetDescendantRectToMyCoords(currentFocused, mTempRect); + int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); + doScrollX(scrollDelta); + } + } + + /** + * Return true if child is an descendant of parent, (or equal to the parent). + */ + private boolean isViewDescendantOf(View child, View parent) { + if (child == parent) { + return true; + } + + final ViewParent theParent = child.getParent(); + return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); + } + + /** + * Fling the scroll view + * + * @param velocityX The initial velocity in the X direction. Positive + * numbers mean that the finger/curor is moving down the screen, + * which means we want to scroll towards the left. + */ + public void fling(int velocityX) { + int width = getWidth() - mPaddingRight - mPaddingLeft; + int right = getChildAt(0).getWidth(); + + mScroller.fling(mScrollX, mScrollY, velocityX, 0, 0, right - width, 0, 0); + + final boolean movingRight = velocityX > 0; + + View newFocused = findFocusableViewInMyBounds(movingRight, + mScroller.getFinalX(), findFocus()); + + if (newFocused == null) { + newFocused = this; + } + + if (newFocused != findFocus() + && newFocused.requestFocus(movingRight ? View.FOCUS_RIGHT : View.FOCUS_LEFT)) { + mScrollViewMovedFocus = true; + mScrollViewMovedFocus = false; + } + + invalidate(); + } + + /** + * {@inheritDoc} + * + *

          This version also clamps the scrolling to the bounds of our child. + */ + public void scrollTo(int x, int y) { + // we rely on the fact the View.scrollBy calls scrollTo. + if (getChildCount() > 0) { + View child = getChildAt(0); + x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); + y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); + if (x != mScrollX || y != mScrollY) { + super.scrollTo(x, y); + } + } + } + + private int clamp(int n, int my, int child) { + if (my >= child || n < 0) { + return 0; + } + if ((my + n) > child) { + return child - my; + } + return n; + } +} diff --git a/core/java/android/widget/ImageView.java b/core/java/android/widget/ImageView.java index b5d4e2d5a6d49df95fc3a19b4e9e03cd3d7db9ae..480b0b8a135a23bab1cd1dda6329a8b9f82e437c 100644 --- a/core/java/android/widget/ImageView.java +++ b/core/java/android/widget/ImageView.java @@ -48,6 +48,7 @@ import android.widget.RemoteViews.RemoteView; * @attr ref android.R.styleable#ImageView_maxHeight * @attr ref android.R.styleable#ImageView_tint * @attr ref android.R.styleable#ImageView_scaleType + * @attr ref android.R.styleable#ImageView_cropToPadding */ @RemoteView public class ImageView extends View { @@ -192,6 +193,7 @@ public class ImageView extends View { * * @attr ref android.R.styleable#ImageView_adjustViewBounds */ + @android.view.RemotableViewMethod public void setAdjustViewBounds(boolean adjustViewBounds) { mAdjustViewBounds = adjustViewBounds; if (adjustViewBounds) { @@ -216,6 +218,7 @@ public class ImageView extends View { * * @attr ref android.R.styleable#ImageView_maxWidth */ + @android.view.RemotableViewMethod public void setMaxWidth(int maxWidth) { mMaxWidth = maxWidth; } @@ -237,6 +240,7 @@ public class ImageView extends View { * * @attr ref android.R.styleable#ImageView_maxHeight */ + @android.view.RemotableViewMethod public void setMaxHeight(int maxHeight) { mMaxHeight = maxHeight; } @@ -255,6 +259,7 @@ public class ImageView extends View { * * @attr ref android.R.styleable#ImageView_src */ + @android.view.RemotableViewMethod public void setImageResource(int resId) { if (mUri != null || mResource != resId) { updateDrawable(null); @@ -271,6 +276,7 @@ public class ImageView extends View { * * @param uri The Uri of an image */ + @android.view.RemotableViewMethod public void setImageURI(Uri uri) { if (mResource != 0 || (mUri != uri && @@ -305,6 +311,7 @@ public class ImageView extends View { * * @param bm The bitmap to set */ + @android.view.RemotableViewMethod public void setImageBitmap(Bitmap bm) { // if this is used frequently, may handle bitmaps explicitly // to reduce the intermediate drawable object @@ -326,6 +333,13 @@ public class ImageView extends View { resizeFromDrawable(); } + /** + * Sets the image level, when it is constructed from a + * {@link android.graphics.drawable.LevelListDrawable}. + * + * @param level The new level for the image. + */ + @android.view.RemotableViewMethod public void setImageLevel(int level) { mLevel = level; if (mDrawable != null) { @@ -832,7 +846,7 @@ public class ImageView extends View { @Override public int getBaseline() { - return mBaselineAligned ? getHeight() : -1; + return mBaselineAligned ? getMeasuredHeight() : -1; } /** diff --git a/core/java/android/widget/LinearLayout.java b/core/java/android/widget/LinearLayout.java index 36ed8bd401d1ec0515390fbd1cf3b042912966e4..a9822f8bc2ce620e6c38386e8e9422e5a9c7bb61 100644 --- a/core/java/android/widget/LinearLayout.java +++ b/core/java/android/widget/LinearLayout.java @@ -136,6 +136,7 @@ public class LinearLayout extends ViewGroup { * * @attr ref android.R.styleable#LinearLayout_baselineAligned */ + @android.view.RemotableViewMethod public void setBaselineAligned(boolean baselineAligned) { mBaselineAligned = baselineAligned; } @@ -208,6 +209,7 @@ public class LinearLayout extends ViewGroup { * * @attr ref android.R.styleable#LinearLayout_baselineAlignedChildIndex */ + @android.view.RemotableViewMethod public void setBaselineAlignedChildIndex(int i) { if ((i < 0) || (i >= getChildCount())) { throw new IllegalArgumentException("base aligned child index out " @@ -265,6 +267,7 @@ public class LinearLayout extends ViewGroup { * to 0.0f if the weight sum should be computed from the children's * layout_weight */ + @android.view.RemotableViewMethod public void setWeightSum(float weightSum) { mWeightSum = Math.max(0.0f, weightSum); } @@ -336,7 +339,7 @@ public class LinearLayout extends ViewGroup { // heightMode is either UNSPECIFIED OR AT_MOST, and this child // wanted to stretch to fill available space. Translate that to // WRAP_CONTENT so that it does not end up with a height of 0 - oldHeight = lp.height; + oldHeight = 0; lp.height = LayoutParams.WRAP_CONTENT; } @@ -475,8 +478,6 @@ public class LinearLayout extends ViewGroup { matchWidthLocally ? margin : measuredWidth); allFillParent = allFillParent && lp.width == LayoutParams.FILL_PARENT; - alternativeMaxWidth = Math.max(alternativeMaxWidth, - matchWidthLocally ? margin : measuredWidth); mTotalLength += child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin + getNextLocationOffset(child); @@ -607,7 +608,7 @@ public class LinearLayout extends ViewGroup { // widthMode is either UNSPECIFIED OR AT_MOST, and this child // wanted to stretch to fill available space. Translate that to // WRAP_CONTENT so that it does not end up with a width of 0 - oldWidth = lp.width; + oldWidth = 0; lp.width = LayoutParams.WRAP_CONTENT; } @@ -766,8 +767,6 @@ public class LinearLayout extends ViewGroup { matchHeightLocally ? margin : childHeight); allFillParent = allFillParent && lp.height == LayoutParams.FILL_PARENT; - alternativeMaxHeight = Math.max(alternativeMaxHeight, - matchHeightLocally ? margin : childHeight); if (baselineAligned) { final int childBaseline = child.getBaseline(); @@ -803,8 +802,7 @@ public class LinearLayout extends ViewGroup { maxHeight = Math.max(maxHeight, ascent + descent); } } else { - alternativeMaxHeight = Math.max(alternativeMaxHeight, - weightedMaxHeight); + alternativeMaxHeight = Math.max(alternativeMaxHeight, weightedMaxHeight); } if (!allFillParent && heightMode != MeasureSpec.EXACTLY) { @@ -1154,6 +1152,7 @@ public class LinearLayout extends ViewGroup { * * @attr ref android.R.styleable#LinearLayout_gravity */ + @android.view.RemotableViewMethod public void setGravity(int gravity) { if (mGravity != gravity) { if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { @@ -1169,6 +1168,7 @@ public class LinearLayout extends ViewGroup { } } + @android.view.RemotableViewMethod public void setHorizontalGravity(int horizontalGravity) { final int gravity = horizontalGravity & Gravity.HORIZONTAL_GRAVITY_MASK; if ((mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != gravity) { @@ -1177,6 +1177,7 @@ public class LinearLayout extends ViewGroup { } } + @android.view.RemotableViewMethod public void setVerticalGravity(int verticalGravity) { final int gravity = verticalGravity & Gravity.VERTICAL_GRAVITY_MASK; if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != gravity) { diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java index dfc7bc38431838dd5ef26069a7b91b03a070a56d..aced533192a3cfb55e35ee3fea59705c84019d4c 100644 --- a/core/java/android/widget/ListView.java +++ b/core/java/android/widget/ListView.java @@ -26,7 +26,6 @@ import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.SparseBooleanArray; -import android.util.SparseArray; import android.view.FocusFinder; import android.view.KeyEvent; import android.view.MotionEvent; @@ -127,13 +126,7 @@ public class ListView extends AbsListView { private SparseBooleanArray mCheckStates; // used for temporary calculations. - private Rect mTempRect = new Rect(); - - /** - * Used to save / restore the state of the focused child in {@link #layoutChildren()} - */ - private SparseArray mfocusRestoreChildState = new SparseArray(); - + private final Rect mTempRect = new Rect(); // the single allocated result per list view; kinda cheesey but avoids // allocating these thingies too often. @@ -1011,34 +1004,13 @@ public class ListView extends AbsListView { if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED)) { final View child = obtainView(0); - final int childViewType = mAdapter.getItemViewType(0); - - AbsListView.LayoutParams lp = (AbsListView.LayoutParams) child.getLayoutParams(); - if (lp == null) { - lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT, 0); - child.setLayoutParams(lp); - } - lp.viewType = childViewType; - - final int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, - mListPadding.left + mListPadding.right, lp.width); - - int lpHeight = lp.height; - - int childHeightSpec; - if (lpHeight > 0) { - childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); - } else { - childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - } - child.measure(childWidthSpec, childHeightSpec); + measureScrapChild(child, 0, widthMeasureSpec); childWidth = child.getMeasuredWidth(); childHeight = child.getMeasuredHeight(); - if (mRecycler.shouldRecycleViewType(childViewType)) { + if (recycleOnMeasure()) { mRecycler.addScrapView(child); } } @@ -1055,13 +1027,41 @@ public class ListView extends AbsListView { if (heightMode == MeasureSpec.AT_MOST) { // TODO: after first layout we should maybe start at the first visible position, not 0 - heightSize = measureHeightOfChildren( - MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), - 0, NO_POSITION, heightSize, -1); + heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1); } setMeasuredDimension(widthSize, heightSize); - mWidthMeasureSpec = widthMeasureSpec; + mWidthMeasureSpec = widthMeasureSpec; + } + + private void measureScrapChild(View child, int position, int widthMeasureSpec) { + LayoutParams p = (LayoutParams) child.getLayoutParams(); + if (p == null) { + p = new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT, 0); + child.setLayoutParams(p); + } + p.viewType = mAdapter.getItemViewType(position); + + int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, + mListPadding.left + mListPadding.right, p.width); + int lpHeight = p.height; + int childHeightSpec; + if (lpHeight > 0) { + childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); + } else { + childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); + } + child.measure(childWidthSpec, childHeightSpec); + } + + /** + * @return True to recycle the views used to measure this ListView in + * UNSPECIFIED/AT_MOST modes, false otherwise. + * @hide + */ + protected boolean recycleOnMeasure() { + return true; } /** @@ -1090,8 +1090,8 @@ public class ListView extends AbsListView { * startPosition is 0). * @return The height of this ListView with the given children. */ - final int measureHeightOfChildren(final int widthMeasureSpec, final int startPosition, - int endPosition, final int maxHeight, int disallowPartialChildPosition) { + final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition, + final int maxHeight, int disallowPartialChildPosition) { final ListAdapter adapter = mAdapter; if (adapter == null) { @@ -1110,29 +1110,20 @@ public class ListView extends AbsListView { // mItemCount - 1 since endPosition parameter is inclusive endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition; final AbsListView.RecycleBin recycleBin = mRecycler; + final boolean recyle = recycleOnMeasure(); + for (i = startPosition; i <= endPosition; ++i) { child = obtainView(i); - final int childViewType = adapter.getItemViewType(i); - AbsListView.LayoutParams lp = (AbsListView.LayoutParams) child.getLayoutParams(); - if (lp == null) { - lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT, 0); - child.setLayoutParams(lp); - } - lp.viewType = childViewType; + measureScrapChild(child, i, widthMeasureSpec); if (i > 0) { // Count the divider for all but one child returnedHeight += dividerHeight; } - child.measure(widthMeasureSpec, lp.height >= 0 - ? MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY) - : MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); - // Recycle the view before we possibly return from the method - if (recycleBin.shouldRecycleViewType(childViewType)) { + if (recyle) { recycleBin.addScrapView(child); } @@ -1329,6 +1320,8 @@ public class ListView extends AbsListView { final boolean blockLayoutRequests = mBlockLayoutRequests; if (!blockLayoutRequests) { mBlockLayoutRequests = true; + } else { + return; } try { @@ -1438,14 +1431,12 @@ public class ListView extends AbsListView { // we can remember the focused view to restore after relayout if the // data hasn't changed, or if the focused position is a header or footer if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) { - focusLayoutRestoreDirectChild = getFocusedChild(); - if (focusLayoutRestoreDirectChild != null) { - - // remember its state - focusLayoutRestoreDirectChild.saveHierarchyState(mfocusRestoreChildState); - - // remember the specific view that had focus - focusLayoutRestoreView = findFocus(); + focusLayoutRestoreDirectChild = focusedChild; + // remember the specific view that had focus + focusLayoutRestoreView = findFocus(); + if (focusLayoutRestoreView != null) { + // tell it we are going to mess with it + focusLayoutRestoreView.onStartTemporaryDetach(); } } requestFocus(); @@ -1528,10 +1519,6 @@ public class ListView extends AbsListView { sel.setSelected(false); mSelectorRect.setEmpty(); } - - if (sel == focusLayoutRestoreDirectChild) { - focusLayoutRestoreDirectChild.restoreHierarchyState(mfocusRestoreChildState); - } } else { positionSelector(sel); } @@ -1544,10 +1531,16 @@ public class ListView extends AbsListView { // focus (i.e. something focusable in touch mode) if (hasFocus() && focusLayoutRestoreView != null) { focusLayoutRestoreView.requestFocus(); - focusLayoutRestoreDirectChild.restoreHierarchyState(mfocusRestoreChildState); } } + // tell focus view we are done mucking with it, if it is still in + // our view hierarchy. + if (focusLayoutRestoreView != null + && focusLayoutRestoreView.getWindowToken() != null) { + focusLayoutRestoreView.onFinishTemporaryDetach(); + } + mLayoutMode = LAYOUT_NORMAL; mDataChanged = false; mNeedSync = false; @@ -1656,16 +1649,20 @@ public class ListView extends AbsListView { // Respect layout params that are already in the view. Otherwise make some up... // noinspection unchecked - AbsListView.LayoutParams p = (AbsListView.LayoutParams)child.getLayoutParams(); + AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams(); if (p == null) { p = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); } p.viewType = mAdapter.getItemViewType(position); - if (recycled) { + if (recycled || (p.recycledHeaderFooter && + p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) { attachViewToParent(child, flowDown ? -1 : 0, p); } else { + if (p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { + p.recycledHeaderFooter = true; + } addViewInLayout(child, flowDown ? -1 : 0, p, true); } @@ -1675,7 +1672,7 @@ public class ListView extends AbsListView { if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) { if (child instanceof Checkable) { - ((Checkable)child).setChecked(mCheckStates.get(position)); + ((Checkable) child).setChecked(mCheckStates.get(position)); } } @@ -1718,12 +1715,11 @@ public class ListView extends AbsListView { } /** - * Sets the currently selected item + * Sets the currently selected item. If in touch mode, the item will not be selected + * but it will still be positioned appropriately. If the specified selection position + * is less than 0, then the item at position 0 will be selected. * * @param position Index (starting at 0) of the data item to be selected. - * - * If in touch mode, the item will not be selected but it will still be positioned - * appropriately. */ @Override public void setSelection(int position) { @@ -1773,10 +1769,8 @@ public class ListView extends AbsListView { */ @Override void setSelectionInt(int position) { - mBlockLayoutRequests = true; setNextSelectedPositionInt(position); layoutChildren(); - mBlockLayoutRequests = false; } /** @@ -2180,6 +2174,10 @@ public class ListView extends AbsListView { && !isViewAncestorOf(selectedView, this)) { selectedView = null; hideSelector(); + + // but we don't want to set the ressurect position (that would make subsequent + // unhandled key events bring back the item we just scrolled off!) + mResurrectToPosition = INVALID_POSITION; } if (needToRedraw) { @@ -2646,6 +2644,7 @@ public class ListView extends AbsListView { final int listBottom = getHeight() - mListPadding.bottom; final int listTop = mListPadding.top; + final AbsListView.RecycleBin recycleBin = mRecycler; if (amount < 0) { // shifted items up @@ -2673,8 +2672,13 @@ public class ListView extends AbsListView { // top views may be panned off screen View first = getChildAt(0); while (first.getBottom() < listTop) { - removeViewInLayout(first); - mRecycler.addScrapView(first); + AbsListView.LayoutParams layoutParams = (LayoutParams) first.getLayoutParams(); + if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) { + removeViewInLayout(first); + recycleBin.addScrapView(first); + } else { + detachViewFromParent(first); + } first = getChildAt(0); mFirstPosition++; } @@ -2699,8 +2703,13 @@ public class ListView extends AbsListView { // bottom view may be panned off screen while (last.getTop() > listBottom) { - removeViewInLayout(last); - mRecycler.addScrapView(last); + AbsListView.LayoutParams layoutParams = (LayoutParams) last.getLayoutParams(); + if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) { + removeViewInLayout(last); + recycleBin.addScrapView(last); + } else { + detachViewFromParent(last); + } last = getChildAt(--lastIndex); } } diff --git a/core/java/android/widget/MediaController.java b/core/java/android/widget/MediaController.java index f2cec92e708e45fa1203dcd2285e6b6deaf0c1e1..227fb9571d2f749f51c812c037ae5b5246719b93 100644 --- a/core/java/android/widget/MediaController.java +++ b/core/java/android/widget/MediaController.java @@ -451,6 +451,7 @@ public class MediaController extends FrameLayout { public void onProgressChanged(SeekBar bar, int progress, boolean fromtouch) { if (fromtouch) { mDragging = true; + duration = mPlayer.getDuration(); long newposition = (duration * progress) / 1000L; mPlayer.seekTo( (int) newposition); if (mCurrentTime != null) diff --git a/core/java/android/widget/MultiAutoCompleteTextView.java b/core/java/android/widget/MultiAutoCompleteTextView.java index 59a931011ad7b18047ba9f78bb621a693b19e25e..05abc2661eb2be3c6cbc923abb5a05dbdb79ca42 100644 --- a/core/java/android/widget/MultiAutoCompleteTextView.java +++ b/core/java/android/widget/MultiAutoCompleteTextView.java @@ -126,7 +126,7 @@ public class MultiAutoCompleteTextView extends AutoCompleteTextView { Editable text = getText(); int end = getSelectionEnd(); - if (end < 0) { + if (end < 0 || mTokenizer == null) { return false; } @@ -147,7 +147,7 @@ public class MultiAutoCompleteTextView extends AutoCompleteTextView { public void performValidation() { Validator v = getValidator(); - if (v == null) { + if (v == null || mTokenizer == null) { return; } diff --git a/core/java/android/widget/PopupWindow.java b/core/java/android/widget/PopupWindow.java index 50248c1064c0b8eb52881091923d5b31c0cfe11c..a4f729f6f6eb4cd2e96e13ad02f0d8743d2dca87 100644 --- a/core/java/android/widget/PopupWindow.java +++ b/core/java/android/widget/PopupWindow.java @@ -24,15 +24,20 @@ import android.view.View; import android.view.WindowManager; import android.view.Gravity; import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.view.ViewTreeObserver.OnScrollChangedListener; import android.view.View.OnTouchListener; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; +import android.graphics.drawable.StateListDrawable; import android.os.IBinder; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; +import java.lang.ref.WeakReference; + /** *

          A popup window that can be used to display an arbitrary view. The popup * windows is a floating container that appears on top of the current @@ -98,6 +103,8 @@ public class PopupWindow { private Rect mTempRect = new Rect(); private Drawable mBackground; + private Drawable mAboveAnchorBackgroundDrawable; + private Drawable mBelowAnchorBackgroundDrawable; private boolean mAboveAnchor; @@ -109,7 +116,23 @@ public class PopupWindow { private static final int[] ABOVE_ANCHOR_STATE_SET = new int[] { com.android.internal.R.attr.state_above_anchor }; - + + private WeakReference mAnchor; + private OnScrollChangedListener mOnScrollChangedListener = + new OnScrollChangedListener() { + public void onScrollChanged() { + View anchor = mAnchor.get(); + if (anchor != null && mPopupView != null) { + WindowManager.LayoutParams p = (WindowManager.LayoutParams) + mPopupView.getLayoutParams(); + + mAboveAnchor = findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff); + update(p.x, p.y, -1, -1, true); + } + } + }; + private int mAnchorXoff, mAnchorYoff; + /** *

          Create a new empty, non focusable popup window of dimension (0,0).

          * @@ -144,6 +167,43 @@ public class PopupWindow { mBackground = a.getDrawable(R.styleable.PopupWindow_popupBackground); + // If this is a StateListDrawable, try to find and store the drawable to be + // used when the drop-down is placed above its anchor view, and the one to be + // used when the drop-down is placed below its anchor view. We extract + // the drawables ourselves to work around a problem with using refreshDrawableState + // that it will take into account the padding of all drawables specified in a + // StateListDrawable, thus adding superfluous padding to drop-down views. + // + // We assume a StateListDrawable will have a drawable for ABOVE_ANCHOR_STATE_SET and + // at least one other drawable, intended for the 'below-anchor state'. + if (mBackground instanceof StateListDrawable) { + StateListDrawable background = (StateListDrawable) mBackground; + + // Find the above-anchor view - this one's easy, it should be labeled as such. + int aboveAnchorStateIndex = background.getStateDrawableIndex(ABOVE_ANCHOR_STATE_SET); + + // Now, for the below-anchor view, look for any other drawable specified in the + // StateListDrawable which is not for the above-anchor state and use that. + int count = background.getStateCount(); + int belowAnchorStateIndex = -1; + for (int i = 0; i < count; i++) { + if (i != aboveAnchorStateIndex) { + belowAnchorStateIndex = i; + break; + } + } + + // Store the drawables we found, if we found them. Otherwise, set them both + // to null so that we'll just use refreshDrawableState. + if (aboveAnchorStateIndex != -1 && belowAnchorStateIndex != -1) { + mAboveAnchorBackgroundDrawable = background.getStateDrawable(aboveAnchorStateIndex); + mBelowAnchorBackgroundDrawable = background.getStateDrawable(belowAnchorStateIndex); + } else { + mBelowAnchorBackgroundDrawable = null; + mAboveAnchorBackgroundDrawable = null; + } + } + a.recycle(); } @@ -579,6 +639,8 @@ public class PopupWindow { return; } + unregisterForScrollChanged(); + mIsShowing = true; mIsDropdown = false; @@ -617,6 +679,8 @@ public class PopupWindow { * the popup in its entirety, this method tries to find a parent scroll * view to scroll. If no parent scroll view can be scrolled, the bottom-left * corner of the popup is pinned at the top left corner of the anchor view.

          + *

          If the view later scrolls to move anchor to a different + * location, the popup will be moved correspondingly.

          * * @param anchor the view on which to pin the popup window * @@ -627,21 +691,53 @@ public class PopupWindow { return; } + registerForScrollChanged(anchor, xoff, yoff); + mIsShowing = true; mIsDropdown = true; WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken()); preparePopup(p); + mAboveAnchor = findDropDownPosition(anchor, p, xoff, yoff); + if (mBackground != null) { - mPopupView.refreshDrawableState(); + // If the background drawable provided was a StateListDrawable with above-anchor + // and below-anchor states, use those. Otherwise rely on refreshDrawableState to + // do the job. + if (mAboveAnchorBackgroundDrawable != null) { + if (mAboveAnchor) { + mPopupView.setBackgroundDrawable(mAboveAnchorBackgroundDrawable); + } else { + mPopupView.setBackgroundDrawable(mBelowAnchorBackgroundDrawable); + } + } else { + mPopupView.refreshDrawableState(); + } } - mAboveAnchor = findDropDownPosition(anchor, p, xoff, yoff); + if (mHeightMode < 0) p.height = mLastHeight = mHeightMode; if (mWidthMode < 0) p.width = mLastWidth = mWidthMode; + p.windowAnimations = computeAnimationResource(); + invokePopup(p); } + /** + * Indicates whether the popup is showing above (the y coordinate of the popup's bottom + * is less than the y coordinate of the anchor) or below the anchor view (the y coordinate + * of the popup is greater than y coordinate of the anchor's bottom). + * + * The value returned + * by this method is meaningful only after {@link #showAsDropDown(android.view.View)} + * or {@link #showAsDropDown(android.view.View, int, int)} was invoked. + * + * @return True if this popup is showing above the anchor view, false otherwise. + */ + public boolean isAboveAnchor() { + return mAboveAnchor; + } + /** *

          Prepare the popup by embedding in into a new ViewGroup if the * background drawable is not null. If embedding is required, the layout @@ -652,28 +748,22 @@ public class PopupWindow { */ private void preparePopup(WindowManager.LayoutParams p) { if (mBackground != null) { + final ViewGroup.LayoutParams layoutParams = mContentView.getLayoutParams(); + int height = ViewGroup.LayoutParams.FILL_PARENT; + if (layoutParams != null && + layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) { + height = ViewGroup.LayoutParams.WRAP_CONTENT; + } + // when a background is available, we embed the content view // within another view that owns the background drawable PopupViewContainer popupViewContainer = new PopupViewContainer(mContext); PopupViewContainer.LayoutParams listParams = new PopupViewContainer.LayoutParams( - ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.FILL_PARENT + ViewGroup.LayoutParams.FILL_PARENT, height ); popupViewContainer.setBackgroundDrawable(mBackground); popupViewContainer.addView(mContentView, listParams); - if (p.height >= 0) { - // accomodate the popup's height to take into account the - // background's padding - p.height += popupViewContainer.getPaddingTop() + - popupViewContainer.getPaddingBottom(); - } - if (p.width >= 0) { - // accomodate the popup's width to take into account the - // background's padding - p.width += popupViewContainer.getPaddingLeft() + - popupViewContainer.getPaddingRight(); - } mPopupView = popupViewContainer; } else { mPopupView = mContentView; @@ -720,7 +810,8 @@ public class PopupWindow { p.flags = computeFlags(p.flags); p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL; p.token = token; - + p.setTitle("PopupWindow:" + Integer.toHexString(hashCode())); + return p; } @@ -746,7 +837,7 @@ public class PopupWindow { if (!mTouchable) { curFlags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; } - if (mTouchable) { + if (mOutsideTouchable) { curFlags |= WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; } if (!mClippingEnabled) { @@ -781,7 +872,9 @@ public class PopupWindow { * * @return true if the popup is translated upwards to fit on screen */ - private boolean findDropDownPosition(View anchor, WindowManager.LayoutParams p, int xoff, int yoff) { + private boolean findDropDownPosition(View anchor, WindowManager.LayoutParams p, + int xoff, int yoff) { + anchor.getLocationInWindow(mDrawingLocation); p.x = mDrawingLocation[0] + xoff; p.y = mDrawingLocation[1] + anchor.getMeasuredHeight() + yoff; @@ -795,8 +888,7 @@ public class PopupWindow { anchor.getWindowVisibleDisplayFrame(displayFrame); final View root = anchor.getRootView(); - if (mScreenLocation[1] + anchor.getMeasuredHeight() + yoff + mPopupHeight > displayFrame.bottom - || p.x + mPopupWidth - root.getWidth() > 0) { + if (p.y + mPopupHeight > displayFrame.bottom || p.x + mPopupWidth - root.getWidth() > 0) { // if the drop down disappears at the bottom of the screen. we try to // scroll a parent scrollview or move the drop down back up on top of // the edit box @@ -815,11 +907,11 @@ public class PopupWindow { // determine whether there is more space above or below the anchor anchor.getLocationOnScreen(mScreenLocation); - onTop = (displayFrame.bottom - mScreenLocation[1] - anchor.getMeasuredHeight() - yoff) - < (mScreenLocation[1] - yoff - displayFrame.top); + onTop = (displayFrame.bottom - mScreenLocation[1] - anchor.getMeasuredHeight() - yoff) < + (mScreenLocation[1] - yoff - displayFrame.top); if (onTop) { p.gravity = Gravity.LEFT | Gravity.BOTTOM; - p.y = root.getHeight() - mDrawingLocation[1] - yoff; + p.y = root.getHeight() - mDrawingLocation[1] + yoff; } else { p.y = mDrawingLocation[1] + anchor.getMeasuredHeight() + yoff; } @@ -841,15 +933,30 @@ public class PopupWindow { * shown. */ public int getMaxAvailableHeight(View anchor) { + return getMaxAvailableHeight(anchor, 0); + } + + /** + * Returns the maximum height that is available for the popup to be + * completely shown. It is recommended that this height be the maximum for + * the popup's height, otherwise it is possible that the popup will be + * clipped. + * + * @param anchor The view on which the popup window must be anchored. + * @param yOffset y offset from the view's bottom edge + * @return The maximum available height for the popup to be completely + * shown. + */ + public int getMaxAvailableHeight(View anchor, int yOffset) { final Rect displayFrame = new Rect(); anchor.getWindowVisibleDisplayFrame(displayFrame); final int[] anchorPos = mDrawingLocation; anchor.getLocationOnScreen(anchorPos); - final int distanceToBottom = displayFrame.bottom - - (anchorPos[1] + anchor.getHeight()); - final int distanceToTop = anchorPos[1] - displayFrame.top; + final int distanceToBottom = displayFrame.bottom - + (anchorPos[1] + anchor.getHeight()) - yOffset; + final int distanceToTop = anchorPos[1] - displayFrame.top + yOffset; // anchorPos[1] is distance from anchor to top of screen int returnedHeight = Math.max(distanceToBottom, distanceToTop); @@ -870,6 +977,8 @@ public class PopupWindow { */ public void dismiss() { if (isShowing() && mPopupView != null) { + unregisterForScrollChanged(); + mWindowManager.removeView(mPopupView); if (mPopupView != mContentView && mPopupView instanceof ViewGroup) { ((ViewGroup) mPopupView).removeView(mContentView); @@ -938,11 +1047,32 @@ public class PopupWindow { * @param height the new height, can be -1 to ignore */ public void update(int x, int y, int width, int height) { + update(x, y, width, height, false); + } + + /** + *

          Updates the position and the dimension of the popup window. Width and + * height can be set to -1 to update location only. Calling this function + * also updates the window with the current popup state as + * described for {@link #update()}.

          + * + * @param x the new x location + * @param y the new y location + * @param width the new width, can be -1 to ignore + * @param height the new height, can be -1 to ignore + * @param force reposition the window even if the specified position + * already seems to correspond to the LayoutParams + * + * @hide pending API council approval + */ + public void update(int x, int y, int width, int height, boolean force) { if (width != -1) { + mLastWidth = width; setWidth(width); } if (height != -1) { + mLastHeight = height; setHeight(height); } @@ -953,7 +1083,7 @@ public class PopupWindow { WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams(); - boolean update = false; + boolean update = force; final int finalWidth = mWidthMode < 0 ? mWidthMode : mLastWidth; if (width != -1 && p.width != finalWidth) { @@ -990,22 +1120,6 @@ public class PopupWindow { } if (update) { - if (mPopupView != mContentView) { - final View popupViewContainer = mPopupView; - if (p.height >= 0) { - // accomodate the popup's height to take into account the - // background's padding - p.height += popupViewContainer.getPaddingTop() + - popupViewContainer.getPaddingBottom(); - } - if (p.width >= 0) { - // accomodate the popup's width to take into account the - // background's padding - p.width += popupViewContainer.getPaddingLeft() + - popupViewContainer.getPaddingRight(); - } - } - mWindowManager.updateViewLayout(mPopupView, p); } } @@ -1029,6 +1143,8 @@ public class PopupWindow { * height can be set to -1 to update location only. Calling this function * also updates the window with the current popup state as * described for {@link #update()}.

          + *

          If the view later scrolls to move anchor to a different + * location, the popup will be moved correspondingly.

          * * @param anchor the popup's anchor view * @param xoff x offset from the view's left edge @@ -1041,6 +1157,12 @@ public class PopupWindow { return; } + WeakReference oldAnchor = mAnchor; + if (oldAnchor == null || oldAnchor.get() != anchor || + mAnchorXoff != xoff || mAnchorYoff != yoff) { + registerForScrollChanged(anchor, xoff, yoff); + } + WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams(); @@ -1055,10 +1177,10 @@ public class PopupWindow { mPopupHeight = height; } - findDropDownPosition(anchor, p, xoff, yoff); + mAboveAnchor = findDropDownPosition(anchor, p, xoff, yoff); update(p.x, p.y, width, height); } - + /** * Listener that is called when this popup window is dismissed. */ @@ -1068,7 +1190,33 @@ public class PopupWindow { */ public void onDismiss(); } - + + private void unregisterForScrollChanged() { + WeakReference anchorRef = mAnchor; + View anchor = null; + if (anchorRef != null) { + anchor = anchorRef.get(); + } + if (anchor != null) { + ViewTreeObserver vto = anchor.getViewTreeObserver(); + vto.removeOnScrollChangedListener(mOnScrollChangedListener); + } + mAnchor = null; + } + + private void registerForScrollChanged(View anchor, int xoff, int yoff) { + unregisterForScrollChanged(); + + mAnchor = new WeakReference(anchor); + ViewTreeObserver vto = anchor.getViewTreeObserver(); + if (vto != null) { + vto.addOnScrollChangedListener(mOnScrollChangedListener); + } + + mAnchorXoff = xoff; + mAnchorYoff = yoff; + } + private class PopupViewContainer extends FrameLayout { public PopupViewContainer(Context context) { diff --git a/core/java/android/widget/ProgressBar.java b/core/java/android/widget/ProgressBar.java index 2e04b5d38d1bb7ba0ebfbf059b0871ad4f105662..441414a20de4ebda7ab179b9fd7895ce07ecf674 100644 --- a/core/java/android/widget/ProgressBar.java +++ b/core/java/android/widget/ProgressBar.java @@ -344,6 +344,7 @@ public class ProgressBar extends View { * * @param indeterminate true to enable the indeterminate mode */ + @android.view.RemotableViewMethod public synchronized void setIndeterminate(boolean indeterminate) { if ((!mOnlyIndeterminate || !mIndeterminate) && indeterminate != mIndeterminate) { mIndeterminate = indeterminate; @@ -525,10 +526,12 @@ public class ProgressBar extends View { * @see #getProgress() * @see #incrementProgressBy(int) */ + @android.view.RemotableViewMethod public synchronized void setProgress(int progress) { setProgress(progress, false); } + @android.view.RemotableViewMethod synchronized void setProgress(int progress, boolean fromUser) { if (mIndeterminate) { return; @@ -560,6 +563,7 @@ public class ProgressBar extends View { * @see #getSecondaryProgress() * @see #incrementSecondaryProgressBy(int) */ + @android.view.RemotableViewMethod public synchronized void setSecondaryProgress(int secondaryProgress) { if (mIndeterminate) { return; @@ -633,6 +637,7 @@ public class ProgressBar extends View { * @see #setProgress(int) * @see #setSecondaryProgress(int) */ + @android.view.RemotableViewMethod public synchronized void setMax(int max) { if (max < 0) { max = 0; @@ -758,10 +763,10 @@ public class ProgressBar extends View { @Override public void invalidateDrawable(Drawable dr) { if (!mInDrawing) { - if (dr == mProgressDrawable || dr == mIndeterminateDrawable) { + if (verifyDrawable(dr)) { final Rect dirty = dr.getBounds(); final int scrollX = mScrollX + mPaddingLeft; - final int scrollY = mScrollY + mPaddingRight; + final int scrollY = mScrollY + mPaddingTop; invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); diff --git a/core/java/android/widget/RadioGroup.java b/core/java/android/widget/RadioGroup.java index ed8df229e6b58d50c266c64845b925d963baa6e1..393346a314f7b1ad20c617c494904f599391c081 100644 --- a/core/java/android/widget/RadioGroup.java +++ b/core/java/android/widget/RadioGroup.java @@ -122,6 +122,23 @@ public class RadioGroup extends LinearLayout { } } + @Override + public void addView(View child, int index, ViewGroup.LayoutParams params) { + if (child instanceof RadioButton) { + final RadioButton button = (RadioButton) child; + if (button.isChecked()) { + mProtectFromCheckedChange = true; + if (mCheckedId != -1) { + setCheckedStateForView(mCheckedId, false); + } + mProtectFromCheckedChange = false; + setCheckedId(button.getId()); + } + } + + super.addView(child, index, params); + } + /** *

          Sets the selection to the radio button whose identifier is passed in * parameter. Using -1 as the selection identifier clears the selection; diff --git a/core/java/android/widget/RelativeLayout.java b/core/java/android/widget/RelativeLayout.java index 91d58051b858004c3d5a64bcf409d8e73cdfd8e8..52c421c7dd9454ecd6012b955024b005ce4ea01d 100644 --- a/core/java/android/widget/RelativeLayout.java +++ b/core/java/android/widget/RelativeLayout.java @@ -22,6 +22,7 @@ import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.Gravity; +import android.view.ViewDebug; import android.widget.RemoteViews.RemoteView; import android.graphics.Rect; import com.android.internal.R; @@ -152,7 +153,7 @@ public class RelativeLayout extends ViewGroup { private void initFromAttributes(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RelativeLayout); - mIgnoreGravity = a.getResourceId(R.styleable.RelativeLayout_ignoreGravity, 0); + mIgnoreGravity = a.getResourceId(R.styleable.RelativeLayout_ignoreGravity, View.NO_ID); mGravity = a.getInt(R.styleable.RelativeLayout_gravity, mGravity); a.recycle(); } @@ -168,6 +169,7 @@ public class RelativeLayout extends ViewGroup { * * @attr ref android.R.styleable#RelativeLayout_ignoreGravity */ + @android.view.RemotableViewMethod public void setIgnoreGravity(int viewId) { mIgnoreGravity = viewId; } @@ -183,6 +185,7 @@ public class RelativeLayout extends ViewGroup { * * @attr ref android.R.styleable#RelativeLayout_gravity */ + @android.view.RemotableViewMethod public void setGravity(int gravity) { if (mGravity != gravity) { if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { @@ -198,6 +201,7 @@ public class RelativeLayout extends ViewGroup { } } + @android.view.RemotableViewMethod public void setHorizontalGravity(int horizontalGravity) { final int gravity = horizontalGravity & Gravity.HORIZONTAL_GRAVITY_MASK; if ((mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != gravity) { @@ -206,6 +210,7 @@ public class RelativeLayout extends ViewGroup { } } + @android.view.RemotableViewMethod public void setVerticalGravity(int verticalGravity) { final int gravity = verticalGravity & Gravity.VERTICAL_GRAVITY_MASK; if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != gravity) { @@ -263,7 +268,7 @@ public class RelativeLayout extends ViewGroup { int right = Integer.MIN_VALUE; int bottom = Integer.MIN_VALUE; - if ((horizontalGravity || verticalGravity) && mIgnoreGravity != 0) { + if ((horizontalGravity || verticalGravity) && mIgnoreGravity != View.NO_ID) { ignore = findViewById(mIgnoreGravity); } @@ -799,13 +804,33 @@ public class RelativeLayout extends ViewGroup { * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerVertical */ public static class LayoutParams extends ViewGroup.MarginLayoutParams { + @ViewDebug.ExportedProperty(resolveId = true, indexMapping = { + @ViewDebug.IntToString(from = ABOVE, to = "above"), + @ViewDebug.IntToString(from = ALIGN_BASELINE, to = "alignBaseline"), + @ViewDebug.IntToString(from = ALIGN_BOTTOM, to = "alignBottom"), + @ViewDebug.IntToString(from = ALIGN_LEFT, to = "alignLeft"), + @ViewDebug.IntToString(from = ALIGN_PARENT_BOTTOM, to = "alignParentBottom"), + @ViewDebug.IntToString(from = ALIGN_PARENT_LEFT, to = "alignParentLeft"), + @ViewDebug.IntToString(from = ALIGN_PARENT_RIGHT, to = "alignParentRight"), + @ViewDebug.IntToString(from = ALIGN_PARENT_TOP, to = "alignParentTop"), + @ViewDebug.IntToString(from = ALIGN_RIGHT, to = "alignRight"), + @ViewDebug.IntToString(from = ALIGN_TOP, to = "alignTop"), + @ViewDebug.IntToString(from = BELOW, to = "below"), + @ViewDebug.IntToString(from = CENTER_HORIZONTAL, to = "centerHorizontal"), + @ViewDebug.IntToString(from = CENTER_IN_PARENT, to = "center"), + @ViewDebug.IntToString(from = CENTER_VERTICAL, to = "centerVertical"), + @ViewDebug.IntToString(from = LEFT_OF, to = "leftOf"), + @ViewDebug.IntToString(from = RIGHT_OF, to = "rightOf") + }, mapping = { @ViewDebug.IntToString(from = TRUE, to = "true") }) private int[] mRules = new int[VERB_COUNT]; + private int mLeft, mTop, mRight, mBottom; /** * When true, uses the parent as the anchor if the anchor doesn't exist or if * the anchor's visibility is GONE. */ + @ViewDebug.ExportedProperty public boolean alignWithParent; public LayoutParams(Context c, AttributeSet attrs) { diff --git a/core/java/android/gadget/GadgetInfo.aidl b/core/java/android/widget/RemoteViews.aidl similarity index 92% rename from core/java/android/gadget/GadgetInfo.aidl rename to core/java/android/widget/RemoteViews.aidl index 72315454b6dd84066ed3dfd3d21f5e59773a9648..ec86410cf89c12fc841055d5262330ecc6462221 100644 --- a/core/java/android/gadget/GadgetInfo.aidl +++ b/core/java/android/widget/RemoteViews.aidl @@ -14,6 +14,6 @@ * limitations under the License. */ -package android.gadget; +package android.widget; -parcelable GadgetInfo; +parcelable RemoteViews; diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java index 572109574aa02341f1cad7cb802e53cbc1ac054f..e000d2e22781e8bcc88fc5d47553315c120fbbef 100644 --- a/core/java/android/widget/RemoteViews.java +++ b/core/java/android/widget/RemoteViews.java @@ -22,6 +22,7 @@ import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; +import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; @@ -30,15 +31,21 @@ import android.os.Parcelable; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; +import android.view.RemotableViewMethod; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater.Filter; import android.view.View.OnClickListener; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import java.lang.Class; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.ArrayList; @@ -77,19 +84,22 @@ public class RemoteViews implements Parcelable, Filter { /** - * This annotation indicates that a subclass of View is alllowed to be used with the - * {@link android.widget.RemoteViews} mechanism. + * This annotation indicates that a subclass of View is alllowed to be used + * with the {@link android.widget.RemoteViews} mechanism. */ @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface RemoteView { } - + /** * Exception to send when something goes wrong executing an action * */ public static class ActionException extends RuntimeException { + public ActionException(Exception ex) { + super(ex); + } public ActionException(String message) { super(message); } @@ -107,320 +117,349 @@ public class RemoteViews implements Parcelable, Filter { return 0; } }; - - /** - * Equivalent to calling View.setVisibility - */ - private class SetViewVisibility extends Action { - public SetViewVisibility(int id, int vis) { - viewId = id; - visibility = vis; - } - - public SetViewVisibility(Parcel parcel) { - viewId = parcel.readInt(); - visibility = parcel.readInt(); - } - - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(TAG); - dest.writeInt(viewId); - dest.writeInt(visibility); - } - - @Override - public void apply(View root) { - View target = root.findViewById(viewId); - if (target != null) { - target.setVisibility(visibility); - } - } - - private int viewId; - private int visibility; - public final static int TAG = 0; - } - + /** - * Equivalent to calling TextView.setText + * Equivalent to calling + * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)} + * to launch the provided {@link PendingIntent}. */ - private class SetTextViewText extends Action { - public SetTextViewText(int id, CharSequence t) { - viewId = id; - text = t; + private class SetOnClickPendingIntent extends Action { + public SetOnClickPendingIntent(int id, PendingIntent pendingIntent) { + this.viewId = id; + this.pendingIntent = pendingIntent; } - public SetTextViewText(Parcel parcel) { + public SetOnClickPendingIntent(Parcel parcel) { viewId = parcel.readInt(); - text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel); + pendingIntent = PendingIntent.readPendingIntentOrNullFromParcel(parcel); } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(TAG); dest.writeInt(viewId); - TextUtils.writeToParcel(text, dest, flags); + pendingIntent.writeToParcel(dest, 0 /* no flags */); } @Override public void apply(View root) { - TextView target = (TextView) root.findViewById(viewId); - if (target != null) { - target.setText(text); + final View target = root.findViewById(viewId); + if (target != null && pendingIntent != null) { + OnClickListener listener = new OnClickListener() { + public void onClick(View v) { + try { + // TODO: Unregister this handler if PendingIntent.FLAG_ONE_SHOT? + pendingIntent.send(); + } catch (CanceledException e) { + throw new ActionException(e.toString()); + } + } + }; + target.setOnClickListener(listener); } } int viewId; - CharSequence text; + PendingIntent pendingIntent; + public final static int TAG = 1; } /** - * Equivalent to calling ImageView.setResource + * Equivalent to calling a combination of {@link Drawable#setAlpha(int)}, + * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)}, + * and/or {@link Drawable#setLevel(int)} on the {@link Drawable} of a given view. + *

          + * These operations will be performed on the {@link Drawable} returned by the + * target {@link View#getBackground()} by default. If targetBackground is false, + * we assume the target is an {@link ImageView} and try applying the operations + * to {@link ImageView#getDrawable()}. + *

          + * You can omit specific calls by marking their values with null or -1. */ - private class SetImageViewResource extends Action { - public SetImageViewResource(int id, int src) { - viewId = id; - srcId = src; + private class SetDrawableParameters extends Action { + public SetDrawableParameters(int id, boolean targetBackground, int alpha, + int colorFilter, PorterDuff.Mode mode, int level) { + this.viewId = id; + this.targetBackground = targetBackground; + this.alpha = alpha; + this.colorFilter = colorFilter; + this.filterMode = mode; + this.level = level; } - public SetImageViewResource(Parcel parcel) { + public SetDrawableParameters(Parcel parcel) { viewId = parcel.readInt(); - srcId = parcel.readInt(); - } - - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(TAG); - dest.writeInt(viewId); - dest.writeInt(srcId); - } - - @Override - public void apply(View root) { - ImageView target = (ImageView) root.findViewById(viewId); - Drawable d = mContext.getResources().getDrawable(srcId); - if (target != null) { - target.setImageDrawable(d); + targetBackground = parcel.readInt() != 0; + alpha = parcel.readInt(); + colorFilter = parcel.readInt(); + boolean hasMode = parcel.readInt() != 0; + if (hasMode) { + filterMode = PorterDuff.Mode.valueOf(parcel.readString()); + } else { + filterMode = null; } - } - - int viewId; - int srcId; - public final static int TAG = 2; - } - - /** - * Equivalent to calling ImageView.setImageURI - */ - private class SetImageViewUri extends Action { - public SetImageViewUri(int id, Uri u) { - viewId = id; - uri = u; - } - - public SetImageViewUri(Parcel parcel) { - viewId = parcel.readInt(); - uri = Uri.CREATOR.createFromParcel(parcel); + level = parcel.readInt(); } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(TAG); dest.writeInt(viewId); - Uri.writeToParcel(dest, uri); + dest.writeInt(targetBackground ? 1 : 0); + dest.writeInt(alpha); + dest.writeInt(colorFilter); + if (filterMode != null) { + dest.writeInt(1); + dest.writeString(filterMode.toString()); + } else { + dest.writeInt(0); + } + dest.writeInt(level); } @Override public void apply(View root) { - ImageView target = (ImageView) root.findViewById(viewId); - if (target != null) { - target.setImageURI(uri); + final View target = root.findViewById(viewId); + if (target == null) { + return; + } + + // Pick the correct drawable to modify for this view + Drawable targetDrawable = null; + if (targetBackground) { + targetDrawable = target.getBackground(); + } else if (target instanceof ImageView) { + ImageView imageView = (ImageView) target; + targetDrawable = imageView.getDrawable(); + } + + // Perform modifications only if values are set correctly + if (alpha != -1) { + targetDrawable.setAlpha(alpha); + } + if (colorFilter != -1 && filterMode != null) { + targetDrawable.setColorFilter(colorFilter, filterMode); + } + if (level != -1) { + targetDrawable.setLevel(level); } } int viewId; - Uri uri; + boolean targetBackground; + int alpha; + int colorFilter; + PorterDuff.Mode filterMode; + int level; + public final static int TAG = 3; } - + /** - * Equivalent to calling ImageView.setImageBitmap + * Base class for the reflection actions. */ - private class SetImageViewBitmap extends Action { - public SetImageViewBitmap(int id, Bitmap src) { - viewId = id; - bitmap = src; - } + private class ReflectionAction extends Action { + static final int TAG = 2; + + static final int BOOLEAN = 1; + static final int BYTE = 2; + static final int SHORT = 3; + static final int INT = 4; + static final int LONG = 5; + static final int FLOAT = 6; + static final int DOUBLE = 7; + static final int CHAR = 8; + static final int STRING = 9; + static final int CHAR_SEQUENCE = 10; + static final int URI = 11; + static final int BITMAP = 12; - public SetImageViewBitmap(Parcel parcel) { - viewId = parcel.readInt(); - bitmap = Bitmap.CREATOR.createFromParcel(parcel); + int viewId; + String methodName; + int type; + Object value; + + ReflectionAction(int viewId, String methodName, int type, Object value) { + this.viewId = viewId; + this.methodName = methodName; + this.type = type; + this.value = value; + } + + ReflectionAction(Parcel in) { + this.viewId = in.readInt(); + this.methodName = in.readString(); + this.type = in.readInt(); + if (false) { + Log.d("RemoteViews", "read viewId=0x" + Integer.toHexString(this.viewId) + + " methodName=" + this.methodName + " type=" + this.type); + } + switch (this.type) { + case BOOLEAN: + this.value = in.readInt() != 0; + break; + case BYTE: + this.value = in.readByte(); + break; + case SHORT: + this.value = (short)in.readInt(); + break; + case INT: + this.value = in.readInt(); + break; + case LONG: + this.value = in.readLong(); + break; + case FLOAT: + this.value = in.readFloat(); + break; + case DOUBLE: + this.value = in.readDouble(); + break; + case CHAR: + this.value = (char)in.readInt(); + break; + case STRING: + this.value = in.readString(); + break; + case CHAR_SEQUENCE: + this.value = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); + break; + case URI: + this.value = Uri.CREATOR.createFromParcel(in); + break; + case BITMAP: + this.value = Bitmap.CREATOR.createFromParcel(in); + break; + default: + break; + } } - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(TAG); - dest.writeInt(viewId); - if (bitmap != null) { - bitmap.writeToParcel(dest, flags); + public void writeToParcel(Parcel out, int flags) { + out.writeInt(TAG); + out.writeInt(this.viewId); + out.writeString(this.methodName); + out.writeInt(this.type); + if (false) { + Log.d("RemoteViews", "write viewId=0x" + Integer.toHexString(this.viewId) + + " methodName=" + this.methodName + " type=" + this.type); + } + switch (this.type) { + case BOOLEAN: + out.writeInt(((Boolean)this.value).booleanValue() ? 1 : 0); + break; + case BYTE: + out.writeByte(((Byte)this.value).byteValue()); + break; + case SHORT: + out.writeInt(((Short)this.value).shortValue()); + break; + case INT: + out.writeInt(((Integer)this.value).intValue()); + break; + case LONG: + out.writeLong(((Long)this.value).longValue()); + break; + case FLOAT: + out.writeFloat(((Float)this.value).floatValue()); + break; + case DOUBLE: + out.writeDouble(((Double)this.value).doubleValue()); + break; + case CHAR: + out.writeInt((int)((Character)this.value).charValue()); + break; + case STRING: + out.writeString((String)this.value); + break; + case CHAR_SEQUENCE: + TextUtils.writeToParcel((CharSequence)this.value, out, flags); + break; + case URI: + ((Uri)this.value).writeToParcel(out, flags); + break; + case BITMAP: + ((Bitmap)this.value).writeToParcel(out, flags); + break; + default: + break; } } - @Override - public void apply(View root) { - if (bitmap != null) { - ImageView target = (ImageView) root.findViewById(viewId); - Drawable d = new BitmapDrawable(bitmap); - if (target != null) { - target.setImageDrawable(d); - } + private Class getParameterType() { + switch (this.type) { + case BOOLEAN: + return boolean.class; + case BYTE: + return byte.class; + case SHORT: + return short.class; + case INT: + return int.class; + case LONG: + return long.class; + case FLOAT: + return float.class; + case DOUBLE: + return double.class; + case CHAR: + return char.class; + case STRING: + return String.class; + case CHAR_SEQUENCE: + return CharSequence.class; + case URI: + return Uri.class; + case BITMAP: + return Bitmap.class; + default: + return null; } } - int viewId; - Bitmap bitmap; - public final static int TAG = 4; - } - - /** - * Equivalent to calling Chronometer.setBase, Chronometer.setFormat, - * and Chronometer.start/stop. - */ - private class SetChronometer extends Action { - public SetChronometer(int id, long base, String format, boolean running) { - this.viewId = id; - this.base = base; - this.format = format; - this.running = running; - } - - public SetChronometer(Parcel parcel) { - viewId = parcel.readInt(); - base = parcel.readLong(); - format = parcel.readString(); - running = parcel.readInt() != 0; - } - - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(TAG); - dest.writeInt(viewId); - dest.writeLong(base); - dest.writeString(format); - dest.writeInt(running ? 1 : 0); - } - @Override public void apply(View root) { - Chronometer target = (Chronometer) root.findViewById(viewId); - if (target != null) { - target.setBase(base); - target.setFormat(format); - if (running) { - target.start(); - } else { - target.stop(); - } + final View view = root.findViewById(viewId); + if (view == null) { + throw new ActionException("can't find view: 0x" + Integer.toHexString(viewId)); } - } - - int viewId; - boolean running; - long base; - String format; - public final static int TAG = 5; - } - - /** - * Equivalent to calling ProgressBar.setMax, ProgressBar.setProgress and - * ProgressBar.setIndeterminate - */ - private class SetProgressBar extends Action { - public SetProgressBar(int id, int max, int progress, boolean indeterminate) { - this.viewId = id; - this.progress = progress; - this.max = max; - this.indeterminate = indeterminate; - } - - public SetProgressBar(Parcel parcel) { - viewId = parcel.readInt(); - progress = parcel.readInt(); - max = parcel.readInt(); - indeterminate = parcel.readInt() != 0; - } - - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(TAG); - dest.writeInt(viewId); - dest.writeInt(progress); - dest.writeInt(max); - dest.writeInt(indeterminate ? 1 : 0); - } - - @Override - public void apply(View root) { - ProgressBar target = (ProgressBar) root.findViewById(viewId); - if (target != null) { - target.setIndeterminate(indeterminate); - if (!indeterminate) { - target.setMax(max); - target.setProgress(progress); - } + Class param = getParameterType(); + if (param == null) { + throw new ActionException("bad type: " + this.type); } - } - - int viewId; - boolean indeterminate; - int progress; - int max; - public final static int TAG = 6; - } - - /** - * Equivalent to calling - * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)} - * to launch the provided {@link PendingIntent}. - */ - private class SetOnClickPendingIntent extends Action { - public SetOnClickPendingIntent(int id, PendingIntent pendingIntent) { - this.viewId = id; - this.pendingIntent = pendingIntent; - } - - public SetOnClickPendingIntent(Parcel parcel) { - viewId = parcel.readInt(); - pendingIntent = PendingIntent.readPendingIntentOrNullFromParcel(parcel); - } - - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(TAG); - dest.writeInt(viewId); - pendingIntent.writeToParcel(dest, 0 /* no flags */); - } - - @Override - public void apply(View root) { - final View target = root.findViewById(viewId); - if (target != null && pendingIntent != null) { - OnClickListener listener = new OnClickListener() { - public void onClick(View v) { - try { - // TODO: Unregister this handler if PendingIntent.FLAG_ONE_SHOT? - pendingIntent.send(); - } catch (CanceledException e) { - throw new ActionException(e.toString()); - } - } - }; - target.setOnClickListener(listener); + Class klass = view.getClass(); + Method method = null; + try { + method = klass.getMethod(this.methodName, getParameterType()); + } + catch (NoSuchMethodException ex) { + throw new ActionException("view: " + klass.getName() + " doesn't have method: " + + this.methodName + "(" + param.getName() + ")"); + } + + if (!method.isAnnotationPresent(RemotableViewMethod.class)) { + throw new ActionException("view: " + klass.getName() + + " can't use method with RemoteViews: " + + this.methodName + "(" + param.getName() + ")"); } - } - - int viewId; - PendingIntent pendingIntent; - public final static int TAG = 7; + try { + if (false) { + Log.d("RemoteViews", "view: " + klass.getName() + " calling method: " + + this.methodName + "(" + param.getName() + ") with " + + (this.value == null ? "null" : this.value.getClass().getName())); + } + method.invoke(view, this.value); + } + catch (Exception ex) { + throw new ActionException(ex); + } + } } + /** * Create a new RemoteViews object that will display the views contained * in the specified layout file. @@ -447,32 +486,17 @@ public class RemoteViews implements Parcelable, Filter { for (int i=0; i + * You can omit specific calls by marking their values with null or -1. + * + * @param viewId The id of the view that contains the target + * {@link Drawable} + * @param targetBackground If true, apply these parameters to the + * {@link Drawable} returned by + * {@link android.view.View#getBackground()}. Otherwise, assume + * the target view is an {@link ImageView} and apply them to + * {@link ImageView#getDrawable()}. + * @param alpha Specify an alpha value for the drawable, or -1 to leave + * unchanged. + * @param colorFilter Specify a color for a + * {@link android.graphics.ColorFilter} for this drawable, or -1 + * to leave unchanged. + * @param mode Specify a PorterDuff mode for this drawable, or null to leave + * unchanged. + * @param level Specify the level for the drawable, or -1 to leave + * unchanged. + */ + public void setDrawableParameters(int viewId, boolean targetBackground, int alpha, + int colorFilter, PorterDuff.Mode mode, int level) { + addAction(new SetDrawableParameters(viewId, targetBackground, alpha, + colorFilter, mode, level)); + } + + /** + * Equivalent to calling {@link android.widget.TextView#setTextColor(int)}. + * + * @param viewId The id of the view whose text should change + * @param color Sets the text color for all the states (normal, selected, + * focused) to be this color. + */ + public void setTextColor(int viewId, int color) { + setInt(viewId, "setTextColor", color); + } + + public void setBoolean(int viewId, String methodName, boolean value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.BOOLEAN, value)); + } + + public void setByte(int viewId, String methodName, byte value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.BYTE, value)); + } + + public void setShort(int viewId, String methodName, short value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.SHORT, value)); + } + + public void setInt(int viewId, String methodName, int value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.INT, value)); + } + + public void setLong(int viewId, String methodName, long value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.LONG, value)); + } + + public void setFloat(int viewId, String methodName, float value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.FLOAT, value)); + } + + public void setDouble(int viewId, String methodName, double value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.DOUBLE, value)); + } + + public void setChar(int viewId, String methodName, char value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR, value)); + } + + public void setString(int viewId, String methodName, String value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.STRING, value)); + } + + public void setCharSequence(int viewId, String methodName, CharSequence value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR_SEQUENCE, value)); + } + + public void setUri(int viewId, String methodName, Uri value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.URI, value)); + } + + public void setBitmap(int viewId, String methodName, Bitmap value) { + addAction(new ReflectionAction(viewId, methodName, ReflectionAction.BITMAP, value)); + } + /** * Inflates the view hierarchy represented by this object and applies * all of the actions. diff --git a/core/java/android/widget/ResourceCursorAdapter.java b/core/java/android/widget/ResourceCursorAdapter.java index 9052ae3b44968ad014269d157db723d47d538dfe..a5dbd9883469c301a0f298b8dc988e64031da8fa 100644 --- a/core/java/android/widget/ResourceCursorAdapter.java +++ b/core/java/android/widget/ResourceCursorAdapter.java @@ -46,9 +46,29 @@ public abstract class ResourceCursorAdapter extends CursorAdapter { public ResourceCursorAdapter(Context context, int layout, Cursor c) { super(context, c); mLayout = mDropDownLayout = layout; - mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } + /** + * Constructor. + * + * @param context The context where the ListView associated with this + * SimpleListItemFactory is running + * @param layout resource identifier of a layout file that defines the views + * for this list item. Unless you override them later, this will + * define both the item views and the drop down views. + * @param c The cursor from which to get the data. + * @param autoRequery If true the adapter will call requery() on the + * cursor whenever it changes so the most recent + * data is always displayed. + * @hide Pending API Council approval + */ + public ResourceCursorAdapter(Context context, int layout, Cursor c, boolean autoRequery) { + super(context, c, autoRequery); + mLayout = mDropDownLayout = layout; + mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } + /** * Inflates view(s) from the specified XML file. * diff --git a/core/java/android/widget/ScrollBarDrawable.java b/core/java/android/widget/ScrollBarDrawable.java index 17f912822e46a99b1d038e1d60c476f33f3db30e..3b113ae332dd9fc3c8225bedb7c3d4edf1fad22e 100644 --- a/core/java/android/widget/ScrollBarDrawable.java +++ b/core/java/android/widget/ScrollBarDrawable.java @@ -152,10 +152,12 @@ public class ScrollBarDrawable extends Drawable { } else { track = mHorizontalTrack; } - if (mChanged) { - track.setBounds(bounds); + if (track != null) { + if (mChanged) { + track.setBounds(bounds); + } + track.draw(canvas); } - track.draw(canvas); } protected void drawThumb(Canvas canvas, Rect bounds, int offset, int length, boolean vertical) { diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java index 20166cf72af694241f4960910ebf8c6837a709f7..c9b3751764eb2f9407c5cbceda5398973734c278 100644 --- a/core/java/android/widget/ScrollView.java +++ b/core/java/android/widget/ScrollView.java @@ -44,13 +44,7 @@ import java.util.List; * manager with a complex hierarchy of objects. A child that is often used * is a {@link LinearLayout} in a vertical orientation, presenting a vertical * array of top-level items that the user can scroll through. - * - *

          You should never use a ScrollView with a {@link ListView}, since - * ListView takes care of its own scrolling. Most importantly, doing this - * defeats all of the important optimizations in ListView for dealing with - * large lists, since it effectively forces the ListView to display its entire - * list of items to fill up the infinite container supplied by ScrollView. - * + * *

          The {@link TextView} class also * takes care of its own scrolling, so does not require a ScrollView, but * using the two together is possible to achieve the effect of a text view @@ -62,13 +56,9 @@ public class ScrollView extends FrameLayout { static final String TAG = "ScrollView"; static final boolean localLOGV = false || Config.LOGV; - private static final int ANIMATED_SCROLL_GAP = 250; + static final int ANIMATED_SCROLL_GAP = 250; - /** - * When arrow scrolling, ListView will never scroll more than this factor - * times the height of the list. - */ - private static final float MAX_SCROLL_FACTOR = 0.5f; + static final float MAX_SCROLL_FACTOR = 0.5f; private long mLastScroll; @@ -124,6 +114,8 @@ public class ScrollView extends FrameLayout { */ private boolean mSmoothScrollingEnabled = true; + private int mTouchSlop; + public ScrollView(Context context) { this(context, null); } @@ -165,8 +157,8 @@ public class ScrollView extends FrameLayout { } final int length = getVerticalFadingEdgeLength(); - final int bottom = getChildAt(0).getBottom(); - final int span = bottom - mScrollY - getHeight(); + final int bottomEdge = getHeight() - mPaddingBottom; + final int span = getChildAt(0).getBottom() - mScrollY - bottomEdge; if (span < length) { return span / (float) length; } @@ -188,6 +180,7 @@ public class ScrollView extends FrameLayout { setFocusable(true); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setWillNotDraw(false); + mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); } @Override @@ -401,7 +394,7 @@ public class ScrollView extends FrameLayout { * of the down event. */ final int yDiff = (int) Math.abs(y - mLastMotionY); - if (yDiff > ViewConfiguration.getTouchSlop()) { + if (yDiff > mTouchSlop) { mIsBeingDragged = true; } break; @@ -488,8 +481,9 @@ public class ScrollView extends FrameLayout { velocityTracker.computeCurrentVelocity(1000); int initialVelocity = (int) velocityTracker.getYVelocity(); - if ((Math.abs(initialVelocity) > ViewConfiguration.getMinimumFlingVelocity()) && - (getChildCount() > 0)) { + if ((Math.abs(initialVelocity) > + ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) && + getChildCount() > 0) { fling(-initialVelocity); } @@ -812,7 +806,7 @@ public class ScrollView extends FrameLayout { /** * Smooth scroll by a Y delta * - * @param delta the number of pixels to scroll by on the X axis + * @param delta the number of pixels to scroll by on the Y axis */ private void doScrollY(int delta) { if (delta != 0) { @@ -923,8 +917,8 @@ public class ScrollView extends FrameLayout { int y = mScroller.getCurrY(); if (getChildCount() > 0) { View child = getChildAt(0); - mScrollX = clamp(x, this.getWidth(), child.getWidth()); - mScrollY = clamp(y, this.getHeight(), child.getHeight()); + mScrollX = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); + mScrollY = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); if (localLOGV) Log.v(TAG, "mScrollY=" + mScrollY + " y=" + y + " height=" + this.getHeight() + " child height=" + child.getHeight()); @@ -1167,8 +1161,8 @@ public class ScrollView extends FrameLayout { * which means we want to scroll towards the top. */ public void fling(int velocityY) { - int height = getHeight(); - int bottom = getChildAt(getChildCount() - 1).getBottom(); + int height = getHeight() - mPaddingBottom - mPaddingTop; + int bottom = getChildAt(0).getHeight(); mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0, bottom - height); @@ -1198,8 +1192,8 @@ public class ScrollView extends FrameLayout { // we rely on the fact the View.scrollBy calls scrollTo. if (getChildCount() > 0) { View child = getChildAt(0); - x = clamp(x, this.getWidth(), child.getWidth()); - y = clamp(y, this.getHeight(), child.getHeight()); + x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); + y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); if (x != mScrollX || y != mScrollY) { super.scrollTo(x, y); } diff --git a/core/java/android/widget/Scroller.java b/core/java/android/widget/Scroller.java index fbe5e576a52c20b258d205a1becd0c7e99874d17..febc95643a050ba92c81df020e2771a82bdca85d 100644 --- a/core/java/android/widget/Scroller.java +++ b/core/java/android/widget/Scroller.java @@ -131,6 +131,26 @@ public class Scroller { return mCurrY; } + /** + * Returns the start X offset in the scroll. + * + * @return The start X offset as an absolute distance from the origin. + * @hide pending API council + */ + public final int getStartX() { + return mStartX; + } + + /** + * Returns the start Y offset in the scroll. + * + * @return The start Y offset as an absolute distance from the origin. + * @hide pending API council + */ + public final int getStartY() { + return mStartY; + } + /** * Returns where the scroll will end. Valid only for "fling" scrolls. * diff --git a/core/java/android/widget/SimpleAdapter.java b/core/java/android/widget/SimpleAdapter.java index 261da9ff46a8a4ce97e8746dec9c01ffadc4d6e5..093c24e0ca58e84d4af59a283ee37a4d8d3c7e87 100644 --- a/core/java/android/widget/SimpleAdapter.java +++ b/core/java/android/widget/SimpleAdapter.java @@ -36,12 +36,16 @@ import java.util.Map; * Binding data to views occurs in two phases. First, if a * {@link android.widget.SimpleAdapter.ViewBinder} is available, * {@link ViewBinder#setViewValue(android.view.View, Object, String)} - * is invoked. If the returned value is true, binding has occured. If the - * returned value is false and the view to bind is a TextView, - * {@link #setViewText(TextView, String)} is invoked. If the returned value - * is false and the view to bind is an ImageView, - * {@link #setViewImage(ImageView, int)} or {@link #setViewImage(ImageView, String)} is - * invoked. If no appropriate binding can be found, an {@link IllegalStateException} is thrown. + * is invoked. If the returned value is true, binding has occurred. + * If the returned value is false, the following views are then tried in order: + *

            + *
          • A view that implements Checkable (e.g. CheckBox). The expected bind value is a boolean. + *
          • TextView. The expected bind value is a string and {@link #setViewText(TextView, String)} + * is invoked. + *
          • ImageView. The expected bind value is a resource id or a string and + * {@link #setViewImage(ImageView, int)} or {@link #setViewImage(ImageView, String)} is invoked. + *
          + * If no appropriate binding can be found, an {@link IllegalStateException} is thrown. */ public class SimpleAdapter extends BaseAdapter implements Filterable { private int[] mTo; @@ -176,7 +180,16 @@ public class SimpleAdapter extends BaseAdapter implements Filterable { } if (!bound) { - if (v instanceof TextView) { + if (v instanceof Checkable) { + if (data instanceof Boolean) { + ((Checkable) v).setChecked((Boolean) data); + } else { + throw new IllegalStateException(v.getClass().getName() + + " should be bound to a Boolean, not a " + data.getClass()); + } + } else if (v instanceof TextView) { + // Note: keep the instanceof TextView check at the bottom of these + // ifs since a lot of views are TextViews (e.g. CheckBoxes). setViewText((TextView) v, text); } else if (v instanceof ImageView) { if (data instanceof Integer) { diff --git a/core/java/com/android/internal/widget/SlidingDrawer.java b/core/java/android/widget/SlidingDrawer.java similarity index 91% rename from core/java/com/android/internal/widget/SlidingDrawer.java rename to core/java/android/widget/SlidingDrawer.java index a4045d553a024472c3a17e0dc3e7c8a0cdb2b054..e0f1bb41ce892534c1c045c5c5c8107483faf71d 100644 --- a/core/java/com/android/internal/widget/SlidingDrawer.java +++ b/core/java/android/widget/SlidingDrawer.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.internal.widget; +package android.widget; import android.view.ViewGroup; import android.view.View; @@ -30,7 +30,7 @@ import android.graphics.Bitmap; import android.os.SystemClock; import android.os.Handler; import android.os.Message; -import com.android.internal.R; +import android.R; /** * SlidingDrawer hides content out of the screen and allows the user to drag a handle @@ -48,7 +48,7 @@ import com.android.internal.R; * content: * *
          - * <com.android.internal.widget.SlidingDrawer
          + * <SlidingDrawer
            *     android:id="@+id/drawer"
            *     android:layout_width="fill_parent"
            *     android:layout_height="fill_parent"
          @@ -66,16 +66,16 @@ import com.android.internal.R;
            *         android:layout_width="fill_parent"
            *         android:layout_height="fill_parent" />
            *
          - * </com.android.internal.widget.SlidingDrawer>
          + * </SlidingDrawer>
            * 
          * - * @attr ref com.android.internal.R.styleable#SlidingDrawer_content - * @attr ref com.android.internal.R.styleable#SlidingDrawer_handle - * @attr ref com.android.internal.R.styleable#SlidingDrawer_topOffset - * @attr ref com.android.internal.R.styleable#SlidingDrawer_bottomOffset - * @attr ref com.android.internal.R.styleable#SlidingDrawer_orientation - * @attr ref com.android.internal.R.styleable#SlidingDrawer_allowSingleTap - * @attr ref com.android.internal.R.styleable#SlidingDrawer_animateOnClick + * @attr ref android.R.styleable#SlidingDrawer_content + * @attr ref android.R.styleable#SlidingDrawer_handle + * @attr ref android.R.styleable#SlidingDrawer_topOffset + * @attr ref android.R.styleable#SlidingDrawer_bottomOffset + * @attr ref android.R.styleable#SlidingDrawer_orientation + * @attr ref android.R.styleable#SlidingDrawer_allowSingleTap + * @attr ref android.R.styleable#SlidingDrawer_animateOnClick */ public class SlidingDrawer extends ViewGroup { public static final int ORIENTATION_HORIZONTAL = 0; @@ -128,6 +128,13 @@ public class SlidingDrawer extends ViewGroup { private boolean mAllowSingleTap; private boolean mAnimateOnClick; + private final int mTapThreshold; + private final int mMaximumTapVelocity; + private final int mMaximumMinorVelocity; + private final int mMaximumMajorVelocity; + private final int mMaximumAcceleration; + private final int mVelocityUnits; + /** * Callback invoked when the drawer is opened. */ @@ -206,6 +213,14 @@ public class SlidingDrawer extends ViewGroup { mHandleId = handleId; mContentId = contentId; + final float density = getResources().getDisplayMetrics().density; + mTapThreshold = (int) (TAP_THRESHOLD * density + 0.5f); + mMaximumTapVelocity = (int) (MAXIMUM_TAP_VELOCITY * density + 0.5f); + mMaximumMinorVelocity = (int) (MAXIMUM_MINOR_VELOCITY * density + 0.5f); + mMaximumMajorVelocity = (int) (MAXIMUM_MAJOR_VELOCITY * density + 0.5f); + mMaximumAcceleration = (int) (MAXIMUM_ACCELERATION * density + 0.5f); + mVelocityUnits = (int) (VELOCITY_UNITS * density + 0.5f); + a.recycle(); setAlwaysDrawnWithCacheEnabled(false); @@ -343,15 +358,17 @@ public class SlidingDrawer extends ViewGroup { } if (action == MotionEvent.ACTION_DOWN) { - if (mOnDrawerScrollListener != null) { - mOnDrawerScrollListener.onScrollStarted(); - } mTracking = true; handle.setPressed(true); // Must be called before prepareTracking() prepareContent(); + // Must be called after prepareContent() + if (mOnDrawerScrollListener != null) { + mOnDrawerScrollListener.onScrollStarted(); + } + if (mVertical) { final int top = mHandle.getTop(); mTouchDelta = (int) y - top; @@ -383,7 +400,7 @@ public class SlidingDrawer extends ViewGroup { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { final VelocityTracker velocityTracker = mVelocityTracker; - velocityTracker.computeCurrentVelocity(VELOCITY_UNITS); + velocityTracker.computeCurrentVelocity(mVelocityUnits); float yVelocity = velocityTracker.getYVelocity(); float xVelocity = velocityTracker.getXVelocity(); @@ -395,16 +412,16 @@ public class SlidingDrawer extends ViewGroup { if (xVelocity < 0) { xVelocity = -xVelocity; } - if (xVelocity > MAXIMUM_MINOR_VELOCITY) { - xVelocity = MAXIMUM_MINOR_VELOCITY; + if (xVelocity > mMaximumMinorVelocity) { + xVelocity = mMaximumMinorVelocity; } } else { negative = xVelocity < 0; if (yVelocity < 0) { yVelocity = -yVelocity; } - if (yVelocity > MAXIMUM_MINOR_VELOCITY) { - yVelocity = MAXIMUM_MINOR_VELOCITY; + if (yVelocity > mMaximumMinorVelocity) { + yVelocity = mMaximumMinorVelocity; } } @@ -416,13 +433,13 @@ public class SlidingDrawer extends ViewGroup { final int top = mHandle.getTop(); final int left = mHandle.getLeft(); - if (Math.abs(velocity) < MAXIMUM_TAP_VELOCITY) { - if (vertical ? (mExpanded && top < TAP_THRESHOLD + mTopOffset) || + if (Math.abs(velocity) < mMaximumTapVelocity) { + if (vertical ? (mExpanded && top < mTapThreshold + mTopOffset) || (!mExpanded && top > mBottomOffset + mBottom - mTop - - mHandleHeight - TAP_THRESHOLD) : - (mExpanded && left < TAP_THRESHOLD + mTopOffset) || + mHandleHeight - mTapThreshold) : + (mExpanded && left < mTapThreshold + mTopOffset) || (!mExpanded && left > mBottomOffset + mRight - mLeft - - mHandleWidth - TAP_THRESHOLD)) { + mHandleWidth - mTapThreshold)) { if (mAllowSingleTap) { playSoundEffect(SoundEffectConstants.CLICK); @@ -432,6 +449,8 @@ public class SlidingDrawer extends ViewGroup { } else { animateOpen(vertical ? top : left); } + } else { + performFling(vertical ? top : left, velocity, false); } } else { @@ -450,12 +469,12 @@ public class SlidingDrawer extends ViewGroup { private void animateClose(int position) { prepareTracking(position); - performFling(position, 2000.0f, true); + performFling(position, mMaximumAcceleration, true); } private void animateOpen(int position) { prepareTracking(position); - performFling(position, -2000.0f, true); + performFling(position, -mMaximumAcceleration, true); } private void performFling(int position, float velocity, boolean always) { @@ -463,35 +482,35 @@ public class SlidingDrawer extends ViewGroup { mAnimatedVelocity = velocity; if (mExpanded) { - if (always || (velocity > MAXIMUM_MAJOR_VELOCITY || + if (always || (velocity > mMaximumMajorVelocity || (position > mTopOffset + (mVertical ? mHandleHeight : mHandleWidth) && - velocity > -MAXIMUM_MAJOR_VELOCITY))) { + velocity > -mMaximumMajorVelocity))) { // We are expanded, but they didn't move sufficiently to cause // us to retract. Animate back to the expanded position. - mAnimatedAcceleration = MAXIMUM_ACCELERATION; + mAnimatedAcceleration = mMaximumAcceleration; if (velocity < 0) { mAnimatedVelocity = 0; } } else { // We are expanded and are now going to animate away. - mAnimatedAcceleration = -MAXIMUM_ACCELERATION; + mAnimatedAcceleration = -mMaximumAcceleration; if (velocity > 0) { mAnimatedVelocity = 0; } } } else { - if (!always && (velocity > MAXIMUM_MAJOR_VELOCITY || + if (!always && (velocity > mMaximumMajorVelocity || (position > (mVertical ? getHeight() : getWidth()) / 2 && - velocity > -MAXIMUM_MAJOR_VELOCITY))) { + velocity > -mMaximumMajorVelocity))) { // We are collapsed, and they moved enough to allow us to expand. - mAnimatedAcceleration = MAXIMUM_ACCELERATION; + mAnimatedAcceleration = mMaximumAcceleration; if (velocity < 0) { mAnimatedVelocity = 0; } } else { // We are collapsed, but they didn't move sufficiently to cause // us to retract. Animate back to the collapsed position. - mAnimatedAcceleration = -MAXIMUM_ACCELERATION; + mAnimatedAcceleration = -mMaximumAcceleration; if (velocity > 0) { mAnimatedVelocity = 0; } @@ -512,8 +531,8 @@ public class SlidingDrawer extends ViewGroup { mVelocityTracker = VelocityTracker.obtain(); boolean opening = !mExpanded; if (opening) { - mAnimatedAcceleration = MAXIMUM_ACCELERATION; - mAnimatedVelocity = 200; + mAnimatedAcceleration = mMaximumAcceleration; + mAnimatedVelocity = mMaximumMajorVelocity; mAnimationPosition = mBottomOffset + (mVertical ? getHeight() - mHandleHeight : getWidth() - mHandleWidth); moveHandle((int) mAnimationPosition); @@ -747,11 +766,11 @@ public class SlidingDrawer extends ViewGroup { * @see #toggle() */ public void animateClose() { + prepareContent(); final OnDrawerScrollListener scrollListener = mOnDrawerScrollListener; if (scrollListener != null) { scrollListener.onScrollStarted(); } - prepareContent(); animateClose(mVertical ? mHandle.getTop() : mHandle.getLeft()); if (scrollListener != null) { scrollListener.onScrollEnded(); @@ -768,11 +787,11 @@ public class SlidingDrawer extends ViewGroup { * @see #toggle() */ public void animateOpen() { + prepareContent(); final OnDrawerScrollListener scrollListener = mOnDrawerScrollListener; if (scrollListener != null) { scrollListener.onScrollStarted(); } - prepareContent(); animateOpen(mVertical ? mHandle.getTop() : mHandle.getLeft()); if (scrollListener != null) { scrollListener.onScrollEnded(); @@ -782,6 +801,7 @@ public class SlidingDrawer extends ViewGroup { private void closeDrawer() { moveHandle(COLLAPSED_FULL_CLOSED); mContent.setVisibility(View.GONE); + mContent.destroyDrawingCache(); if (!mExpanded) { return; @@ -796,8 +816,6 @@ public class SlidingDrawer extends ViewGroup { private void openDrawer() { moveHandle(EXPANDED_FULL_OPEN); mContent.setVisibility(View.VISIBLE); - // TODO: Should we uncomment to preserve memory, but increase memory churn? - // mContent.destroyDrawingCache(); if (mExpanded) { return; diff --git a/core/java/android/widget/TabHost.java b/core/java/android/widget/TabHost.java index da4a077eee727bd07e59c4d86fb573f8c7a5b7e1..dc2c70de92e4b05e7afcc971796c9ed3dfe5beb6 100644 --- a/core/java/android/widget/TabHost.java +++ b/core/java/android/widget/TabHost.java @@ -405,7 +405,7 @@ mTabHost.addTab(TAB_TAG_1, "Hello, world!", "Tab 1"); * Specify a label and icon as the tab indicator. */ public TabSpec setIndicator(CharSequence label, Drawable icon) { - mIndicatorStrategy = new LabelAndIconIndicatorStategy(label, icon); + mIndicatorStrategy = new LabelAndIconIndicatorStrategy(label, icon); return this; } @@ -497,12 +497,12 @@ mTabHost.addTab(TAB_TAG_1, "Hello, world!", "Tab 1"); /** * How we create a tab indicator that has a label and an icon */ - private class LabelAndIconIndicatorStategy implements IndicatorStrategy { + private class LabelAndIconIndicatorStrategy implements IndicatorStrategy { private final CharSequence mLabel; private final Drawable mIcon; - private LabelAndIconIndicatorStategy(CharSequence label, Drawable icon) { + private LabelAndIconIndicatorStrategy(CharSequence label, Drawable icon) { mLabel = label; mIcon = icon; } diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java index aa70663ff649a81a2ba111ef3b9c5d559c5aa32c..7b62b50ce31f86b492259fd8b517efb1eef3a828 100644 --- a/core/java/android/widget/TextView.java +++ b/core/java/android/widget/TextView.java @@ -17,6 +17,7 @@ package android.widget; import android.content.Context; +import android.content.Intent; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; @@ -32,6 +33,7 @@ import android.os.Bundle; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; +import android.os.ResultReceiver; import android.os.SystemClock; import android.os.Message; import android.text.BoringLayout; @@ -41,7 +43,9 @@ import android.text.GetChars; import android.text.GraphicsOperations; import android.text.ClipboardManager; import android.text.InputFilter; +import android.text.InputType; import android.text.Layout; +import android.text.ParcelableSpan; import android.text.Selection; import android.text.SpanWatcher; import android.text.Spannable; @@ -69,7 +73,6 @@ import android.text.method.TransformationMethod; import android.text.style.ParagraphStyle; import android.text.style.URLSpan; import android.text.style.UpdateAppearance; -import android.text.style.UpdateLayout; import android.text.util.Linkify; import android.util.AttributeSet; import android.util.Log; @@ -83,9 +86,11 @@ import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewDebug; +import android.view.ViewRoot; import android.view.ViewTreeObserver; import android.view.ViewGroup.LayoutParams; import android.view.animation.AnimationUtils; +import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; @@ -168,6 +173,9 @@ import org.xmlpull.v1.XmlPullParserException; */ @RemoteView public class TextView extends View implements ViewTreeObserver.OnPreDrawListener { + static final String TAG = "TextView"; + static final boolean DEBUG_EXTRACT = false; + private static int PRIORITY = 100; private ColorStateList mTextColor; @@ -177,6 +185,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener private int mCurHintTextColor; private boolean mFreezesText; private boolean mFrozenWithFocus; + private boolean mTemporaryDetach; + + private boolean mEatTouchRelease = false; + private boolean mScrolled = false; private Editable.Factory mEditableFactory = Editable.Factory.getInstance(); private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance(); @@ -207,16 +219,24 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight; int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight; int mDrawablePadding; - }; + } private Drawables mDrawables; private CharSequence mError; private boolean mErrorWasChanged; private PopupWindow mPopup; + /** + * This flag is set if the TextView tries to display an error before it + * is attached to the window (so its position is still unknown). + * It causes the error to be shown later, when onAttachedToWindow() + * is called. + */ + private boolean mShowErrorAfterAttach; private CharWrapper mCharWrapper = null; private boolean mSelectionMoved = false; + private boolean mTouchFocusSelected = false; private Marquee mMarquee; private boolean mRestartMarquee; @@ -224,8 +244,13 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener private int mMarqueeRepeatLimit = 3; class InputContentType { - String privateContentType; + int imeOptions = EditorInfo.IME_NULL; + String privateImeOptions; + CharSequence imeActionLabel; + int imeActionId; Bundle extras; + OnEditorActionListener onEditorActionListener; + boolean enterDown; } InputContentType mInputContentType; @@ -235,7 +260,11 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener float[] mTmpOffset = new float[2]; ExtractedTextRequest mExtracting; final ExtractedText mTmpExtracted = new ExtractedText(); - boolean mBatchEditing; + int mBatchEditNesting; + boolean mCursorChanged; + boolean mSelectionModeChanged; + boolean mContentChanged; + int mChangedStart, mChangedEnd, mChangedDelta; } InputMethodState mInputMethodState; @@ -250,6 +279,26 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener p.measureText("H"); } + /** + * Interface definition for a callback to be invoked when an action is + * performed on the editor. + */ + public interface OnEditorActionListener { + /** + * Called when an action is being performed. + * + * @param v The view that was clicked. + * @param actionId Identifier of the action. This will be either the + * identifier you supplied, or {@link EditorInfo#IME_NULL + * EditorInfo.IME_NULL} if being called due to the enter key + * being pressed. + * @param event If triggered by an enter key, this is the event; + * otherwise, this is null. + * @return Return true if you have consumed the action, else false. + */ + boolean onEditorAction(TextView v, int actionId, KeyEvent event); + } + public TextView(Context context) { this(context, null); } @@ -358,7 +407,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener int shadowcolor = 0; float dx = 0, dy = 0, r = 0; boolean password = false; - int contentType = EditorInfo.TYPE_NULL; + int inputType = EditorInfo.TYPE_NULL; int n = a.getIndexCount(); for (int i = 0; i < n; i++) { @@ -592,11 +641,34 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener break; case com.android.internal.R.styleable.TextView_inputType: - contentType = a.getInt(attr, mInputType); + inputType = a.getInt(attr, mInputType); break; - case com.android.internal.R.styleable.TextView_editorPrivateContentType: - setPrivateContentType(a.getString(attr)); + case com.android.internal.R.styleable.TextView_imeOptions: + if (mInputContentType == null) { + mInputContentType = new InputContentType(); + } + mInputContentType.imeOptions = a.getInt(attr, + mInputContentType.imeOptions); + break; + + case com.android.internal.R.styleable.TextView_imeActionLabel: + if (mInputContentType == null) { + mInputContentType = new InputContentType(); + } + mInputContentType.imeActionLabel = a.getText(attr); + break; + + case com.android.internal.R.styleable.TextView_imeActionId: + if (mInputContentType == null) { + mInputContentType = new InputContentType(); + } + mInputContentType.imeActionId = a.getInt(attr, + mInputContentType.imeActionId); + break; + + case com.android.internal.R.styleable.TextView_privateImeOptions: + setPrivateImeOptions(a.getString(attr)); break; case com.android.internal.R.styleable.TextView_editorExtras: @@ -614,7 +686,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener BufferType bufferType = BufferType.EDITABLE; - if ((contentType&(EditorInfo.TYPE_MASK_CLASS + if ((inputType&(EditorInfo.TYPE_MASK_CLASS |EditorInfo.TYPE_MASK_VARIATION)) == (EditorInfo.TYPE_CLASS_TEXT |EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { @@ -638,57 +710,57 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener throw new RuntimeException(ex); } try { - mInputType = contentType != EditorInfo.TYPE_NULL - ? contentType + mInputType = inputType != EditorInfo.TYPE_NULL + ? inputType : mInput.getInputType(); } catch (IncompatibleClassChangeError e) { mInputType = EditorInfo.TYPE_CLASS_TEXT; } } else if (digits != null) { mInput = DigitsKeyListener.getInstance(digits.toString()); - mInputType = contentType; - } else if (contentType != EditorInfo.TYPE_NULL) { - setInputType(contentType, true); - singleLine = (contentType&(EditorInfo.TYPE_MASK_CLASS + mInputType = inputType; + } else if (inputType != EditorInfo.TYPE_NULL) { + setInputType(inputType, true); + singleLine = (inputType&(EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) != (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); } else if (phone) { mInput = DialerKeyListener.getInstance(); - contentType = EditorInfo.TYPE_CLASS_PHONE; + inputType = EditorInfo.TYPE_CLASS_PHONE; } else if (numeric != 0) { mInput = DigitsKeyListener.getInstance((numeric & SIGNED) != 0, (numeric & DECIMAL) != 0); - contentType = EditorInfo.TYPE_CLASS_NUMBER; + inputType = EditorInfo.TYPE_CLASS_NUMBER; if ((numeric & SIGNED) != 0) { - contentType |= EditorInfo.TYPE_NUMBER_FLAG_SIGNED; + inputType |= EditorInfo.TYPE_NUMBER_FLAG_SIGNED; } if ((numeric & DECIMAL) != 0) { - contentType |= EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; + inputType |= EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; } - mInputType = contentType; + mInputType = inputType; } else if (autotext || autocap != -1) { TextKeyListener.Capitalize cap; - contentType = EditorInfo.TYPE_CLASS_TEXT; + inputType = EditorInfo.TYPE_CLASS_TEXT; if (!singleLine) { - contentType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; + inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; } switch (autocap) { case 1: cap = TextKeyListener.Capitalize.SENTENCES; - contentType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES; + inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES; break; case 2: cap = TextKeyListener.Capitalize.WORDS; - contentType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS; + inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS; break; case 3: cap = TextKeyListener.Capitalize.CHARACTERS; - contentType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS; + inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS; break; default: @@ -697,7 +769,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } mInput = TextKeyListener.getInstance(autotext, cap); - mInputType = contentType; + mInputType = inputType; } else if (editable) { mInput = TextKeyListener.getInstance(); mInputType = EditorInfo.TYPE_CLASS_TEXT; @@ -769,6 +841,11 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener if (password) { setTransformationMethod(PasswordTransformationMethod.getInstance()); typefaceIndex = MONOSPACE; + } else if ((mInputType&(EditorInfo.TYPE_MASK_CLASS + |EditorInfo.TYPE_MASK_VARIATION)) + == (EditorInfo.TYPE_CLASS_TEXT + |EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { + typefaceIndex = MONOSPACE; } setTypefaceByIndex(typefaceIndex, styleIndex); @@ -1057,6 +1134,11 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * @attr ref android.R.styleable#TextView_singleLine */ public final void setTransformationMethod(TransformationMethod method) { + if (method == mTransformation) { + // Avoid the setText() below if the transformation is + // the same. + return; + } if (mTransformation != null) { if (mText instanceof Spannable) { ((Spannable) mText).removeSpan(mTransformation); @@ -1330,7 +1412,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener */ public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) { final Resources resources = getContext().getResources(); - setCompoundDrawables(left != 0 ? resources.getDrawable(left) : null, + setCompoundDrawablesWithIntrinsicBounds(left != 0 ? resources.getDrawable(left) : null, top != 0 ? resources.getDrawable(top) : null, right != 0 ? resources.getDrawable(right) : null, bottom != 0 ? resources.getDrawable(bottom) : null); @@ -1412,10 +1494,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener @Override public void setPadding(int left, int top, int right, int bottom) { - if (left != getPaddingLeft() || - right != getPaddingRight() || - top != getPaddingTop() || - bottom != getPaddingBottom()) { + if (left != mPaddingLeft || + right != mPaddingRight || + top != mPaddingTop || + bottom != mPaddingBottom) { nullLayouts(); } @@ -1504,6 +1586,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_textSize */ + @android.view.RemotableViewMethod public void setTextSize(float size) { setTextSize(TypedValue.COMPLEX_UNIT_SP, size); } @@ -1555,6 +1638,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_textScaleX */ + @android.view.RemotableViewMethod public void setTextScaleX(float size) { if (size != mTextPaint.getTextScaleX()) { mTextPaint.setTextScaleX(size); @@ -1603,6 +1687,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_textColor */ + @android.view.RemotableViewMethod public void setTextColor(int color) { mTextColor = ColorStateList.valueOf(color); updateTextColors(); @@ -1645,6 +1730,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_textColorHighlight */ + @android.view.RemotableViewMethod public void setHighlightColor(int color) { if (mHighlightColor != color) { mHighlightColor = color; @@ -1686,6 +1772,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_autoLink */ + @android.view.RemotableViewMethod public final void setAutoLinkMask(int mask) { mAutoLinkMask = mask; } @@ -1698,6 +1785,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_linksClickable */ + @android.view.RemotableViewMethod public final void setLinksClickable(boolean whether) { mLinksClickable = whether; } @@ -1734,6 +1822,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_textColorHint */ + @android.view.RemotableViewMethod public final void setHintTextColor(int color) { mHintTextColor = ColorStateList.valueOf(color); updateTextColors(); @@ -1772,6 +1861,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_textColorLink */ + @android.view.RemotableViewMethod public final void setLinkTextColor(int color) { mLinkTextColor = ColorStateList.valueOf(color); updateTextColors(); @@ -1859,6 +1949,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * reflows the text if they are different from the old flags. * @see Paint#setFlags */ + @android.view.RemotableViewMethod public void setPaintFlags(int flags) { if (mTextPaint.getFlags() != flags) { mTextPaint.setFlags(flags); @@ -1892,6 +1983,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_minLines */ + @android.view.RemotableViewMethod public void setMinLines(int minlines) { mMinimum = minlines; mMinMode = LINES; @@ -1905,6 +1997,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_minHeight */ + @android.view.RemotableViewMethod public void setMinHeight(int minHeight) { mMinimum = minHeight; mMinMode = PIXELS; @@ -1918,6 +2011,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_maxLines */ + @android.view.RemotableViewMethod public void setMaxLines(int maxlines) { mMaximum = maxlines; mMaxMode = LINES; @@ -1931,6 +2025,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_maxHeight */ + @android.view.RemotableViewMethod public void setMaxHeight(int maxHeight) { mMaximum = maxHeight; mMaxMode = PIXELS; @@ -1944,6 +2039,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_lines */ + @android.view.RemotableViewMethod public void setLines(int lines) { mMaximum = mMinimum = lines; mMaxMode = mMinMode = LINES; @@ -1959,6 +2055,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_height */ + @android.view.RemotableViewMethod public void setHeight(int pixels) { mMaximum = mMinimum = pixels; mMaxMode = mMinMode = PIXELS; @@ -1972,6 +2069,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_minEms */ + @android.view.RemotableViewMethod public void setMinEms(int minems) { mMinWidth = minems; mMinWidthMode = EMS; @@ -1985,6 +2083,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_minWidth */ + @android.view.RemotableViewMethod public void setMinWidth(int minpixels) { mMinWidth = minpixels; mMinWidthMode = PIXELS; @@ -1998,6 +2097,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_maxEms */ + @android.view.RemotableViewMethod public void setMaxEms(int maxems) { mMaxWidth = maxems; mMaxWidthMode = EMS; @@ -2011,6 +2111,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_maxWidth */ + @android.view.RemotableViewMethod public void setMaxWidth(int maxpixels) { mMaxWidth = maxpixels; mMaxWidthMode = PIXELS; @@ -2024,6 +2125,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_ems */ + @android.view.RemotableViewMethod public void setEms(int ems) { mMaxWidth = mMinWidth = ems; mMaxWidthMode = mMinWidthMode = EMS; @@ -2039,6 +2141,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_width */ + @android.view.RemotableViewMethod public void setWidth(int pixels) { mMaxWidth = mMinWidth = pixels; mMaxWidthMode = mMinWidthMode = PIXELS; @@ -2150,6 +2253,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener int selEnd; CharSequence text; boolean frozenWithFocus; + CharSequence error; SavedState(Parcelable superState) { super(superState); @@ -2162,6 +2266,13 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener out.writeInt(selEnd); out.writeInt(frozenWithFocus ? 1 : 0); TextUtils.writeToParcel(text, out, flags); + + if (error == null) { + out.writeInt(0); + } else { + out.writeInt(1); + TextUtils.writeToParcel(error, out, flags); + } } @Override @@ -2192,6 +2303,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener selEnd = in.readInt(); frozenWithFocus = (in.readInt() != 0); text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); + + if (in.readInt() != 0) { + error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); + } } } @@ -2244,6 +2359,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener ss.frozenWithFocus = true; } + ss.error = mError; + return ss; } @@ -2289,6 +2406,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } } } + + if (ss.error != null) { + setError(ss.error); + } } /** @@ -2304,6 +2425,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_freezesText */ + @android.view.RemotableViewMethod public void setFreezesText(boolean freezesText) { mFreezesText = freezesText; } @@ -2342,12 +2464,14 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * Sets the string value of the TextView. TextView does not accept * HTML-like formatting, which you can do with text strings in XML resource files. * To style your strings, attach android.text.style.* objects to a - * {@link android.text.SpannableString SpannableString}, or see - * - * String Resources for an example of setting formatted text in the XML resource file. + * {@link android.text.SpannableString SpannableString}, or see the + * + * Available Resource Types documentation for an example of setting + * formatted text in the XML resource file. * * @attr ref android.R.styleable#TextView_text */ + @android.view.RemotableViewMethod public final void setText(CharSequence text) { setText(text, mBufferType); } @@ -2360,6 +2484,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @see #setText(CharSequence) */ + @android.view.RemotableViewMethod public final void setTextKeepState(CharSequence text) { setTextKeepState(text, mBufferType); } @@ -2630,6 +2755,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } } + @android.view.RemotableViewMethod public final void setText(int resid) { setText(getContext().getResources().getText(resid)); } @@ -2648,6 +2774,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_hint */ + @android.view.RemotableViewMethod public final void setHint(CharSequence hint) { mHint = TextUtils.stringOrSpannedString(hint); @@ -2668,6 +2795,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_hint */ + @android.view.RemotableViewMethod public final void setHint(int resid) { setHint(getContext().getResources().getText(resid)); } @@ -2698,20 +2826,40 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener */ public void setInputType(int type) { setInputType(type, false); - if ((type&(EditorInfo.TYPE_MASK_CLASS - |EditorInfo.TYPE_MASK_VARIATION)) + final int variation = type&(EditorInfo.TYPE_MASK_CLASS + |EditorInfo.TYPE_MASK_VARIATION); + final boolean isPassword = variation == (EditorInfo.TYPE_CLASS_TEXT - |EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { + |EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); + boolean forceUpdate = false; + if (isPassword) { setTransformationMethod(PasswordTransformationMethod.getInstance()); setTypefaceByIndex(MONOSPACE, 0); + } else if (mTransformation == PasswordTransformationMethod.getInstance()) { + // We need to clean up if we were previously in password mode. + if (variation != (EditorInfo.TYPE_CLASS_TEXT + |EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD)) { + setTypefaceByIndex(-1, -1); + } + forceUpdate = true; + } else if (variation == (EditorInfo.TYPE_CLASS_TEXT + |EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD)) { + setTypefaceByIndex(MONOSPACE, 0); } + boolean multiLine = (type&(EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); - if (mSingleLine == multiLine) { - setSingleLine(!multiLine); - } + + // We need to update the single line mode if it has changed or we + // were previously in password mode. + if (mSingleLine == multiLine || forceUpdate) { + // Change single line mode, but only change the transformation if + // we are not in password mode. + applySingleLine(!multiLine, !isPassword); + } + InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) imm.restartInput(this); } @@ -2719,7 +2867,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener /** * Directly change the content type integer of the text view, without * modifying any other state. - * @see #setContentType + * @see #setInputType(int) * @see android.text.InputType * @attr ref android.R.styleable#TextView_inputType */ @@ -2782,29 +2930,176 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return mInputType; } + /** + * Change the editor type integer associated with the text view, which + * will be reported to an IME with {@link EditorInfo#imeOptions} when it + * has focus. + * @see #getImeOptions + * @see android.view.inputmethod.EditorInfo + * @attr ref android.R.styleable#TextView_imeOptions + */ + public void setImeOptions(int imeOptions) { + if (mInputContentType == null) { + mInputContentType = new InputContentType(); + } + mInputContentType.imeOptions = imeOptions; + } + + /** + * Get the type of the IME editor. + * + * @see #setImeOptions(int) + * @see android.view.inputmethod.EditorInfo + */ + public int getImeOptions() { + return mInputContentType != null + ? mInputContentType.imeOptions : EditorInfo.IME_NULL; + } + + /** + * Change the custom IME action associated with the text view, which + * will be reported to an IME with {@link EditorInfo#actionLabel} + * and {@link EditorInfo#actionId} when it has focus. + * @see #getImeActionLabel + * @see #getImeActionId + * @see android.view.inputmethod.EditorInfo + * @attr ref android.R.styleable#TextView_imeActionLabel + * @attr ref android.R.styleable#TextView_imeActionId + */ + public void setImeActionLabel(CharSequence label, int actionId) { + if (mInputContentType == null) { + mInputContentType = new InputContentType(); + } + mInputContentType.imeActionLabel = label; + mInputContentType.imeActionId = actionId; + } + + /** + * Get the IME action label previous set with {@link #setImeActionLabel}. + * + * @see #setImeActionLabel + * @see android.view.inputmethod.EditorInfo + */ + public CharSequence getImeActionLabel() { + return mInputContentType != null + ? mInputContentType.imeActionLabel : null; + } + + /** + * Get the IME action ID previous set with {@link #setImeActionLabel}. + * + * @see #setImeActionLabel + * @see android.view.inputmethod.EditorInfo + */ + public int getImeActionId() { + return mInputContentType != null + ? mInputContentType.imeActionId : 0; + } + + /** + * Set a special listener to be called when an action is performed + * on the text view. This will be called when the enter key is pressed, + * or when an action supplied to the IME is selected by the user. Setting + * this means that the normal hard key event will not insert a newline + * into the text view, even if it is multi-line; holding down the ALT + * modifier will, however, allow the user to insert a newline character. + */ + public void setOnEditorActionListener(OnEditorActionListener l) { + if (mInputContentType == null) { + mInputContentType = new InputContentType(); + } + mInputContentType.onEditorActionListener = l; + } + + /** + * Called when an attached input method calls + * {@link InputConnection#performEditorAction(int) + * InputConnection.performEditorAction()} + * for this text view. The default implementation will call your action + * listener supplied to {@link #setOnEditorActionListener}, or perform + * a standard operation for {@link EditorInfo#IME_ACTION_NEXT + * EditorInfo.IME_ACTION_NEXT} or {@link EditorInfo#IME_ACTION_DONE + * EditorInfo.IME_ACTION_DONE}. + * + *

          For backwards compatibility, if no IME options have been set and the + * text view would not normally advance focus on enter, then + * the NEXT and DONE actions received here will be turned into an enter + * key down/up pair to go through the normal key handling. + * + * @param actionCode The code of the action being performed. + * + * @see #setOnEditorActionListener + */ + public void onEditorAction(int actionCode) { + final InputContentType ict = mInputContentType; + if (ict != null) { + if (ict.onEditorActionListener != null) { + if (ict.onEditorActionListener.onEditorAction(this, + actionCode, null)) { + return; + } + } + } + if (ict != null || !shouldAdvanceFocusOnEnter()) { + // This is the handling for some default action. + // Note that for backwards compatibility we don't do this + // default handling if explicit ime options have not been given, + // to instead turn this into the normal enter key codes that an + // app may be expecting. + if (actionCode == EditorInfo.IME_ACTION_NEXT) { + View v = focusSearch(FOCUS_DOWN); + if (v != null) { + if (!v.requestFocus(FOCUS_DOWN)) { + throw new IllegalStateException("focus search returned a view " + + "that wasn't able to take focus!"); + } + } + return; + + } else if (actionCode == EditorInfo.IME_ACTION_DONE) { + InputMethodManager imm = InputMethodManager.peekInstance(); + if (imm != null) { + imm.hideSoftInputFromWindow(getWindowToken(), 0); + } + return; + } + } + + Handler h = getHandler(); + long eventTime = SystemClock.uptimeMillis(); + h.sendMessage(h.obtainMessage(ViewRoot.DISPATCH_KEY_FROM_IME, + new KeyEvent(eventTime, eventTime, + KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0, 0, 0, + KeyEvent.FLAG_SOFT_KEYBOARD|KeyEvent.FLAG_KEEP_TOUCH_MODE))); + h.sendMessage(h.obtainMessage(ViewRoot.DISPATCH_KEY_FROM_IME, + new KeyEvent(SystemClock.uptimeMillis(), eventTime, + KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, 0, 0, + KeyEvent.FLAG_SOFT_KEYBOARD|KeyEvent.FLAG_KEEP_TOUCH_MODE))); + } + /** * Set the private content type of the text, which is the - * {@link EditorInfo#privateContentType TextBoxAttribute.privateContentType} + * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions} * field that will be filled in when creating an input connection. * - * @see #getPrivateContentType() - * @see EditorInfo#privateContentType - * @attr ref android.R.styleable#TextView_editorPrivateContentType + * @see #getPrivateImeOptions() + * @see EditorInfo#privateImeOptions + * @attr ref android.R.styleable#TextView_privateImeOptions */ - public void setPrivateContentType(String type) { + public void setPrivateImeOptions(String type) { if (mInputContentType == null) mInputContentType = new InputContentType(); - mInputContentType.privateContentType = type; + mInputContentType.privateImeOptions = type; } /** * Get the private type of the content. * - * @see #setPrivateContentType(String) - * @see EditorInfo#privateContentType + * @see #setPrivateImeOptions(String) + * @see EditorInfo#privateImeOptions */ - public String getPrivateContentType() { + public String getPrivateImeOptions() { return mInputContentType != null - ? mInputContentType.privateContentType : null; + ? mInputContentType.privateImeOptions : null; } /** @@ -2814,7 +3109,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * given integer is the resource ID of an XML resource holding an * {@link android.R.styleable#InputExtras <input-extras>} XML tree. * - * @see #getInputExtras() + * @see #getInputExtras(boolean) * @see EditorInfo#extras * @attr ref android.R.styleable#TextView_editorExtras */ @@ -2832,7 +3127,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @param create If true, the extras will be created if they don't already * exist. Otherwise, null will be returned if none have been created. - * @see #setInputExtras(int) + * @see #setInputExtras(int)View * @see EditorInfo#extras * @attr ref android.R.styleable#TextView_editorExtras */ @@ -2865,6 +3160,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * error is null, the error message and icon * will be cleared. */ + @android.view.RemotableViewMethod public void setError(CharSequence error) { if (error == null) { setError(null, null); @@ -2916,13 +3212,39 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } private void showError() { + if (getWindowToken() == null) { + mShowErrorAfterAttach = true; + return; + } + if (mPopup == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); - TextView err = (TextView) inflater.inflate(com.android.internal.R.layout.textview_hint, + final TextView err = (TextView) inflater.inflate(com.android.internal.R.layout.textview_hint, null); - mPopup = new PopupWindow(err, 200, 50); + mPopup = new PopupWindow(err, 200, 50) { + private boolean mAbove = false; + + @Override + public void update(int x, int y, int w, int h, boolean force) { + super.update(x, y, w, h, force); + + boolean above = isAboveAnchor(); + if (above != mAbove) { + mAbove = above; + + if (above) { + err.setBackgroundResource(com.android.internal.R.drawable.popup_inline_error_above); + } else { + err.setBackgroundResource(com.android.internal.R.drawable.popup_inline_error); + } + } + } + }; mPopup.setFocusable(false); + // The user is entering text, so the input method is needed. We + // don't want the popup to be displayed on top of it. + mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); } TextView tv = (TextView) mPopup.getContentView(); @@ -2979,6 +3301,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener mPopup.dismiss(); } } + + mShowErrorAfterAttach = false; } private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { @@ -3268,6 +3592,18 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return !changed; } + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + + mTemporaryDetach = false; + + if (mShowErrorAfterAttach) { + showError(); + mShowErrorAfterAttach = false; + } + } + @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); @@ -3310,6 +3646,16 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return (int) Math.max(0, mShadowDx + mShadowRadius); } + @Override + protected boolean verifyDrawable(Drawable who) { + final boolean verified = super.verifyDrawable(who); + if (!verified && mDrawables != null) { + return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || + who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom; + } + return verified; + } + @Override protected void onDraw(Canvas canvas) { // Draw the background for this view @@ -3505,38 +3851,48 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } */ - InputMethodManager imm = InputMethodManager.peekInstance(); - if (highlight != null && mInputMethodState != null - && !mInputMethodState.mBatchEditing && imm != null) { - if (imm.isActive(this)) { - int candStart = -1; - int candEnd = -1; - if (mText instanceof Spannable) { - Spannable sp = (Spannable)mText; - candStart = EditableInputConnection.getComposingSpanStart(sp); - candEnd = EditableInputConnection.getComposingSpanEnd(sp); + final InputMethodState ims = mInputMethodState; + if (ims != null && ims.mBatchEditNesting == 0) { + InputMethodManager imm = InputMethodManager.peekInstance(); + if (imm != null) { + if (imm.isActive(this)) { + boolean reported = false; + if (ims.mContentChanged || ims.mSelectionModeChanged) { + // We are in extract mode and the content has changed + // in some way... just report complete new text to the + // input method. + reported = reportExtractedText(); + } + if (!reported && highlight != null) { + int candStart = -1; + int candEnd = -1; + if (mText instanceof Spannable) { + Spannable sp = (Spannable)mText; + candStart = EditableInputConnection.getComposingSpanStart(sp); + candEnd = EditableInputConnection.getComposingSpanEnd(sp); + } + imm.updateSelection(this, selStart, selEnd, candStart, candEnd); + } + } + + if (imm.isWatchingCursor(this) && highlight != null) { + highlight.computeBounds(ims.mTmpRectF, true); + ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; + + canvas.getMatrix().mapPoints(ims.mTmpOffset); + ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); + + ims.mTmpRectF.offset(0, voffsetCursor - voffsetText); + + ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), + (int)(ims.mTmpRectF.top + 0.5), + (int)(ims.mTmpRectF.right + 0.5), + (int)(ims.mTmpRectF.bottom + 0.5)); + + imm.updateCursor(this, + ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, + ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); } - imm.updateSelection(this, selStart, selEnd, candStart, candEnd); - } - - if (imm.isWatchingCursor(this)) { - final InputMethodState ims = mInputMethodState; - highlight.computeBounds(ims.mTmpRectF, true); - ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; - - canvas.getMatrix().mapPoints(ims.mTmpOffset); - ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); - - ims.mTmpRectF.offset(0, voffsetCursor - voffsetText); - - ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), - (int)(ims.mTmpRectF.top + 0.5), - (int)(ims.mTmpRectF.right + 0.5), - (int)(ims.mTmpRectF.bottom + 0.5)); - - imm.updateCursor(this, - ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, - ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); } } @@ -3634,7 +3990,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener @Override public boolean onKeyDown(int keyCode, KeyEvent event) { - int which = doKeyDown(keyCode, event); + int which = doKeyDown(keyCode, event, null); if (which == 0) { // Go through default dispatching. return super.onKeyDown(keyCode, event); @@ -3647,12 +4003,18 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { KeyEvent down = new KeyEvent(event, KeyEvent.ACTION_DOWN); - int which = doKeyDown(keyCode, down); + int which = doKeyDown(keyCode, down, event); if (which == 0) { // Go through default dispatching. return super.onKeyMultiple(keyCode, repeatCount, event); } + if (which == -1) { + // Consumed the whole thing. + return true; + } + repeatCount--; + // We are going to dispatch the remaining events to either the input // or movement method. To do this, we will just send a repeated stream // of down and up events until we have done the complete repeatCount. @@ -3680,15 +4042,67 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return true; } - private int doKeyDown(int keyCode, KeyEvent event) { + /** + * Returns true if pressing ENTER in this field advances focus instead + * of inserting the character. This is true mostly in single-line fields, + * but also in mail addresses and subjects which will display on multiple + * lines but where it doesn't make sense to insert newlines. + */ + private boolean shouldAdvanceFocusOnEnter() { + if (mInput == null) { + return false; + } + + if (mSingleLine) { + return true; + } + + if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { + int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; + + if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || + variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { + return true; + } + } + + return false; + } + + private boolean isInterestingEnter(KeyEvent event) { + if ((event.getFlags() & KeyEvent.FLAG_SOFT_KEYBOARD) != 0 && + mInputContentType != null && + (mInputContentType.imeOptions & + EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) { + // If this enter key came from a soft keyboard, and the + // text editor has been configured to not do a default + // action for software enter keys, then we aren't interested. + return false; + } + return true; + } + + private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { if (!isEnabled()) { return 0; } switch (keyCode) { - case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: - if (mSingleLine && mInput != null) { + if (!isInterestingEnter(event)) { + // Ignore enter key we aren't interested in. + return -1; + } + if ((event.getMetaState()&KeyEvent.META_ALT_ON) == 0 + && mInputContentType != null + && mInputContentType.onEditorActionListener != null) { + mInputContentType.enterDown = true; + // We are consuming the enter key for them. + return -1; + } + // fall through... + case KeyEvent.KEYCODE_DPAD_CENTER: + if (shouldAdvanceFocusOnEnter()) { return 0; } } @@ -3702,20 +4116,63 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener */ mErrorWasChanged = false; - if (mInput.onKeyDown(this, (Editable) mText, keyCode, event)) { - if (mError != null && !mErrorWasChanged) { - setError(null, null); + boolean doDown = true; + if (otherEvent != null) { + try { + beginBatchEdit(); + boolean handled = mInput.onKeyOther(this, (Editable) mText, + otherEvent); + if (mError != null && !mErrorWasChanged) { + setError(null, null); + } + doDown = false; + if (handled) { + return -1; + } + } catch (AbstractMethodError e) { + // onKeyOther was added after 1.0, so if it isn't + // implemented we need to try to dispatch as a regular down. + } finally { + endBatchEdit(); + } + } + + if (doDown) { + beginBatchEdit(); + if (mInput.onKeyDown(this, (Editable) mText, keyCode, event)) { + endBatchEdit(); + if (mError != null && !mErrorWasChanged) { + setError(null, null); + } + return 1; } - return 1; + endBatchEdit(); } } // bug 650865: sometimes we get a key event before a layout. // don't try to move around if we don't know the layout. - if (mMovement != null && mLayout != null) - if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) - return 2; + if (mMovement != null && mLayout != null) { + boolean doDown = true; + if (otherEvent != null) { + try { + boolean handled = mMovement.onKeyOther(this, (Spannable) mText, + otherEvent); + doDown = false; + if (handled) { + return -1; + } + } catch (AbstractMethodError e) { + // onKeyOther was added after 1.0, so if it isn't + // implemented we need to try to dispatch as a regular down. + } + } + if (doDown) { + if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) + return 2; + } + } return 0; } @@ -3728,8 +4185,37 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: + /* + * If there is a click listener, just call through to + * super, which will invoke it. + * + * If there isn't a click listener, try to show the soft + * input method. (It will also + * call performClick(), but that won't do anything in + * this case.) + */ + if (mOnClickListener == null) { + if (mMovement != null && mText instanceof Editable + && mLayout != null && onCheckIsTextEditor()) { + InputMethodManager imm = (InputMethodManager) + getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(this, 0); + } + } + return super.onKeyUp(keyCode, event); + case KeyEvent.KEYCODE_ENTER: - if (mSingleLine && mInput != null) { + if (mInputContentType != null + && mInputContentType.onEditorActionListener != null + && mInputContentType.enterDown) { + mInputContentType.enterDown = false; + if (mInputContentType.onEditorActionListener.onEditorAction( + this, EditorInfo.IME_NULL, event)) { + return true; + } + } + + if (shouldAdvanceFocusOnEnter()) { /* * If there is a click listener, just call through to * super, which will invoke it. @@ -3756,6 +4242,14 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener */ super.onKeyUp(keyCode, event); return true; + } else if ((event.getFlags() + & KeyEvent.FLAG_SOFT_KEYBOARD) != 0) { + // No target for next focus, but make sure the IME + // if this came from it. + InputMethodManager imm = InputMethodManager.peekInstance(); + if (imm != null) { + imm.hideSoftInputFromWindow(getWindowToken(), 0); + } } } @@ -3784,11 +4278,31 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener mInputMethodState = new InputMethodState(); } outAttrs.inputType = mInputType; - outAttrs.hintText = mHint; if (mInputContentType != null) { - outAttrs.privateContentType = mInputContentType.privateContentType; + outAttrs.imeOptions = mInputContentType.imeOptions; + outAttrs.privateImeOptions = mInputContentType.privateImeOptions; + outAttrs.actionLabel = mInputContentType.imeActionLabel; + outAttrs.actionId = mInputContentType.imeActionId; outAttrs.extras = mInputContentType.extras; + } else { + outAttrs.imeOptions = EditorInfo.IME_NULL; + } + if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION) + == EditorInfo.IME_ACTION_UNSPECIFIED) { + if (focusSearch(FOCUS_DOWN) != null) { + // An action has not been set, but the enter key will move to + // the next focus, so set the action to that. + outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; + } else { + // An action has not been set, and there is no focus to move + // to, so let's just supply a "done" action. + outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; + } + if (!shouldAdvanceFocusOnEnter()) { + outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; + } } + outAttrs.hintText = mHint; if (mText instanceof Editable) { InputConnection ic = new EditableInputConnection(this); outAttrs.initialSelStart = Selection.getSelectionStart(mText); @@ -3803,14 +4317,69 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener /** * If this TextView contains editable content, extract a portion of it * based on the information in request in to outText. - * @return Returns true if the text is editable and was successfully - * extracted, else false. + * @return Returns true if the text was successfully extracted, else false. */ public boolean extractText(ExtractedTextRequest request, ExtractedText outText) { - Editable content = getEditableText(); + return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, + EXTRACT_UNKNOWN, outText); + } + + static final int EXTRACT_NOTHING = -2; + static final int EXTRACT_UNKNOWN = -1; + + boolean extractTextInternal(ExtractedTextRequest request, + int partialStartOffset, int partialEndOffset, int delta, + ExtractedText outText) { + final CharSequence content = mText; if (content != null) { - outText.text = content.subSequence(0, content.length()); + if (partialStartOffset != EXTRACT_NOTHING) { + final int N = content.length(); + if (partialStartOffset < 0) { + outText.partialStartOffset = outText.partialEndOffset = -1; + partialStartOffset = 0; + partialEndOffset = N; + } else { + // Adjust offsets to ensure we contain full spans. + if (content instanceof Spanned) { + Spanned spanned = (Spanned)content; + Object[] spans = spanned.getSpans(partialStartOffset, + partialEndOffset, ParcelableSpan.class); + int i = spans.length; + while (i > 0) { + i--; + int j = spanned.getSpanStart(spans[i]); + if (j < partialStartOffset) partialStartOffset = j; + j = spanned.getSpanEnd(spans[i]); + if (j > partialEndOffset) partialEndOffset = j; + } + } + outText.partialStartOffset = partialStartOffset; + outText.partialEndOffset = partialEndOffset; + // Now use the delta to determine the actual amount of text + // we need. + partialEndOffset += delta; + if (partialEndOffset > N) { + partialEndOffset = N; + } else if (partialEndOffset < 0) { + partialEndOffset = 0; + } + } + if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { + outText.text = content.subSequence(partialStartOffset, + partialEndOffset); + } else { + outText.text = TextUtils.substring(content, partialStartOffset, + partialEndOffset); + } + } + outText.flags = 0; + if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) { + outText.flags |= ExtractedText.FLAG_SELECTING; + } + if (mSingleLine) { + outText.flags |= ExtractedText.FLAG_SINGLE_LINE; + } outText.startOffset = 0; outText.selectionStart = Selection.getSelectionStart(content); outText.selectionEnd = Selection.getSelectionEnd(content); @@ -3819,19 +4388,50 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return false; } - void reportExtractedText() { - if (mInputMethodState != null) { + boolean reportExtractedText() { + final InputMethodState ims = mInputMethodState; + final boolean contentChanged = ims.mContentChanged; + if (ims != null && (contentChanged || ims.mSelectionModeChanged)) { + ims.mContentChanged = false; + ims.mSelectionModeChanged = false; final ExtractedTextRequest req = mInputMethodState.mExtracting; if (req != null) { InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) { - if (extractText(req, mInputMethodState.mTmpExtracted)) { + if (DEBUG_EXTRACT) Log.v(TAG, "Retrieving extracted start=" + + ims.mChangedStart + " end=" + ims.mChangedEnd + + " delta=" + ims.mChangedDelta); + if (ims.mChangedStart < 0 && !contentChanged) { + ims.mChangedStart = EXTRACT_NOTHING; + } + if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, + ims.mChangedDelta, ims.mTmpExtracted)) { + if (DEBUG_EXTRACT) Log.v(TAG, "Reporting extracted start=" + + ims.mTmpExtracted.partialStartOffset + + " end=" + ims.mTmpExtracted.partialEndOffset + + ": " + ims.mTmpExtracted.text); imm.updateExtractedText(this, req.token, mInputMethodState.mTmpExtracted); + return true; } } } } + return false; + } + + /** + * This is used to remove all style-impacting spans from text before new + * extracted text is being replaced into it, so that we don't have any + * lingering spans applied during the replace. + */ + static void removeParcelableSpans(Spannable spannable, int start, int end) { + Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); + int i = spans.length; + while (i > 0) { + i--; + spannable.removeSpan(spans[i]); + } } /** @@ -3839,9 +4439,44 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. */ public void setExtractedText(ExtractedText text) { - setText(text.text, TextView.BufferType.EDITABLE); - Selection.setSelection((Spannable)getText(), - text.selectionStart, text.selectionEnd); + Editable content = getEditableText(); + if (text.text != null) { + if (content == null) { + setText(text.text, TextView.BufferType.EDITABLE); + } else if (text.partialStartOffset < 0) { + removeParcelableSpans(content, 0, content.length()); + content.replace(0, content.length(), text.text); + } else { + final int N = content.length(); + int start = text.partialStartOffset; + if (start > N) start = N; + int end = text.partialEndOffset; + if (end > N) end = N; + removeParcelableSpans(content, start, end); + content.replace(start, end, text.text); + } + } + + // Now set the selection position... make sure it is in range, to + // avoid crashes. If this is a partial update, it is possible that + // the underlying text may have changed, causing us problems here. + // Also we just don't want to trust clients to do the right thing. + Spannable sp = (Spannable)getText(); + final int N = sp.length(); + int start = text.selectionStart; + if (start < 0) start = 0; + else if (start > N) start = N; + int end = text.selectionEnd; + if (end < 0) end = 0; + else if (end > N) end = N; + Selection.setSelection(sp, start, end); + + // Finally, update the selection mode. + if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) { + MetaKeyKeyListener.startSelecting(this, sp); + } else { + MetaKeyKeyListener.stopSelecting(this, sp); + } } /** @@ -3866,36 +4501,91 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener public void onCommitCompletion(CompletionInfo text) { } + public void beginBatchEdit() { + final InputMethodState ims = mInputMethodState; + if (ims != null) { + int nesting = ++ims.mBatchEditNesting; + if (nesting == 1) { + ims.mCursorChanged = false; + ims.mChangedDelta = 0; + if (ims.mContentChanged) { + // We already have a pending change from somewhere else, + // so turn this into a full update. + ims.mChangedStart = 0; + ims.mChangedEnd = mText.length(); + } else { + ims.mChangedStart = EXTRACT_UNKNOWN; + ims.mChangedEnd = EXTRACT_UNKNOWN; + ims.mContentChanged = false; + } + onBeginBatchEdit(); + } + } + } + + public void endBatchEdit() { + final InputMethodState ims = mInputMethodState; + if (ims != null) { + int nesting = --ims.mBatchEditNesting; + if (nesting == 0) { + finishBatchEdit(ims); + } + } + } + + void ensureEndedBatchEdit() { + final InputMethodState ims = mInputMethodState; + if (ims != null && ims.mBatchEditNesting != 0) { + ims.mBatchEditNesting = 0; + finishBatchEdit(ims); + } + } + + void finishBatchEdit(final InputMethodState ims) { + onEndBatchEdit(); + + if (ims.mContentChanged || ims.mSelectionModeChanged) { + updateAfterEdit(); + reportExtractedText(); + } else if (ims.mCursorChanged) { + // Cheezy way to get us to report the current cursor location. + invalidateCursor(); + } + } + + void updateAfterEdit() { + invalidate(); + int curs = Selection.getSelectionStart(mText); + + if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == + Gravity.BOTTOM) { + registerForPreDraw(); + } + + if (curs >= 0) { + mHighlightPathBogus = true; + + if (isFocused()) { + mShowCursor = SystemClock.uptimeMillis(); + makeBlink(); + } + } + + checkForResize(); + } + /** * Called by the framework in response to a request to begin a batch - * of edit operations from the current input method, as a result of - * it calling {@link InputConnection#beginBatchEdit - * InputConnection.beginBatchEdit()}. The default implementation sets - * up the TextView's internal state to take care of this; if overriding - * you should call through to the super class. + * of edit operations through a call to link {@link #beginBatchEdit()}. */ public void onBeginBatchEdit() { - if (mInputMethodState != null) { - // XXX we should be smarter here, such as not doing invalidates - // until all edits are done. - mInputMethodState.mBatchEditing = true; - } } /** * Called by the framework in response to a request to end a batch - * of edit operations from the current input method, as a result of - * it calling {@link InputConnection#endBatchEdit - * InputConnection.endBatchEdit()}. The default implementation sets - * up the TextView's internal state to take care of this; if overriding - * you should call through to the super class. + * of edit operations through a call to link {@link #endBatchEdit}. */ public void onEndBatchEdit() { - if (mInputMethodState != null) { - mInputMethodState.mBatchEditing = false; - // Cheezy way to get us to report the current cursor location. - invalidateCursor(); - } } /** @@ -4542,9 +5232,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } /** - * Returns true if anything changed. + * Move the point, specified by the offset, into the view if it is needed. + * This has to be called after layout. Returns true if anything changed. */ - private boolean bringPointIntoView(int offset) { + public boolean bringPointIntoView(int offset) { boolean changed = false; int line = mLayout.getLineForOffset(offset); @@ -4793,8 +5484,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_singleLine */ + @android.view.RemotableViewMethod public void setSingleLine(boolean singleLine) { - mSingleLine = singleLine; if ((mInputType&EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { if (singleLine) { @@ -4803,19 +5494,27 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; } } + applySingleLine(singleLine, true); + } + private void applySingleLine(boolean singleLine, boolean applyTransformation) { + mSingleLine = singleLine; if (singleLine) { setLines(1); setHorizontallyScrolling(true); - setTransformationMethod(SingleLineTransformationMethod. - getInstance()); + if (applyTransformation) { + setTransformationMethod(SingleLineTransformationMethod. + getInstance()); + } } else { setMaxLines(Integer.MAX_VALUE); setHorizontallyScrolling(false); - setTransformationMethod(null); + if (applyTransformation) { + setTransformationMethod(null); + } } } - + /** * Causes words in the text that are longer than the view is wide * to be ellipsized instead of broken in the middle. You may also @@ -4860,6 +5559,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_selectAllOnFocus */ + @android.view.RemotableViewMethod public void setSelectAllOnFocus(boolean selectAllOnFocus) { mSelectAllOnFocus = selectAllOnFocus; @@ -4873,6 +5573,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @attr ref android.R.styleable#TextView_cursorVisible */ + @android.view.RemotableViewMethod public void setCursorVisible(boolean visible) { mCursorVisible = visible; invalidate(); @@ -4938,6 +5639,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener float mScroll; Marquee(TextView v) { + final float density = v.getContext().getResources().getDisplayMetrics().density; + mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / (float) MARQUEE_RESOLUTION; mView = new WeakReference(v); } @@ -5006,7 +5709,6 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener if (textView != null && textView.mLayout != null) { mStatus = MARQUEE_STARTING; mScroll = 0.0f; - mScrollUnit = MARQUEE_PIXELS_PER_SECOND / (float) MARQUEE_RESOLUTION; mMaxScroll = textView.mLayout.getLineWidth(0) - (textView.getWidth() - textView.getCompoundPaddingLeft() - textView.getCompoundPaddingRight()); textView.invalidate(); @@ -5045,6 +5747,16 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener int start, int before, int after) { } + /** + * This method is called when the selection has changed, in case any + * subclasses would like to know. + * + * @param selStart The new selection start location. + * @param selEnd The new selection end location. + */ + protected void onSelectionChanged(int selStart, int selEnd) { + } + /** * Adds a TextWatcher to the list of those whose methods are called * whenever this TextView's text changes. @@ -5123,26 +5835,22 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener */ void handleTextChanged(CharSequence buffer, int start, int before, int after) { - invalidate(); - - int curs = Selection.getSelectionStart(buffer); - - if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == - Gravity.BOTTOM) { - registerForPreDraw(); - } - - if (curs >= 0) { - mHighlightPathBogus = true; - - if (isFocused()) { - mShowCursor = SystemClock.uptimeMillis(); - makeBlink(); + final InputMethodState ims = mInputMethodState; + if (ims == null || ims.mBatchEditNesting == 0) { + updateAfterEdit(); + } + if (ims != null) { + ims.mContentChanged = true; + if (ims.mChangedStart < 0) { + ims.mChangedStart = start; + ims.mChangedEnd = start+before; + } else { + if (ims.mChangedStart > start) ims.mChangedStart = start; + if (ims.mChangedEnd < (start+before)) ims.mChangedEnd = start+before; } + ims.mChangedDelta += after-before; } - - checkForResize(); - + sendOnTextChanged(buffer, start, before, after); onTextChanged(buffer, start, before, after); } @@ -5151,19 +5859,27 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * Not private so it can be called from an inner class without going * through a thunk. */ - void spanChange(Spanned buf, Object what, int o, int n) { + void spanChange(Spanned buf, Object what, int oldStart, int newStart, + int oldEnd, int newEnd) { // XXX Make the start and end move together if this ends up // spending too much time invalidating. + boolean selChanged = false; + int newSelStart=-1, newSelEnd=-1; + + final InputMethodState ims = mInputMethodState; + if (what == Selection.SELECTION_END) { mHighlightPathBogus = true; + selChanged = true; + newSelEnd = newStart; if (!isFocused()) { mSelectionMoved = true; } - if (o >= 0 || n >= 0) { - invalidateCursor(Selection.getSelectionStart(buf), o, n); + if (oldStart >= 0 || newStart >= 0) { + invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); registerForPreDraw(); if (isFocused()) { @@ -5175,28 +5891,84 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener if (what == Selection.SELECTION_START) { mHighlightPathBogus = true; + selChanged = true; + newSelStart = newStart; if (!isFocused()) { mSelectionMoved = true; } - if (o >= 0 || n >= 0) { - invalidateCursor(Selection.getSelectionEnd(buf), o, n); + if (oldStart >= 0 || newStart >= 0) { + int end = Selection.getSelectionEnd(buf); + invalidateCursor(end, oldStart, newStart); } } + if (selChanged) { + if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { + if (newSelStart < 0) { + newSelStart = Selection.getSelectionStart(buf); + } + if (newSelEnd < 0) { + newSelEnd = Selection.getSelectionEnd(buf); + } + onSelectionChanged(newSelStart, newSelEnd); + } + } + if (what instanceof UpdateAppearance || what instanceof ParagraphStyle) { - invalidate(); - mHighlightPathBogus = true; - checkForResize(); + if (ims == null || ims.mBatchEditNesting == 0) { + invalidate(); + mHighlightPathBogus = true; + checkForResize(); + } else { + ims.mContentChanged = true; + } } if (MetaKeyKeyListener.isMetaTracker(buf, what)) { mHighlightPathBogus = true; + if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { + ims.mSelectionModeChanged = true; + } if (Selection.getSelectionStart(buf) >= 0) { - invalidateCursor(); + if (ims == null || ims.mBatchEditNesting == 0) { + invalidateCursor(); + } else { + ims.mCursorChanged = true; + } + } + } + + if (what instanceof ParcelableSpan) { + // If this is a span that can be sent to a remote process, + // the current extract editor would be interested in it. + if (ims != null && ims.mExtracting != null) { + if (ims.mBatchEditNesting != 0) { + if (oldStart >= 0) { + if (ims.mChangedStart > oldStart) { + ims.mChangedStart = oldStart; + } + if (ims.mChangedStart > oldEnd) { + ims.mChangedStart = oldEnd; + } + } + if (newStart >= 0) { + if (ims.mChangedStart > newStart) { + ims.mChangedStart = newStart; + } + if (ims.mChangedStart > newEnd) { + ims.mChangedStart = newEnd; + } + } + } else { + if (DEBUG_EXTRACT) Log.v(TAG, "Span change outside of batch: " + + oldStart + "-" + oldEnd + "," + + newStart + "-" + newEnd + what); + ims.mContentChanged = true; + } } } } @@ -5205,36 +5977,45 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener implements TextWatcher, SpanWatcher { public void beforeTextChanged(CharSequence buffer, int start, int before, int after) { + if (DEBUG_EXTRACT) Log.v(TAG, "beforeTextChanged start=" + start + + " before=" + before + " after=" + after + ": " + buffer); TextView.this.sendBeforeTextChanged(buffer, start, before, after); } public void onTextChanged(CharSequence buffer, int start, int before, int after) { + if (DEBUG_EXTRACT) Log.v(TAG, "onTextChanged start=" + start + + " before=" + before + " after=" + after + ": " + buffer); TextView.this.handleTextChanged(buffer, start, before, after); } public void afterTextChanged(Editable buffer) { + if (DEBUG_EXTRACT) Log.v(TAG, "afterTextChanged: " + buffer); TextView.this.sendAfterTextChanged(buffer); if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) { MetaKeyKeyListener.stopSelecting(TextView.this, buffer); } - - TextView.this.reportExtractedText(); } public void onSpanChanged(Spannable buf, Object what, int s, int e, int st, int en) { - TextView.this.spanChange(buf, what, s, st); + if (DEBUG_EXTRACT) Log.v(TAG, "onSpanChanged s=" + s + " e=" + e + + " st=" + st + " en=" + en + " what=" + what + ": " + buf); + TextView.this.spanChange(buf, what, s, st, e, en); } public void onSpanAdded(Spannable buf, Object what, int s, int e) { - TextView.this.spanChange(buf, what, -1, s); + if (DEBUG_EXTRACT) Log.v(TAG, "onSpanAdded s=" + s + " e=" + e + + " what=" + what + ": " + buf); + TextView.this.spanChange(buf, what, -1, s, -1, e); } public void onSpanRemoved(Spannable buf, Object what, int s, int e) { - TextView.this.spanChange(buf, what, s, -1); + if (DEBUG_EXTRACT) Log.v(TAG, "onSpanRemoved s=" + s + " e=" + e + + " what=" + what + ": " + buf); + TextView.this.spanChange(buf, what, s, -1, e, -1); } } @@ -5254,10 +6035,28 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener mBlink.postAtTime(mBlink, mShowCursor + BLINK); } + @Override + public void onStartTemporaryDetach() { + mTemporaryDetach = true; + } + + @Override + public void onFinishTemporaryDetach() { + mTemporaryDetach = false; + } + @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + if (mTemporaryDetach) { + // If we are temporarily in the detach state, then do nothing. + super.onFocusChanged(focused, direction, previouslyFocusedRect); + return; + } + mShowCursor = SystemClock.uptimeMillis(); + ensureEndedBatchEdit(); + if (focused) { int selStart = getSelectionStart(); int selEnd = getSelectionEnd(); @@ -5286,6 +6085,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener Selection.setSelection((Spannable) mText, selStart, selEnd); } + mTouchFocusSelected = true; } mFrozenWithFocus = false; @@ -5338,11 +6138,25 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } // Don't leave us in the middle of a batch edit. onEndBatchEdit(); + if (mInputContentType != null) { + mInputContentType.enterDown = false; + } } startStopMarquee(hasWindowFocus); } + /** + * Use {@link BaseInputConnection#removeComposingSpans + * BaseInputConnection.removeComposingSpans()} to remove any IME composing + * state from this text view. + */ + public void clearComposingText() { + if (mText instanceof Spannable) { + BaseInputConnection.removeComposingSpans((Spannable)mText); + } + } + @Override public void setSelected(boolean selected) { boolean wasSelected = isSelected(); @@ -5358,8 +6172,30 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } } + class CommitSelectionReceiver extends ResultReceiver { + int mNewStart; + int mNewEnd; + + CommitSelectionReceiver() { + super(getHandler()); + } + + protected void onReceiveResult(int resultCode, Bundle resultData) { + if (resultCode != InputMethodManager.RESULT_SHOWN) { + Selection.setSelection((Spannable)mText, mNewStart, mNewEnd); + } + } + } + @Override public boolean onTouchEvent(MotionEvent event) { + final int action = event.getAction(); + if (action == MotionEvent.ACTION_DOWN) { + // Reset this state; it will be re-set if super.onTouchEvent + // causes focus to move to the view. + mTouchFocusSelected = false; + } + final boolean superResult = super.onTouchEvent(event); /* @@ -5367,24 +6203,57 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * move the selection away from whatever the menu action was * trying to affect. */ - if (mEatTouchRelease && event.getAction() == MotionEvent.ACTION_UP) { + if (mEatTouchRelease && action == MotionEvent.ACTION_UP) { mEatTouchRelease = false; return superResult; } - if (mMovement != null && mText instanceof Spannable && - mLayout != null) { - boolean moved = mMovement.onTouchEvent(this, (Spannable) mText, event); + if ((mMovement != null || onCheckIsTextEditor()) && mText instanceof Spannable && mLayout != null) { + + if (action == MotionEvent.ACTION_DOWN) { + mScrolled = false; + } + + boolean handled = false; + + int oldSelStart = Selection.getSelectionStart(mText); + int oldSelEnd = Selection.getSelectionEnd(mText); + + if (mMovement != null) { + handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); + } if (mText instanceof Editable && onCheckIsTextEditor()) { - if (event.getAction() == MotionEvent.ACTION_UP && isFocused()) { + if (action == MotionEvent.ACTION_UP && isFocused() && !mScrolled) { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.showSoftInput(this, 0); + + // This is going to be gross... if tapping on the text view + // causes the IME to be displayed, we don't want the selection + // to change. But the selection has already changed, and + // we won't know right away whether the IME is getting + // displayed, so... + + int newSelStart = Selection.getSelectionStart(mText); + int newSelEnd = Selection.getSelectionEnd(mText); + CommitSelectionReceiver csr = null; + if (newSelStart != oldSelStart || newSelEnd != oldSelEnd) { + csr = new CommitSelectionReceiver(); + csr.mNewStart = newSelStart; + csr.mNewEnd = newSelEnd; + } + + if (imm.showSoftInput(this, 0, csr) && csr != null) { + // The IME might get shown -- revert to the old + // selection, and change to the new when we finally + // find out of it is okay. + Selection.setSelection((Spannable)mText, oldSelStart, oldSelEnd); + handled = true; + } } } - if (moved) { + if (handled) { return true; } } @@ -5392,6 +6261,22 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return superResult; } + /** + * Returns true, only while processing a touch gesture, if the initial + * touch down event caused focus to move to the text view and as a result + * its selection changed. Only valid while processing the touch gesture + * of interest. + */ + public boolean didTouchFocusSelect() { + return mTouchFocusSelected; + } + + @Override + public void cancelLongPress() { + super.cancelLongPress(); + mScrolled = true; + } + @Override public boolean onTrackballEvent(MotionEvent event) { if (mMovement != null && mText instanceof Spannable && @@ -5408,8 +6293,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener mScroller = s; } - private static class Blink extends Handler - implements Runnable { + private static class Blink extends Handler implements Runnable { private WeakReference mView; private boolean mCancelled; @@ -5514,6 +6398,11 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return super.computeVerticalScrollRange(); } + @Override + protected int computeVerticalScrollExtent() { + return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); + } + public enum BufferType { NORMAL, SPANNABLE, EDITABLE, } @@ -5568,28 +6457,28 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener switch (keyCode) { case KeyEvent.KEYCODE_A: if (canSelectAll()) { - return onMenu(ID_SELECT_ALL); + return onTextContextMenuItem(ID_SELECT_ALL); } break; case KeyEvent.KEYCODE_X: if (canCut()) { - return onMenu(ID_CUT); + return onTextContextMenuItem(ID_CUT); } break; case KeyEvent.KEYCODE_C: if (canCopy()) { - return onMenu(ID_COPY); + return onTextContextMenuItem(ID_COPY); } break; case KeyEvent.KEYCODE_V: if (canPaste()) { - return onMenu(ID_PASTE); + return onTextContextMenuItem(ID_PASTE); } break; @@ -5655,6 +6544,79 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return false; } + /** + * Returns a word to add to the dictionary from the context menu, + * or null if there is no cursor or no word at the cursor. + */ + private String getWordForDictionary() { + /* + * Quick return if the input type is one where adding words + * to the dictionary doesn't make any sense. + */ + int klass = mInputType & InputType.TYPE_MASK_CLASS; + if (klass == InputType.TYPE_CLASS_NUMBER || + klass == InputType.TYPE_CLASS_PHONE || + klass == InputType.TYPE_CLASS_DATETIME) { + return null; + } + + int variation = mInputType & InputType.TYPE_MASK_VARIATION; + if (variation == InputType.TYPE_TEXT_VARIATION_URI || + variation == InputType.TYPE_TEXT_VARIATION_PASSWORD || + variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD || + variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || + variation == InputType.TYPE_TEXT_VARIATION_FILTER) { + return null; + } + + int end = getSelectionEnd(); + + if (end < 0) { + return null; + } + + int start = end; + int len = mText.length(); + + for (; start > 0; start--) { + char c = mTransformed.charAt(start - 1); + int type = Character.getType(c); + + if (c != '\'' && + type != Character.UPPERCASE_LETTER && + type != Character.LOWERCASE_LETTER && + type != Character.TITLECASE_LETTER && + type != Character.MODIFIER_LETTER && + type != Character.DECIMAL_DIGIT_NUMBER) { + break; + } + } + + for (; end < len; end++) { + char c = mTransformed.charAt(end); + int type = Character.getType(c); + + if (c != '\'' && + type != Character.UPPERCASE_LETTER && + type != Character.LOWERCASE_LETTER && + type != Character.TITLECASE_LETTER && + type != Character.MODIFIER_LETTER && + type != Character.DECIMAL_DIGIT_NUMBER) { + break; + } + } + + if (start == end) { + return null; + } + + if (end - start > 48) { + return null; + } + + return TextUtils.substring(mTransformed, start, end); + } + @Override protected void onCreateContextMenu(ContextMenu menu) { super.onCreateContextMenu(menu); @@ -5696,7 +6658,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener setOnMenuItemClickListener(handler); added = true; } else { - menu.add(0, ID_SELECT_TEXT, 0, + menu.add(0, ID_START_SELECTING_TEXT, 0, com.android.internal.R.string.selectText). setOnMenuItemClickListener(handler); added = true; @@ -5755,11 +6717,19 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } } - InputMethodManager imm = InputMethodManager.peekInstance(); - if (imm != null && imm.isActive(this)) { - menu.add(1, ID_SWITCH_IME, 0, com.android.internal.R.string.inputMethod). + if (isInputMethodTarget()) { + menu.add(1, ID_SWITCH_INPUT_METHOD, 0, com.android.internal.R.string.inputMethod). + setOnMenuItemClickListener(handler); + added = true; + } + + String word = getWordForDictionary(); + if (word != null) { + menu.add(1, ID_ADD_TO_DICTIONARY, 0, + getContext().getString(com.android.internal.R.string.addToDictionary, word)). setOnMenuItemClickListener(handler); added = true; + } if (added) { @@ -5767,22 +6737,40 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } } - private static final int ID_SELECT_ALL = com.android.internal.R.id.selectAll; - private static final int ID_SELECT_TEXT = com.android.internal.R.id.selectText; - private static final int ID_STOP_SELECTING_TEXT = com.android.internal.R.id.stopSelectingText; - private static final int ID_CUT = com.android.internal.R.id.cut; - private static final int ID_COPY = com.android.internal.R.id.copy; - private static final int ID_PASTE = com.android.internal.R.id.paste; - private static final int ID_COPY_URL = com.android.internal.R.id.copyUrl; - private static final int ID_SWITCH_IME = com.android.internal.R.id.inputMethod; + /** + * Returns whether this text view is a current input method target. The + * default implementation just checks with {@link InputMethodManager}. + */ + public boolean isInputMethodTarget() { + InputMethodManager imm = InputMethodManager.peekInstance(); + return imm != null && imm.isActive(this); + } + + private static final int ID_SELECT_ALL = android.R.id.selectAll; + private static final int ID_START_SELECTING_TEXT = android.R.id.startSelectingText; + private static final int ID_STOP_SELECTING_TEXT = android.R.id.stopSelectingText; + private static final int ID_CUT = android.R.id.cut; + private static final int ID_COPY = android.R.id.copy; + private static final int ID_PASTE = android.R.id.paste; + private static final int ID_COPY_URL = android.R.id.copyUrl; + private static final int ID_SWITCH_INPUT_METHOD = android.R.id.switchInputMethod; + private static final int ID_ADD_TO_DICTIONARY = android.R.id.addToDictionary; private class MenuHandler implements MenuItem.OnMenuItemClickListener { public boolean onMenuItemClick(MenuItem item) { - return onMenu(item.getItemId()); + return onTextContextMenuItem(item.getItemId()); } } - private boolean onMenu(int id) { + /** + * Called when a context menu option for the text view is selected. Currently + * this will be one of: {@link android.R.id#selectAll}, + * {@link android.R.id#startSelectingText}, {@link android.R.id#stopSelectingText}, + * {@link android.R.id#cut}, {@link android.R.id#copy}, + * {@link android.R.id#paste}, {@link android.R.id#copyUrl}, + * or {@link android.R.id#switchInputMethod}. + */ + public boolean onTextContextMenuItem(int id) { int selStart = getSelectionStart(); int selEnd = getSelectionEnd(); @@ -5807,10 +6795,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener switch (id) { case ID_SELECT_ALL: Selection.setSelection((Spannable) mText, 0, - mText.length()); + mText.length()); return true; - case ID_SELECT_TEXT: + case ID_START_SELECTING_TEXT: MetaKeyKeyListener.startSelecting(this, (Spannable) mText); return true; @@ -5865,12 +6853,23 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return true; - case ID_SWITCH_IME: + case ID_SWITCH_INPUT_METHOD: InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) { imm.showInputMethodPicker(); } return true; + + case ID_ADD_TO_DICTIONARY: + String word = getWordForDictionary(); + + if (word != null) { + Intent i = new Intent("com.android.settings.USER_DICTIONARY_INSERT"); + i.putExtra("word", word); + getContext().startActivity(i); + } + + return true; } return false; @@ -5885,8 +6884,6 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return false; } - private boolean mEatTouchRelease = false; - @ViewDebug.ExportedProperty private CharSequence mText; private CharSequence mTransformed; diff --git a/core/java/android/widget/VideoView.java b/core/java/android/widget/VideoView.java index 1227afd9c186cdd1ba514250751ce56d519d2088..4c5df2f4c8152a4eb06bb78d90966a232430153d 100644 --- a/core/java/android/widget/VideoView.java +++ b/core/java/android/widget/VideoView.java @@ -46,8 +46,10 @@ import java.io.IOException; * such as scaling and tinting. */ public class VideoView extends SurfaceView implements MediaPlayerControl { + private String TAG = "VideoView"; // settable by the client private Uri mUri; + private int mDuration; // All the stuff we need for playing and showing a video private SurfaceHolder mSurfaceHolder = null; @@ -184,6 +186,8 @@ public class VideoView extends SurfaceView implements MediaPlayerControl { mMediaPlayer.setOnPreparedListener(mPreparedListener); mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener); mIsPrepared = false; + Log.v(TAG, "reset duration to -1 in openVideo"); + mDuration = -1; mMediaPlayer.setOnCompletionListener(mCompletionListener); mMediaPlayer.setOnErrorListener(mErrorListener); mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener); @@ -195,10 +199,10 @@ public class VideoView extends SurfaceView implements MediaPlayerControl { mMediaPlayer.prepareAsync(); attachMediaController(); } catch (IOException ex) { - Log.w("VideoView", "Unable to open content: " + mUri, ex); + Log.w(TAG, "Unable to open content: " + mUri, ex); return; } catch (IllegalArgumentException ex) { - Log.w("VideoView", "Unable to open content: " + mUri, ex); + Log.w(TAG, "Unable to open content: " + mUri, ex); return; } } @@ -298,15 +302,15 @@ public class VideoView extends SurfaceView implements MediaPlayerControl { private MediaPlayer.OnErrorListener mErrorListener = new MediaPlayer.OnErrorListener() { - public boolean onError(MediaPlayer mp, int a, int b) { - Log.d("VideoView", "Error: " + a + "," + b); + public boolean onError(MediaPlayer mp, int framework_err, int impl_err) { + Log.d(TAG, "Error: " + framework_err + "," + impl_err); if (mMediaController != null) { mMediaController.hide(); } /* If an error handler has been supplied, use it and finish. */ if (mOnErrorListener != null) { - if (mOnErrorListener.onError(mMediaPlayer, a, b)) { + if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) { return true; } } @@ -318,9 +322,17 @@ public class VideoView extends SurfaceView implements MediaPlayerControl { */ if (getWindowToken() != null) { Resources r = mContext.getResources(); + int messageId; + + if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) { + messageId = com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback; + } else { + messageId = com.android.internal.R.string.VideoView_error_text_unknown; + } + new AlertDialog.Builder(mContext) .setTitle(com.android.internal.R.string.VideoView_error_title) - .setMessage(com.android.internal.R.string.VideoView_error_text_unknown) + .setMessage(messageId) .setPositiveButton(com.android.internal.R.string.VideoView_error_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -497,9 +509,14 @@ public class VideoView extends SurfaceView implements MediaPlayerControl { public int getDuration() { if (mMediaPlayer != null && mIsPrepared) { - return mMediaPlayer.getDuration(); + if (mDuration > 0) { + return mDuration; + } + mDuration = mMediaPlayer.getDuration(); + return mDuration; } - return -1; + mDuration = -1; + return mDuration; } public int getCurrentPosition() { diff --git a/core/java/android/widget/ViewAnimator.java b/core/java/android/widget/ViewAnimator.java index acc9c4607ef2272d539f398434c3301aa6a015b9..fa8935e3bc552dbe017a50873394cf635f3550cb 100644 --- a/core/java/android/widget/ViewAnimator.java +++ b/core/java/android/widget/ViewAnimator.java @@ -28,6 +28,9 @@ import android.view.animation.AnimationUtils; /** * Base class for a {@link FrameLayout} container that will perform animations * when switching between its views. + * + * @attr ref android.R.styleable#ViewAnimator_inAnimation + * @attr ref android.R.styleable#ViewAnimator_outAnimation */ public class ViewAnimator extends FrameLayout { @@ -144,6 +147,56 @@ public class ViewAnimator extends FrameLayout { } } + @Override + public void removeAllViews() { + super.removeAllViews(); + mWhichChild = 0; + mFirstTime = true; + } + + @Override + public void removeView(View view) { + final int index = indexOfChild(view); + if (index >= 0) { + removeViewAt(index); + } + } + + @Override + public void removeViewAt(int index) { + super.removeViewAt(index); + final int childCount = getChildCount(); + if (childCount == 0) { + mWhichChild = 0; + mFirstTime = true; + } else if (mWhichChild >= childCount) { + // Displayed is above child count, so float down to top of stack + setDisplayedChild(childCount - 1); + } else if (mWhichChild == index) { + // Displayed was removed, so show the new child living in its place + setDisplayedChild(mWhichChild); + } + } + + public void removeViewInLayout(View view) { + removeView(view); + } + + public void removeViews(int start, int count) { + super.removeViews(start, count); + if (getChildCount() == 0) { + mWhichChild = 0; + mFirstTime = true; + } else if (mWhichChild >= start && mWhichChild < start + count) { + // Try showing new displayed child, wrapping if needed + setDisplayedChild(mWhichChild); + } + } + + public void removeViewsInLayout(int start, int count) { + removeViews(start, count); + } + /** * Returns the View corresponding to the currently displayed child. * diff --git a/core/java/android/widget/ViewFlipper.java b/core/java/android/widget/ViewFlipper.java index a3c15d945b3b2c0d064c87a43ab8b1ad9926e958..8a7946b951b1a464f3ea38e9b4af1c1c60ee2b87 100644 --- a/core/java/android/widget/ViewFlipper.java +++ b/core/java/android/widget/ViewFlipper.java @@ -22,11 +22,14 @@ import android.content.res.TypedArray; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; +import android.widget.RemoteViews.RemoteView; /** * Simple {@link ViewAnimator} that will animate between two or more views * that have been added to it. Only one child is shown at a time. If * requested, can automatically flip between each child at a regular interval. + * + * @attr ref android.R.styleable#ViewFlipper_flipInterval */ public class ViewFlipper extends ViewAnimator { private int mFlipInterval = 3000; @@ -52,6 +55,7 @@ public class ViewFlipper extends ViewAnimator { * @param milliseconds * time in milliseconds */ + @android.view.RemotableViewMethod public void setFlipInterval(int milliseconds) { mFlipInterval = milliseconds; } diff --git a/core/java/android/widget/ZoomButton.java b/core/java/android/widget/ZoomButton.java index 5df8c8adf58a651f79fb7bb004b44232a09d37e6..0df919d02a5f3fbb5eb3ff30336eac8ba5cdd0cb 100644 --- a/core/java/android/widget/ZoomButton.java +++ b/core/java/android/widget/ZoomButton.java @@ -20,6 +20,7 @@ import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.view.GestureDetector; +import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; @@ -54,9 +55,10 @@ public class ZoomButton extends ImageButton implements OnLongClickListener { public ZoomButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mHandler = new Handler(); - mGestureDetector = new GestureDetector(new SimpleOnGestureListener() { + mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener() { @Override public void onLongPress(MotionEvent e) { + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); onLongClick(ZoomButton.this); } }); diff --git a/core/java/android/widget/ZoomButtonsController.java b/core/java/android/widget/ZoomButtonsController.java new file mode 100644 index 0000000000000000000000000000000000000000..4daa41949330bbc0c52eb78e95f20bbb44cf6a49 --- /dev/null +++ b/core/java/android/widget/ZoomButtonsController.java @@ -0,0 +1,848 @@ +/* + * 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. + */ + +package android.widget; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.BroadcastReceiver; +import android.content.ContentResolver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.graphics.Canvas; +import android.graphics.PixelFormat; +import android.graphics.Rect; +import android.os.Handler; +import android.os.Message; +import android.os.SystemClock; +import android.provider.Settings; +import android.util.Log; +import android.view.GestureDetector; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.ViewGroup; +import android.view.ViewParent; +import android.view.ViewRoot; +import android.view.Window; +import android.view.WindowManager; +import android.view.View.OnClickListener; +import android.view.WindowManager.LayoutParams; + +/* + * Implementation notes: + * - The zoom controls are displayed in their own window. + * (Easier for the client and better performance) + * - This window is not touchable, and by default is not focusable. + * - To make the buttons clickable, it attaches a OnTouchListener to the owner + * view and does the hit detection locally. + * - When it is focusable, it forwards uninteresting events to the owner view's + * view hierarchy. + */ +/** + * The {@link ZoomButtonsController} handles showing and hiding the zoom + * controls relative to an owner view. It also gives the client access to the + * zoom controls container, allowing for additional accessory buttons to be + * shown in the zoom controls window. + *

          + * Typical usage involves the client using the {@link GestureDetector} to + * forward events from + * {@link GestureDetector.OnDoubleTapListener#onDoubleTapEvent(MotionEvent)} to + * {@link #handleDoubleTapEvent(MotionEvent)}. Also, whenever the owner cannot + * be zoomed further, the client should update + * {@link #setZoomInEnabled(boolean)} and {@link #setZoomOutEnabled(boolean)}. + *

          + * If you are using this with a custom View, please call + * {@link #setVisible(boolean) setVisible(false)} from the + * {@link View#onDetachedFromWindow}. + * + * @hide + */ +public class ZoomButtonsController implements View.OnTouchListener { + + private static final String TAG = "ZoomButtonsController"; + + private static final int ZOOM_CONTROLS_TIMEOUT = + (int) ViewConfiguration.getZoomControlsTimeout(); + + private static final int ZOOM_CONTROLS_TOUCH_PADDING = 20; + private int mTouchPaddingScaledSq; + + private Context mContext; + private WindowManager mWindowManager; + + /** + * The view that is being zoomed by this zoom controller. + */ + private View mOwnerView; + + /** + * The location of the owner view on the screen. This is recalculated + * each time the zoom controller is shown. + */ + private int[] mOwnerViewRawLocation = new int[2]; + + /** + * The container that is added as a window. + */ + private FrameLayout mContainer; + private LayoutParams mContainerLayoutParams; + private int[] mContainerRawLocation = new int[2]; + + private ZoomControls mControls; + + /** + * The view (or null) that should receive touch events. This will get set if + * the touch down hits the container. It will be reset on the touch up. + */ + private View mTouchTargetView; + /** + * The {@link #mTouchTargetView}'s location in window, set on touch down. + */ + private int[] mTouchTargetWindowLocation = new int[2]; + /** + * If the zoom controller is dismissed but the user is still in a touch + * interaction, we set this to true. This will ignore all touch events until + * up/cancel, and then set the owner's touch listener to null. + */ + private boolean mReleaseTouchListenerOnUp; + + /** + * Whether we are currently in the double-tap gesture, with the second tap + * still being performed (i.e., we're waiting for the second tap's touch up). + */ + private boolean mIsSecondTapDown; + + /** Whether the container has been added to the window manager. */ + private boolean mIsVisible; + + private Rect mTempRect = new Rect(); + private int[] mTempIntArray = new int[2]; + + private OnZoomListener mCallback; + + /** + * In 1.0, the ZoomControls were to be added to the UI by the client of + * WebView, MapView, etc. We didn't want apps to break, so we return a dummy + * view in place now. + */ + private InvisibleView mDummyZoomControls; + + /** + * When showing the zoom, we add the view as a new window. However, there is + * logic that needs to know the size of the zoom which is determined after + * it's laid out. Therefore, we must post this logic onto the UI thread so + * it will be exceuted AFTER the layout. This is the logic. + */ + private Runnable mPostedVisibleInitializer; + + private IntentFilter mConfigurationChangedFilter = + new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED); + + /** + * Needed to reposition the zoom controls after configuration changes. + */ + private BroadcastReceiver mConfigurationChangedReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (!mIsVisible) return; + + mHandler.removeMessages(MSG_POST_CONFIGURATION_CHANGED); + mHandler.sendEmptyMessage(MSG_POST_CONFIGURATION_CHANGED); + } + }; + + /** + * The setting name that tracks whether we've shown the zoom tutorial. + */ + private static final String SETTING_NAME_SHOWN_TUTORIAL = "shown_zoom_tutorial"; + private static Dialog sTutorialDialog; + + /** When configuration changes, this is called after the UI thread is idle. */ + private static final int MSG_POST_CONFIGURATION_CHANGED = 2; + /** Used to delay the zoom controller dismissal. */ + private static final int MSG_DISMISS_ZOOM_CONTROLS = 3; + /** + * If setVisible(true) is called and the owner view's window token is null, + * we delay the setVisible(true) call until it is not null. + */ + private static final int MSG_POST_SET_VISIBLE = 4; + + private Handler mHandler = new Handler() { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MSG_POST_CONFIGURATION_CHANGED: + onPostConfigurationChanged(); + break; + + case MSG_DISMISS_ZOOM_CONTROLS: + setVisible(false); + break; + + case MSG_POST_SET_VISIBLE: + if (mOwnerView.getWindowToken() == null) { + // Doh, it is still null, just ignore the set visible call + Log.e(TAG, + "Cannot make the zoom controller visible if the owner view is " + + "not attached to a window."); + } else { + setVisible(true); + } + break; + } + + } + }; + + /** + * Constructor for the {@link ZoomButtonsController}. + * + * @param ownerView The view that is being zoomed by the zoom controls. The + * zoom controls will be displayed aligned with this view. + */ + public ZoomButtonsController(View ownerView) { + mContext = ownerView.getContext(); + mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); + mOwnerView = ownerView; + + mTouchPaddingScaledSq = (int) + (ZOOM_CONTROLS_TOUCH_PADDING * mContext.getResources().getDisplayMetrics().density); + mTouchPaddingScaledSq *= mTouchPaddingScaledSq; + + mContainer = createContainer(); + } + + /** + * Whether to enable the zoom in control. + * + * @param enabled Whether to enable the zoom in control. + */ + public void setZoomInEnabled(boolean enabled) { + mControls.setIsZoomInEnabled(enabled); + } + + /** + * Whether to enable the zoom out control. + * + * @param enabled Whether to enable the zoom out control. + */ + public void setZoomOutEnabled(boolean enabled) { + mControls.setIsZoomOutEnabled(enabled); + } + + /** + * Sets the delay between zoom callbacks as the user holds a zoom button. + * + * @param speed The delay in milliseconds between zoom callbacks. + */ + public void setZoomSpeed(long speed) { + mControls.setZoomSpeed(speed); + } + + private FrameLayout createContainer() { + LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + // Controls are positioned BOTTOM | CENTER with respect to the owner view. + lp.gravity = Gravity.TOP | Gravity.LEFT; + lp.flags = LayoutParams.FLAG_NOT_TOUCHABLE | + LayoutParams.FLAG_NOT_FOCUSABLE | + LayoutParams.FLAG_LAYOUT_NO_LIMITS; + lp.height = LayoutParams.WRAP_CONTENT; + lp.width = LayoutParams.FILL_PARENT; + lp.type = LayoutParams.TYPE_APPLICATION_PANEL; + lp.format = PixelFormat.TRANSPARENT; + lp.windowAnimations = com.android.internal.R.style.Animation_ZoomButtons; + mContainerLayoutParams = lp; + + FrameLayout container = new Container(mContext); + container.setLayoutParams(lp); + container.setMeasureAllChildren(true); + + LayoutInflater inflater = (LayoutInflater) mContext + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + inflater.inflate(com.android.internal.R.layout.zoom_container, container); + + mControls = (ZoomControls) container.findViewById(com.android.internal.R.id.zoomControls); + mControls.setOnZoomInClickListener(new OnClickListener() { + public void onClick(View v) { + dismissControlsDelayed(ZOOM_CONTROLS_TIMEOUT); + if (mCallback != null) mCallback.onZoom(true); + } + }); + mControls.setOnZoomOutClickListener(new OnClickListener() { + public void onClick(View v) { + dismissControlsDelayed(ZOOM_CONTROLS_TIMEOUT); + if (mCallback != null) mCallback.onZoom(false); + } + }); + + return container; + } + + /** + * Sets the {@link OnZoomListener} listener that receives callbacks to zoom. + * + * @param listener The listener that will be told to zoom. + */ + public void setOnZoomListener(OnZoomListener listener) { + mCallback = listener; + } + + /** + * Sets whether the zoom controls should be focusable. If the controls are + * focusable, then trackball and arrow key interactions are possible. + * Otherwise, only touch interactions are possible. + * + * @param focusable Whether the zoom controls should be focusable. + */ + public void setFocusable(boolean focusable) { + int oldFlags = mContainerLayoutParams.flags; + if (focusable) { + mContainerLayoutParams.flags &= ~LayoutParams.FLAG_NOT_FOCUSABLE; + } else { + mContainerLayoutParams.flags |= LayoutParams.FLAG_NOT_FOCUSABLE; + } + + if ((mContainerLayoutParams.flags != oldFlags) && mIsVisible) { + mWindowManager.updateViewLayout(mContainer, mContainerLayoutParams); + } + } + + /** + * Whether the zoom controls are visible to the user. + * + * @return Whether the zoom controls are visible to the user. + */ + public boolean isVisible() { + return mIsVisible; + } + + /** + * Sets whether the zoom controls should be visible to the user. + * + * @param visible Whether the zoom controls should be visible to the user. + */ + public void setVisible(boolean visible) { + + if (visible) { + if (mOwnerView.getWindowToken() == null) { + /* + * We need a window token to show ourselves, maybe the owner's + * window hasn't been created yet but it will have been by the + * time the looper is idle, so post the setVisible(true) call. + */ + if (!mHandler.hasMessages(MSG_POST_SET_VISIBLE)) { + mHandler.sendEmptyMessage(MSG_POST_SET_VISIBLE); + } + return; + } + + dismissControlsDelayed(ZOOM_CONTROLS_TIMEOUT); + } + + if (mIsVisible == visible) { + return; + } + mIsVisible = visible; + + if (visible) { + if (mContainerLayoutParams.token == null) { + mContainerLayoutParams.token = mOwnerView.getWindowToken(); + } + + mWindowManager.addView(mContainer, mContainerLayoutParams); + + if (mPostedVisibleInitializer == null) { + mPostedVisibleInitializer = new Runnable() { + public void run() { + refreshPositioningVariables(); + + if (mCallback != null) { + mCallback.onVisibilityChanged(true); + } + } + }; + } + + mHandler.post(mPostedVisibleInitializer); + + // Handle configuration changes when visible + mContext.registerReceiver(mConfigurationChangedReceiver, mConfigurationChangedFilter); + + // Steal touches events from the owner + mOwnerView.setOnTouchListener(this); + mReleaseTouchListenerOnUp = false; + + } else { + // Don't want to steal any more touches + if (mTouchTargetView != null) { + // We are still stealing the touch events for this touch + // sequence, so release the touch listener later + mReleaseTouchListenerOnUp = true; + } else { + mOwnerView.setOnTouchListener(null); + } + + // No longer care about configuration changes + mContext.unregisterReceiver(mConfigurationChangedReceiver); + + mWindowManager.removeView(mContainer); + mHandler.removeCallbacks(mPostedVisibleInitializer); + + if (mCallback != null) { + mCallback.onVisibilityChanged(false); + } + } + + } + + /** + * Gets the container that is the parent of the zoom controls. + *

          + * The client can add other views to this container to link them with the + * zoom controls. + * + * @return The container of the zoom controls. It will be a layout that + * respects the gravity of a child's layout parameters. + */ + public ViewGroup getContainer() { + return mContainer; + } + + private void dismissControlsDelayed(int delay) { + mHandler.removeMessages(MSG_DISMISS_ZOOM_CONTROLS); + mHandler.sendEmptyMessageDelayed(MSG_DISMISS_ZOOM_CONTROLS, delay); + } + + /** + * Should be called by the client for each event belonging to the second tap + * (the down, move, up, and/or cancel events). + * + * @param event The event belonging to the second tap. + * @return Whether the event was consumed. + */ + public boolean handleDoubleTapEvent(MotionEvent event) { + int action = event.getAction(); + + if (action == MotionEvent.ACTION_DOWN) { + int x = (int) event.getX(); + int y = (int) event.getY(); + + /* + * This class will consume all events in the second tap (down, + * move(s), up). But, the owner already got the second tap's down, + * so cancel that. Do this before setVisible, since that call + * will set us as a touch listener. + */ + MotionEvent cancelEvent = MotionEvent.obtain(event.getDownTime(), + SystemClock.elapsedRealtime(), + MotionEvent.ACTION_CANCEL, 0, 0, 0); + mOwnerView.dispatchTouchEvent(cancelEvent); + cancelEvent.recycle(); + + setVisible(true); + centerPoint(x, y); + mIsSecondTapDown = true; + } + + return true; + } + + private void refreshPositioningVariables() { + // Position the zoom controls on the bottom of the owner view. + int ownerHeight = mOwnerView.getHeight(); + int ownerWidth = mOwnerView.getWidth(); + // The gap between the top of the owner and the top of the container + int containerOwnerYOffset = ownerHeight - mContainer.getHeight(); + + // Calculate the owner view's bounds + mOwnerView.getLocationOnScreen(mOwnerViewRawLocation); + mContainerRawLocation[0] = mOwnerViewRawLocation[0]; + mContainerRawLocation[1] = mOwnerViewRawLocation[1] + containerOwnerYOffset; + + int[] ownerViewWindowLoc = mTempIntArray; + mOwnerView.getLocationInWindow(ownerViewWindowLoc); + + // lp.x and lp.y should be relative to the owner's window top-left + mContainerLayoutParams.x = ownerViewWindowLoc[0]; + mContainerLayoutParams.width = ownerWidth; + mContainerLayoutParams.y = ownerViewWindowLoc[1] + containerOwnerYOffset; + if (mIsVisible) { + mWindowManager.updateViewLayout(mContainer, mContainerLayoutParams); + } + + } + + /** + * Centers the point (in owner view's coordinates). + */ + private void centerPoint(int x, int y) { + if (mCallback != null) { + mCallback.onCenter(x, y); + } + } + + /* This will only be called when the container has focus. */ + private boolean onContainerKey(KeyEvent event) { + int keyCode = event.getKeyCode(); + if (isInterestingKey(keyCode)) { + + if (keyCode == KeyEvent.KEYCODE_BACK) { + setVisible(false); + } else { + dismissControlsDelayed(ZOOM_CONTROLS_TIMEOUT); + } + + // Let the container handle the key + return false; + + } else { + + ViewRoot viewRoot = getOwnerViewRoot(); + if (viewRoot != null) { + viewRoot.dispatchKey(event); + } + + // We gave the key to the owner, don't let the container handle this key + return true; + } + } + + private boolean isInterestingKey(int keyCode) { + switch (keyCode) { + case KeyEvent.KEYCODE_DPAD_CENTER: + case KeyEvent.KEYCODE_DPAD_UP: + case KeyEvent.KEYCODE_DPAD_DOWN: + case KeyEvent.KEYCODE_DPAD_LEFT: + case KeyEvent.KEYCODE_DPAD_RIGHT: + case KeyEvent.KEYCODE_ENTER: + case KeyEvent.KEYCODE_BACK: + return true; + default: + return false; + } + } + + private ViewRoot getOwnerViewRoot() { + View rootViewOfOwner = mOwnerView.getRootView(); + if (rootViewOfOwner == null) { + return null; + } + + ViewParent parentOfRootView = rootViewOfOwner.getParent(); + if (parentOfRootView instanceof ViewRoot) { + return (ViewRoot) parentOfRootView; + } else { + return null; + } + } + + /** + * @hide The ZoomButtonsController implements the OnTouchListener, but this + * does not need to be shown in its public API. + */ + public boolean onTouch(View v, MotionEvent event) { + int action = event.getAction(); + + // Consume all events during the second-tap interaction (down, move, up/cancel) + boolean consumeEvent = mIsSecondTapDown; + if ((action == MotionEvent.ACTION_UP) || (action == MotionEvent.ACTION_CANCEL)) { + // The second tap can no longer be down + mIsSecondTapDown = false; + } + + if (mReleaseTouchListenerOnUp) { + // The controls were dismissed but we need to throw away all events until the up + if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { + mOwnerView.setOnTouchListener(null); + setTouchTargetView(null); + mReleaseTouchListenerOnUp = false; + } + + // Eat this event + return true; + } + + dismissControlsDelayed(ZOOM_CONTROLS_TIMEOUT); + + View targetView = mTouchTargetView; + + switch (action) { + case MotionEvent.ACTION_DOWN: + targetView = findViewForTouch((int) event.getRawX(), (int) event.getRawY()); + setTouchTargetView(targetView); + break; + + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + setTouchTargetView(null); + break; + } + + if (targetView != null) { + // The upperleft corner of the target view in raw coordinates + int targetViewRawX = mContainerRawLocation[0] + mTouchTargetWindowLocation[0]; + int targetViewRawY = mContainerRawLocation[1] + mTouchTargetWindowLocation[1]; + + MotionEvent containerEvent = MotionEvent.obtain(event); + // Convert the motion event into the target view's coordinates (from + // owner view's coordinates) + containerEvent.offsetLocation(mOwnerViewRawLocation[0] - targetViewRawX, + mOwnerViewRawLocation[1] - targetViewRawY); + /* Disallow negative coordinates (which can occur due to + * ZOOM_CONTROLS_TOUCH_PADDING) */ + if (containerEvent.getX() < 0) { + containerEvent.offsetLocation(-containerEvent.getX(), 0); + } + if (containerEvent.getY() < 0) { + containerEvent.offsetLocation(0, -containerEvent.getY()); + } + boolean retValue = targetView.dispatchTouchEvent(containerEvent); + containerEvent.recycle(); + return retValue || consumeEvent; + + } else { + return consumeEvent; + } + } + + private void setTouchTargetView(View view) { + mTouchTargetView = view; + if (view != null) { + view.getLocationInWindow(mTouchTargetWindowLocation); + } + } + + /** + * Returns the View that should receive a touch at the given coordinates. + * + * @param rawX The raw X. + * @param rawY The raw Y. + * @return The view that should receive the touches, or null if there is not one. + */ + private View findViewForTouch(int rawX, int rawY) { + // Reverse order so the child drawn on top gets first dibs. + int containerCoordsX = rawX - mContainerRawLocation[0]; + int containerCoordsY = rawY - mContainerRawLocation[1]; + Rect frame = mTempRect; + + View closestChild = null; + int closestChildDistanceSq = Integer.MAX_VALUE; + + for (int i = mContainer.getChildCount() - 1; i >= 0; i--) { + View child = mContainer.getChildAt(i); + if (child.getVisibility() != View.VISIBLE) { + continue; + } + + child.getHitRect(frame); + if (frame.contains(containerCoordsX, containerCoordsY)) { + return child; + } + + int distanceX = Math.min(Math.abs(frame.left - containerCoordsX), + Math.abs(containerCoordsX - frame.right)); + int distanceY = Math.min(Math.abs(frame.top - containerCoordsY), + Math.abs(containerCoordsY - frame.bottom)); + int distanceSq = distanceX * distanceX + distanceY * distanceY; + + if ((distanceSq < mTouchPaddingScaledSq) && + (distanceSq < closestChildDistanceSq)) { + closestChild = child; + closestChildDistanceSq = distanceSq; + } + } + + return closestChild; + } + + private void onPostConfigurationChanged() { + dismissControlsDelayed(ZOOM_CONTROLS_TIMEOUT); + refreshPositioningVariables(); + } + + /* + * This is static so Activities can call this instead of the Views + * (Activities usually do not have a reference to the ZoomButtonsController + * instance.) + */ + /** + * Shows a "tutorial" (some text) to the user teaching her the new zoom + * invocation method. Must call from the main thread. + *

          + * It checks the global system setting to ensure this has not been seen + * before. Furthermore, if the application does not have privilege to write + * to the system settings, it will store this bit locally in a shared + * preference. + * + * @hide This should only be used by our main apps--browser, maps, and + * gallery + */ + public static void showZoomTutorialOnce(Context context) { + + // TODO: remove this code, but to hit the weekend build, just never show + if (true) return; + + ContentResolver cr = context.getContentResolver(); + if (Settings.System.getInt(cr, SETTING_NAME_SHOWN_TUTORIAL, 0) == 1) { + return; + } + + SharedPreferences sp = context.getSharedPreferences("_zoom", Context.MODE_PRIVATE); + if (sp.getInt(SETTING_NAME_SHOWN_TUTORIAL, 0) == 1) { + return; + } + + if (sTutorialDialog != null && sTutorialDialog.isShowing()) { + sTutorialDialog.dismiss(); + } + + LayoutInflater layoutInflater = + (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + TextView textView = (TextView) layoutInflater.inflate( + com.android.internal.R.layout.alert_dialog_simple_text, null) + .findViewById(android.R.id.text1); + textView.setText(com.android.internal.R.string.tutorial_double_tap_to_zoom_message_short); + + sTutorialDialog = new AlertDialog.Builder(context) + .setView(textView) + .setIcon(0) + .create(); + + Window window = sTutorialDialog.getWindow(); + window.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM); + window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND | + WindowManager.LayoutParams.FLAG_BLUR_BEHIND); + window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | + WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); + + sTutorialDialog.show(); + } + + /** @hide Should only be used by Android platform apps */ + public static void finishZoomTutorial(Context context, boolean userNotified) { + if (sTutorialDialog == null) return; + + sTutorialDialog.dismiss(); + sTutorialDialog = null; + + // Record that they have seen the tutorial + if (userNotified) { + try { + Settings.System.putInt(context.getContentResolver(), SETTING_NAME_SHOWN_TUTORIAL, + 1); + } catch (SecurityException e) { + /* + * The app does not have permission to clear this global flag, make + * sure the user does not see the message when he comes back to this + * same app at least. + */ + SharedPreferences sp = context.getSharedPreferences("_zoom", Context.MODE_PRIVATE); + sp.edit().putInt(SETTING_NAME_SHOWN_TUTORIAL, 1).commit(); + } + } + } + + /** @hide Should only be used by Android platform apps */ + public void finishZoomTutorial() { + finishZoomTutorial(mContext, true); + } + + /** @hide Should only be used only be WebView and MapView */ + public View getDummyZoomControls() { + if (mDummyZoomControls == null) { + mDummyZoomControls = new InvisibleView(mContext); + } + return mDummyZoomControls; + } + + /** + * Interface that will be called when the user performs an interaction that + * triggers some action, for example zooming. + */ + public interface OnZoomListener { + /** + * Called when the given point should be centered. The point will be in + * owner view coordinates. + * + * @param x The x of the point. + * @param y The y of the point. + */ + void onCenter(int x, int y); + + /** + * Called when the zoom controls' visibility changes. + * + * @param visible Whether the zoom controls are visible. + */ + void onVisibilityChanged(boolean visible); + + /** + * Called when the owner view needs to be zoomed. + * + * @param zoomIn The direction of the zoom: true to zoom in, false to zoom out. + */ + void onZoom(boolean zoomIn); + } + + private class Container extends FrameLayout { + public Container(Context context) { + super(context); + } + + /* + * Need to override this to intercept the key events. Otherwise, we + * would attach a key listener to the container but its superclass + * ViewGroup gives it to the focused View instead of calling the key + * listener, and so we wouldn't get the events. + */ + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + return onContainerKey(event) ? true : super.dispatchKeyEvent(event); + } + } + + /** + * An InvisibleView is an invisible, zero-sized View for backwards + * compatibility + */ + private final class InvisibleView extends View { + + private InvisibleView(Context context) { + super(context); + setVisibility(GONE); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + setMeasuredDimension(0, 0); + } + + @Override + public void draw(Canvas canvas) { + } + + @Override + protected void dispatchDraw(Canvas canvas) { + } + } + +} diff --git a/core/java/android/widget/ZoomControls.java b/core/java/android/widget/ZoomControls.java index 1fd662c70e551b3e5ea7b54c1c5230b02cbb0ba8..84d8f0e015b39c54ac9cef16d1fa9f934ea68192 100644 --- a/core/java/android/widget/ZoomControls.java +++ b/core/java/android/widget/ZoomControls.java @@ -29,8 +29,12 @@ import com.android.internal.R; /** * The {@code ZoomControls} class displays a simple set of controls used for zooming and - * provides callbacks to register for events. - */ + * provides callbacks to register for events. */ +// TODO: pending API council +// *

          +// * Instead of using this directly, consider using the {@link ZoomButtonsController} which +// * handles displaying the zoom controls. +// */ @Widget public class ZoomControls extends LinearLayout { diff --git a/core/java/com/android/internal/app/ExternalMediaFormatActivity.java b/core/java/com/android/internal/app/ExternalMediaFormatActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..000f6c49ab4995d80d308c8754d9756d2a3cecc7 --- /dev/null +++ b/core/java/com/android/internal/app/ExternalMediaFormatActivity.java @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2007 Google Inc. + * + * 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. + */ + +package com.android.internal.app; + +import android.app.AlertDialog; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import android.os.Handler; +import android.os.IMountService; +import android.os.Message; +import android.os.RemoteException; +import android.os.ServiceManager; +import android.os.Environment; +import android.widget.Toast; +import android.util.Log; + +/** + * This activity is shown to the user to confirm formatting of external media. + * It uses the alert dialog style. It will be launched from a notification, or from settings + */ +public class ExternalMediaFormatActivity extends AlertActivity implements DialogInterface.OnClickListener { + + private static final int POSITIVE_BUTTON = AlertDialog.BUTTON1; + + /** Used to detect when the media state changes, in case we need to call finish() */ + private BroadcastReceiver mStorageReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + Log.d("ExternalMediaFormatActivity", "got action " + action); + + if (action == Intent.ACTION_MEDIA_REMOVED || + action == Intent.ACTION_MEDIA_CHECKING || + action == Intent.ACTION_MEDIA_MOUNTED || + action == Intent.ACTION_MEDIA_SHARED) { + finish(); + } + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + Log.d("ExternalMediaFormatActivity", "onCreate!"); + // Set up the "dialog" + final AlertController.AlertParams p = mAlertParams; + p.mIconId = com.android.internal.R.drawable.stat_sys_warning; + p.mTitle = getString(com.android.internal.R.string.extmedia_format_title); + p.mMessage = getString(com.android.internal.R.string.extmedia_format_message); + p.mPositiveButtonText = getString(com.android.internal.R.string.extmedia_format_button_format); + p.mPositiveButtonListener = this; + p.mNegativeButtonText = getString(com.android.internal.R.string.cancel); + p.mNegativeButtonListener = this; + setupAlert(); + } + + @Override + protected void onResume() { + super.onResume(); + + IntentFilter filter = new IntentFilter(); + filter.addAction(Intent.ACTION_MEDIA_REMOVED); + filter.addAction(Intent.ACTION_MEDIA_CHECKING); + filter.addAction(Intent.ACTION_MEDIA_MOUNTED); + filter.addAction(Intent.ACTION_MEDIA_SHARED); + registerReceiver(mStorageReceiver, filter); + } + + @Override + protected void onPause() { + super.onPause(); + + unregisterReceiver(mStorageReceiver); + } + + /** + * {@inheritDoc} + */ + public void onClick(DialogInterface dialog, int which) { + + if (which == POSITIVE_BUTTON) { + IMountService mountService = IMountService.Stub.asInterface(ServiceManager + .getService("mount")); + if (mountService != null) { + try { + mountService.formatMedia(Environment.getExternalStorageDirectory().toString()); + } catch (RemoteException e) { + } + } + } + + // No matter what, finish the activity + finish(); + } +} diff --git a/core/java/com/android/internal/app/IBatteryStats.aidl b/core/java/com/android/internal/app/IBatteryStats.aidl index 434850c439ba98abc643f32b5539df2b2d2c1636..edda1d92300593f27328566d9bdaa833209efbf5 100644 --- a/core/java/com/android/internal/app/IBatteryStats.aidl +++ b/core/java/com/android/internal/app/IBatteryStats.aidl @@ -19,11 +19,17 @@ package com.android.internal.app; import com.android.internal.os.BatteryStatsImpl; interface IBatteryStats { - BatteryStatsImpl getStatistics(); + byte[] getStatistics(); void noteStartWakelock(int uid, String name, int type); void noteStopWakelock(int uid, String name, int type); void noteStartSensor(int uid, int sensor); void noteStopSensor(int uid, int sensor); + void noteStartGps(int uid); + void noteStopGps(int uid); + void noteScreenOn(); + void noteScreenOff(); + void notePhoneOn(); + void notePhoneOff(); void setOnBattery(boolean onBattery); long getAwakeTimeBattery(); long getAwakeTimePlugged(); diff --git a/tests/GadgetHost/src/com/android/gadgethost/TestGadgetProvider.java b/core/java/com/android/internal/app/IUsageStats.aidl old mode 100644 new mode 100755 similarity index 62% rename from tests/GadgetHost/src/com/android/gadgethost/TestGadgetProvider.java rename to core/java/com/android/internal/app/IUsageStats.aidl index 8f9641b6fe8c70d9b95ad3bf13f16631f710a636..6b053d5c99751557e4738d5e171462f8aa32add9 --- a/tests/GadgetHost/src/com/android/gadgethost/TestGadgetProvider.java +++ b/core/java/com/android/internal/app/IUsageStats.aidl @@ -14,19 +14,14 @@ * limitations under the License. */ -package com.android.gadgethost; +package com.android.internal.app; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.util.Log; +import android.content.ComponentName; +import com.android.internal.os.PkgUsageStats; -public class TestGadgetProvider extends BroadcastReceiver { - - static final String TAG = "TestGadgetProvider"; - - public void onReceive(Context context, Intent intent) { - Log.d(TAG, "intent=" + intent); - } +interface IUsageStats { + void noteResumeComponent(in ComponentName componentName); + void notePauseComponent(in ComponentName componentName); + PkgUsageStats getPkgUsageStats(in ComponentName componentName); + PkgUsageStats[] getAllPkgUsageStats(); } - diff --git a/core/java/com/android/internal/app/UsbStorageStopActivity.java b/core/java/com/android/internal/app/UsbStorageStopActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..557a5232a62461050d491edb2f6fbfa45d2b218c --- /dev/null +++ b/core/java/com/android/internal/app/UsbStorageStopActivity.java @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2007 Google Inc. + * + * 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. + */ + +package com.android.internal.app; + +import android.app.AlertDialog; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import android.os.Handler; +import android.os.IMountService; +import android.os.Message; +import android.os.RemoteException; +import android.os.ServiceManager; +import android.widget.Toast; + +/** + * This activity is shown to the user for him/her to disable USB mass storage. + * It uses the alert dialog style. It will be launched from a notification. + */ +public class UsbStorageStopActivity extends AlertActivity implements DialogInterface.OnClickListener { + + private static final int POSITIVE_BUTTON = AlertDialog.BUTTON1; + + /** Used to detect when the USB cable is unplugged, so we can call finish() */ + private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction() == Intent.ACTION_BATTERY_CHANGED) { + handleBatteryChanged(intent); + } + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Set up the "dialog" + final AlertController.AlertParams p = mAlertParams; + p.mIconId = com.android.internal.R.drawable.ic_dialog_alert; + p.mTitle = getString(com.android.internal.R.string.usb_storage_stop_title); + p.mMessage = getString(com.android.internal.R.string.usb_storage_stop_message); + p.mPositiveButtonText = getString(com.android.internal.R.string.usb_storage_stop_button_mount); + p.mPositiveButtonListener = this; + p.mNegativeButtonText = getString(com.android.internal.R.string.usb_storage_stop_button_unmount); + p.mNegativeButtonListener = this; + setupAlert(); + } + + @Override + protected void onResume() { + super.onResume(); + + registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + } + + @Override + protected void onPause() { + super.onPause(); + + unregisterReceiver(mBatteryReceiver); + } + + /** + * {@inheritDoc} + */ + public void onClick(DialogInterface dialog, int which) { + + if (which == POSITIVE_BUTTON) { + stopUsbStorage(); + } + + // No matter what, finish the activity + finish(); + } + + private void stopUsbStorage() { + IMountService mountService = IMountService.Stub.asInterface(ServiceManager + .getService("mount")); + if (mountService == null) { + showStoppingError(); + return; + } + + try { + mountService.setMassStorageEnabled(false); + } catch (RemoteException e) { + showStoppingError(); + return; + } + } + + private void handleBatteryChanged(Intent intent) { + int pluggedType = intent.getIntExtra("plugged", 0); + if (pluggedType == 0) { + // It was disconnected from the plug, so finish + finish(); + } + } + + private void showStoppingError() { + Toast.makeText(this, com.android.internal.R.string.usb_storage_stop_error_message, + Toast.LENGTH_LONG).show(); + } + +} diff --git a/core/java/com/android/internal/gadget/IGadgetService.aidl b/core/java/com/android/internal/appwidget/IAppWidgetHost.aidl similarity index 66% rename from core/java/com/android/internal/gadget/IGadgetService.aidl rename to core/java/com/android/internal/appwidget/IAppWidgetHost.aidl index 6f9af045314495f36d55aec350e42b778376abec..2ed4773f4fd0b594c58eeb56ac2759676b20df2f 100644 --- a/core/java/com/android/internal/gadget/IGadgetService.aidl +++ b/core/java/com/android/internal/appwidget/IAppWidgetHost.aidl @@ -14,16 +14,15 @@ * limitations under the License. */ -package com.android.internal.gadget; +package com.android.internal.appwidget; import android.content.ComponentName; -import android.gadget.GadgetInfo; +import android.appwidget.AppWidgetProviderInfo; +import android.widget.RemoteViews; /** {@hide} */ -interface IGadgetService { - int allocateGadgetId(String hostPackage); - void deleteGadgetId(int gadgetId); - void bindGadgetId(int gadgetId, in ComponentName provider); - GadgetInfo getGadgetInfo(int gadgetId); - List getInstalledProviders(); +oneway interface IAppWidgetHost { + void updateAppWidget(int appWidgetId, in RemoteViews views); + void providerChanged(int appWidgetId, in AppWidgetProviderInfo info); } + diff --git a/core/java/com/android/internal/appwidget/IAppWidgetService.aidl b/core/java/com/android/internal/appwidget/IAppWidgetService.aidl new file mode 100644 index 0000000000000000000000000000000000000000..496aa1a2f3e74bd4e67a5689d28147218c74437b --- /dev/null +++ b/core/java/com/android/internal/appwidget/IAppWidgetService.aidl @@ -0,0 +1,50 @@ +/* + * 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. + */ + +package com.android.internal.appwidget; + +import android.content.ComponentName; +import android.appwidget.AppWidgetProviderInfo; +import com.android.internal.appwidget.IAppWidgetHost; +import android.widget.RemoteViews; + +/** {@hide} */ +interface IAppWidgetService { + + // + // for AppWidgetHost + // + int[] startListening(IAppWidgetHost host, String packageName, int hostId, + out List updatedViews); + void stopListening(int hostId); + int allocateAppWidgetId(String packageName, int hostId); + void deleteAppWidgetId(int appWidgetId); + void deleteHost(int hostId); + void deleteAllHosts(); + RemoteViews getAppWidgetViews(int appWidgetId); + + // + // for AppWidgetManager + // + void updateAppWidgetIds(in int[] appWidgetIds, in RemoteViews views); + void updateAppWidgetProvider(in ComponentName provider, in RemoteViews views); + List getInstalledProviders(); + AppWidgetProviderInfo getAppWidgetInfo(int appWidgetId); + void bindAppWidgetId(int appWidgetId, in ComponentName provider); + int[] getAppWidgetIds(in ComponentName provider); + +} + diff --git a/core/java/com/android/internal/gadget/package.html b/core/java/com/android/internal/appwidget/package.html similarity index 100% rename from core/java/com/android/internal/gadget/package.html rename to core/java/com/android/internal/appwidget/package.html diff --git a/core/java/com/android/internal/logging/AndroidConfig.java b/core/java/com/android/internal/logging/AndroidConfig.java index d8be889998b65a9d02be3b42e6d3ba93ece3184e..f8002c68cd4cfbaa2dc9f15700ffe1cc6d3ab198 100644 --- a/core/java/com/android/internal/logging/AndroidConfig.java +++ b/core/java/com/android/internal/logging/AndroidConfig.java @@ -34,11 +34,14 @@ public class AndroidConfig { super(); try { - Logger.global.addHandler(new AndroidHandler()); - Logger.global.setLevel(Level.ALL); + Logger rootLogger = Logger.getLogger(""); + rootLogger.addHandler(new AndroidHandler()); + rootLogger.setLevel(Level.INFO); + + // Turn down logging in Apache libraries. + Logger.getLogger("org.apache").setLevel(Level.WARNING); } catch (Exception ex) { ex.printStackTrace(); } - } - + } } diff --git a/core/java/com/android/internal/logging/AndroidHandler.java b/core/java/com/android/internal/logging/AndroidHandler.java index a6a4c6461d5b08c4764cfb0b816216f901484123..d9fcf60756eac25bf02ec7585fa9ce0e97439ad8 100644 --- a/core/java/com/android/internal/logging/AndroidHandler.java +++ b/core/java/com/android/internal/logging/AndroidHandler.java @@ -18,14 +18,14 @@ package com.android.internal.logging; import android.util.Log; -import java.util.logging.Formatter; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.SimpleFormatter; +import java.util.logging.*; +import java.util.Date; +import java.text.MessageFormat; +import java.io.PrintWriter; +import java.io.StringWriter; /** - * Implements a {@link java.util.Logger} handler that writes to the Android log. The + * Implements a {@link java.util.logging.Logger} handler that writes to the Android log. The * implementation is rather straightforward. The name of the logger serves as * the log tag. Only the log levels need to be converted appropriately. For * this purpose, the following mapping is being used: @@ -81,8 +81,24 @@ public class AndroidHandler extends Handler { /** * Holds the formatter for all Android log handlers. */ - private static final Formatter THE_FORMATTER = new SimpleFormatter(); - + private static final Formatter THE_FORMATTER = new Formatter() { + @Override + public String format(LogRecord r) { + Throwable thrown = r.getThrown(); + if (thrown != null) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + sw.write(r.getMessage()); + sw.write("\n"); + thrown.printStackTrace(pw); + pw.flush(); + return sw.toString(); + } else { + return r.getMessage(); + } + } + }; + /** * Constructs a new instance of the Android log handler. */ @@ -106,27 +122,40 @@ public class AndroidHandler extends Handler { int level = getAndroidLevel(record.getLevel()); String tag = record.getLoggerName(); + if (tag == null) { + // Anonymous logger. + tag = "null"; + } else { + // Tags must be <= 23 characters. + int length = tag.length(); + if (length > 23) { + // Most loggers use the full class name. Try dropping the + // package. + int lastPeriod = tag.lastIndexOf("."); + if (length - lastPeriod - 1 <= 23) { + tag = tag.substring(lastPeriod + 1); + } else { + // Use last 23 chars. + tag = tag.substring(tag.length() - 23); + } + } + } + if (!Log.isLoggable(tag, level)) { return; } - - String msg; - try { - msg = getFormatter().format(record); - } catch (RuntimeException e) { - Log.e("AndroidHandler", "Error formatting log record", e); - msg = record.getMessage(); - } - Log.println(level, tag, msg); + + String message = getFormatter().format(record); + Log.println(level, tag, message); } catch (RuntimeException e) { - Log.e("AndroidHandler", "Error publishing log record", e); + Log.e("AndroidHandler", "Error logging message.", e); } } /** - * Converts a {@link java.util.Logger} logging level into an Android one. + * Converts a {@link java.util.logging.Logger} logging level into an Android one. * - * @param level The {@link java.util.Logger} logging level. + * @param level The {@link java.util.logging.Logger} logging level. * * @return The resulting Android logging level. */ diff --git a/core/java/com/android/internal/net/DbSSLSessionCache.java b/core/java/com/android/internal/net/DbSSLSessionCache.java new file mode 100644 index 0000000000000000000000000000000000000000..842d40b0073c8adbe780d11153e6ec79fb091909 --- /dev/null +++ b/core/java/com/android/internal/net/DbSSLSessionCache.java @@ -0,0 +1,289 @@ +// Copyright 2009 The Android Open Source Project + +package com.android.internal.net; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.SQLException; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import org.apache.commons.codec.binary.Base64; +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; + +import java.util.HashMap; +import java.util.Map; + +import javax.net.ssl.SSLSession; + +/** + * Hook into harmony SSL cache to persist the SSL sessions. + * + * Current implementation is suitable for saving a small number of hosts - + * like google services. It can be extended with expiration and more features + * to support more hosts. + * + * {@hide} + */ +public class DbSSLSessionCache implements SSLClientSessionCache { + private static final String TAG = "DbSSLSessionCache"; + + /** + * Table where sessions are stored. + */ + public static final String SSL_CACHE_TABLE = "ssl_sessions"; + + private static final String SSL_CACHE_ID = "_id"; + + /** + * Key is host:port - port is not optional. + */ + private static final String SSL_CACHE_HOSTPORT = "hostport"; + + /** + * Base64-encoded DER value of the session. + */ + private static final String SSL_CACHE_SESSION = "session"; + + /** + * Time when the record was added - should be close to the time + * of the initial session negotiation. + */ + private static final String SSL_CACHE_TIME_SEC = "time_sec"; + + public static final String DATABASE_NAME = "ssl_sessions.db"; + + public static final int DATABASE_VERSION = 2; + + /** public for testing + */ + public static final int SSL_CACHE_ID_COL = 0; + public static final int SSL_CACHE_HOSTPORT_COL = 1; + public static final int SSL_CACHE_SESSION_COL = 2; + public static final int SSL_CACHE_TIME_SEC_COL = 3; + + public static final int MAX_CACHE_SIZE = 256; + + private final Map mExternalCache = + new HashMap(); + + + private DatabaseHelper mDatabaseHelper; + + private boolean mNeedsCacheLoad = true; + + public static final String[] PROJECTION = new String[] { + SSL_CACHE_ID, + SSL_CACHE_HOSTPORT, + SSL_CACHE_SESSION, + SSL_CACHE_TIME_SEC + }; + + private static final Map sInstances = + new HashMap(); + + /** + * Returns a singleton instance of the DbSSLSessionCache that should be used for this + * context's package. + * + * @param context The context that should be used for getting/creating the singleton instance. + * @return The singleton instance for the context's package. + */ + public static synchronized DbSSLSessionCache getInstanceForPackage(Context context) { + String packageName = context.getPackageName(); + if (sInstances.containsKey(packageName)) { + return sInstances.get(packageName); + } + DbSSLSessionCache cache = new DbSSLSessionCache(context); + sInstances.put(packageName, cache); + return cache; + } + + /** + * Create a SslSessionCache instance, using the specified context to + * initialize the database. + * + * This constructor will use the default database - created for the application + * context. + * + * @param activityContext + */ + private DbSSLSessionCache(Context activityContext) { + Context appContext = activityContext.getApplicationContext(); + mDatabaseHelper = new DatabaseHelper(appContext); + } + + /** + * Create a SslSessionCache that uses a specific database. + * + * + * @param database + */ + public DbSSLSessionCache(DatabaseHelper database) { + this.mDatabaseHelper = database; + } + + public void putSessionData(SSLSession session, byte[] der) { + if (mDatabaseHelper == null) { + return; + } + synchronized (this.getClass()) { + SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); + if (mExternalCache.size() == MAX_CACHE_SIZE) { + // remove oldest. + // TODO: check if the new one is in cached already ( i.e. update ). + Cursor byTime = mDatabaseHelper.getReadableDatabase().query(SSL_CACHE_TABLE, + PROJECTION, null, null, null, null, SSL_CACHE_TIME_SEC); + if (byTime.moveToFirst()) { + // TODO: can I do byTime.deleteRow() ? + String hostPort = byTime.getString(SSL_CACHE_HOSTPORT_COL); + db.delete(SSL_CACHE_TABLE, + SSL_CACHE_HOSTPORT + "= ?" , new String[] { hostPort }); + mExternalCache.remove(hostPort); + } else { + Log.w(TAG, "No rows found"); + // something is wrong, clear it + clear(); + } + } + // Serialize native session to standard DER encoding + long t0 = System.currentTimeMillis(); + + String b64 = new String(Base64.encodeBase64(der)); + String key = session.getPeerHost() + ":" + session.getPeerPort(); + + ContentValues values = new ContentValues(); + values.put(SSL_CACHE_HOSTPORT, key); + values.put(SSL_CACHE_SESSION, b64); + values.put(SSL_CACHE_TIME_SEC, System.currentTimeMillis() / 1000); + + mExternalCache.put(key, der); + + try { + db.insert(SSL_CACHE_TABLE, null /*nullColumnHack */ , values); + } catch(SQLException ex) { + // Ignore - nothing we can do to recover, and caller shouldn't + // be affected. + Log.w(TAG, "Ignoring SQL exception when caching session", ex); + } + if (Log.isLoggable(TAG, Log.DEBUG)) { + long t1 = System.currentTimeMillis(); + Log.d(TAG, "New SSL session " + session.getPeerHost() + + " DER len: " + der.length + " " + (t1 - t0)); + } + } + + } + + public byte[] getSessionData(String host, int port) { + // Current (simple) implementation does a single lookup to DB, then saves + // all entries to the cache. + + // This works for google services - i.e. small number of certs. + // If we extend this to all processes - we should hold a separate cache + // or do lookups to DB each time. + if (mDatabaseHelper == null) { + return null; + } + synchronized(this.getClass()) { + if (mNeedsCacheLoad) { + // Don't try to load again, if something is wrong on the first + // request it'll likely be wrong each time. + mNeedsCacheLoad = false; + long t0 = System.currentTimeMillis(); + + Cursor cur = null; + try { + cur = mDatabaseHelper.getReadableDatabase().query(SSL_CACHE_TABLE, + PROJECTION, null, null, null, null, null); + if (cur.moveToFirst()) { + do { + String hostPort = cur.getString(SSL_CACHE_HOSTPORT_COL); + String value = cur.getString(SSL_CACHE_SESSION_COL); + + if (hostPort == null || value == null) { + continue; + } + // TODO: blob support ? + byte[] der = Base64.decodeBase64(value.getBytes()); + mExternalCache.put(hostPort, der); + } while (cur.moveToNext()); + + } + } catch (SQLException ex) { + Log.d(TAG, "Error loading SSL cached entries ", ex); + } finally { + if (cur != null) { + cur.close(); + } + if (Log.isLoggable(TAG, Log.DEBUG)) { + long t1 = System.currentTimeMillis(); + Log.d(TAG, "LOADED CACHED SSL " + (t1 - t0) + " ms"); + } + } + } + + String key = host + ":" + port; + + return mExternalCache.get(key); + } + } + + /** + * Reset the database and internal state. + * Used for testing or to free space. + */ + public void clear() { + synchronized(this) { + try { + mExternalCache.clear(); + mNeedsCacheLoad = true; + mDatabaseHelper.getWritableDatabase().delete(SSL_CACHE_TABLE, + null, null); + } catch (SQLException ex) { + Log.d(TAG, "Error removing SSL cached entries ", ex); + // ignore - nothing we can do about it + } + } + } + + public byte[] getSessionData(byte[] id) { + // We support client side only - the cache will do nothing for + // server-side sessions. + return null; + } + + /** Visible for testing. + */ + public static class DatabaseHelper extends SQLiteOpenHelper { + + public DatabaseHelper(Context context) { + super(context, DATABASE_NAME, null /* factory */, DATABASE_VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + db.execSQL("CREATE TABLE " + SSL_CACHE_TABLE + " (" + + SSL_CACHE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + SSL_CACHE_HOSTPORT + " TEXT UNIQUE ON CONFLICT REPLACE," + + SSL_CACHE_SESSION + " TEXT," + + SSL_CACHE_TIME_SEC + " INTEGER" + + ");"); + + // No index - we load on startup, index would slow down inserts. + // If we want to scale this to lots of rows - we could use + // index, but then we'll hit DB a bit too often ( including + // negative hits ) + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + db.execSQL("DROP TABLE IF EXISTS " + SSL_CACHE_TABLE ); + onCreate(db); + } + + } + +} diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java index 8912960b0a479888cd96f53bae179f09d93141a1..7eea8b73da0d4ad668ede1c80906dc5acac3b12a 100644 --- a/core/java/com/android/internal/os/BatteryStatsImpl.java +++ b/core/java/com/android/internal/os/BatteryStatsImpl.java @@ -17,18 +17,19 @@ package com.android.internal.os; import android.os.BatteryStats; +import android.os.NetStat; import android.os.Parcel; import android.os.ParcelFormatException; import android.os.Parcelable; import android.os.SystemClock; import android.util.Log; +import android.util.Printer; import android.util.SparseArray; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -38,13 +39,15 @@ import java.util.Map; * battery life. All times are represented in microseconds except where indicated * otherwise. */ -public final class BatteryStatsImpl extends BatteryStats implements Parcelable { +public final class BatteryStatsImpl extends BatteryStats { + private static final String TAG = "BatteryStatsImpl"; + private static final boolean DEBUG = false; // In-memory Parcel magic number, used to detect attempts to unmarshall bad data private static final int MAGIC = 0xBA757475; // 'BATSTATS' // Current on-disk Parcel version - private static final int VERSION = 13; + private static final int VERSION = 25; private final File mFile; private final File mBackupFile; @@ -62,8 +65,13 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { final ArrayList mPartialTimers = new ArrayList(); final ArrayList mFullTimers = new ArrayList(); final ArrayList mWindowTimers = new ArrayList(); - final ArrayList mSensorTimers = new ArrayList(); + final SparseArray> mSensorTimers + = new SparseArray>(); + // These are the objects that will want to do something when the device + // is unplugged from power. + final ArrayList mUnpluggables = new ArrayList(); + int mStartCount; long mBatteryUptime; @@ -77,17 +85,27 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { long mRealtime; long mRealtimeStart; long mLastRealtime; - + + boolean mScreenOn; + Timer mScreenOnTimer; + + boolean mPhoneOn; + Timer mPhoneOnTimer; + /** * These provide time bases that discount the time the device is plugged * in to power. */ boolean mOnBattery; + boolean mOnBatteryInternal; long mTrackBatteryPastUptime; long mTrackBatteryUptimeStart; long mTrackBatteryPastRealtime; long mTrackBatteryRealtimeStart; - + + long mUnpluggedBatteryUptime; + long mUnpluggedBatteryRealtime; + long mLastWriteTime = 0; // Milliseconds // For debugging @@ -95,101 +113,162 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { mFile = mBackupFile = null; } + public static interface Unpluggable { + void unplug(long batteryUptime, long batteryRealtime); + void plug(long batteryUptime, long batteryRealtime); + } + /** * State for keeping track of timing information. */ - public static final class Timer extends BatteryStats.Timer { - ArrayList mTimerPool; + public static final class Timer extends BatteryStats.Timer implements Unpluggable { + final int mType; + final ArrayList mTimerPool; - int mType; int mNesting; int mCount; int mLoadedCount; int mLastCount; + int mUnpluggedCount; - // Times are in microseconds for better accuracy when dividing by the lock count + // Times are in microseconds for better accuracy when dividing by the + // lock count, and are in "battery realtime" units. - long mTotalTime; // Add mUnpluggedTotalTime to get true value - long mLoadedTotalTime; - long mLastTotalTime; - long mStartTime; - long mUpdateTime; + /** + * The total time we have accumulated since the start of the original + * boot, to the last time something interesting happened in the + * current run. + */ + long mTotalTime; + + /** + * The total time we loaded for the previous runs. Subtract this from + * mTotalTime to find the time for the current run of the system. + */ + long mLoadedTime; + + /** + * The run time of the last run of the system, as loaded from the + * saved data. + */ + long mLastTime; /** - * The value of mTotalTime when unplug() was last called, initially 0. + * The value of mTotalTime when unplug() was last called. Subtract + * this from mTotalTime to find the time since the last unplug from + * power. */ - long mTotalTimeAtLastUnplug; + long mUnpluggedTime; - /** Constructor used for unmarshalling only. */ - Timer() {} + /** + * The last time at which we updated the timer. If mNesting is > 0, + * subtract this from the current battery time to find the amount of + * time we have been running since we last computed an update. + */ + long mUpdateTime; + + /** + * The total time at which the timer was acquired, to determine if + * was actually held for an interesting duration. + */ + long mAcquireTime; + + Timer(int type, ArrayList timerPool, + ArrayList unpluggables, Parcel in) { + mType = type; + mTimerPool = timerPool; + mCount = in.readInt(); + mLoadedCount = in.readInt(); + mLastCount = in.readInt(); + mUnpluggedCount = in.readInt(); + mTotalTime = in.readLong(); + mLoadedTime = in.readLong(); + mLastTime = in.readLong(); + mUpdateTime = in.readLong(); + mUnpluggedTime = in.readLong(); + unpluggables.add(this); + } - Timer(int type, ArrayList timerPool) { + Timer(int type, ArrayList timerPool, + ArrayList unpluggables) { mType = type; mTimerPool = timerPool; + unpluggables.add(this); } - public void writeToParcel(Parcel out) { - out.writeInt(mType); - out.writeInt(mNesting); + public void writeToParcel(Parcel out, long batteryRealtime) { out.writeInt(mCount); out.writeInt(mLoadedCount); out.writeInt(mLastCount); - out.writeLong(mTotalTime); - out.writeLong(mLoadedTotalTime); - out.writeLong(mLastTotalTime); - out.writeLong(mStartTime); + out.writeInt(mUnpluggedCount); + out.writeLong(computeRunTimeLocked(batteryRealtime)); + out.writeLong(mLoadedTime); + out.writeLong(mLastTime); out.writeLong(mUpdateTime); - out.writeLong(mTotalTimeAtLastUnplug); + out.writeLong(mUnpluggedTime); } - public void readFromParcel(Parcel in) { - mType = in.readInt(); - mNesting = in.readInt(); - mCount = in.readInt(); - mLoadedCount = in.readInt(); - mLastCount = in.readInt(); - mTotalTime = in.readLong(); - mLoadedTotalTime = in.readLong(); - mLastTotalTime = in.readLong(); - mStartTime = in.readLong(); - mUpdateTime = in.readLong(); - mTotalTimeAtLastUnplug = in.readLong(); - } - - private void unplug() { - mTotalTimeAtLastUnplug += mTotalTime; - mTotalTime = 0; + public void unplug(long batteryUptime, long batteryRealtime) { + if (DEBUG && mType < 0) { + Log.v(TAG, "unplug #" + mType + ": realtime=" + batteryRealtime + + " old mUnpluggedTime=" + mUnpluggedTime + + " old mUnpluggedCount=" + mUnpluggedCount); + } + mUnpluggedTime = computeRunTimeLocked(batteryRealtime); + mUnpluggedCount = mCount; + if (DEBUG && mType < 0) { + Log.v(TAG, "unplug #" + mType + + ": new mUnpluggedTime=" + mUnpluggedTime + + " new mUnpluggedCount=" + mUnpluggedCount); + } } + public void plug(long batteryUptime, long batteryRealtime) { + if (mNesting > 0) { + if (DEBUG && mType < 0) { + Log.v(TAG, "plug #" + mType + ": realtime=" + batteryRealtime + + " old mTotalTime=" + mTotalTime + + " old mUpdateTime=" + mUpdateTime); + } + mTotalTime = computeRunTimeLocked(batteryRealtime); + mUpdateTime = batteryRealtime; + if (DEBUG && mType < 0) { + Log.v(TAG, "plug #" + mType + + ": new mTotalTime=" + mTotalTime + + " old mUpdateTime=" + mUpdateTime); + } + } + } + /** * Writes a possibly null Timer to a Parcel. * * @param out the Parcel to be written to. * @param timer a Timer, or null. */ - public static void writeTimerToParcel(Parcel out, Timer timer) { + public static void writeTimerToParcel(Parcel out, Timer timer, + long batteryRealtime) { if (timer == null) { out.writeInt(0); // indicates null return; } out.writeInt(1); // indicates non-null - timer.writeToParcel(out); + timer.writeToParcel(out, batteryRealtime); } @Override - public long getTotalTime(long now, int which) { + public long getTotalTime(long batteryRealtime, int which) { long val; if (which == STATS_LAST) { - val = mLastTotalTime; + val = mLastTime; } else { - val = computeRunTimeLocked(now); - if (which != STATS_UNPLUGGED) { - val += mTotalTimeAtLastUnplug; - } - if ((which == STATS_CURRENT) || (which == STATS_UNPLUGGED)) { - val -= mLoadedTotalTime; + val = computeRunTimeLocked(batteryRealtime); + if (which == STATS_UNPLUGGED) { + val -= mUnpluggedTime; + } else if (which != STATS_TOTAL) { + val -= mLoadedTime; } } @@ -203,7 +282,9 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { val = mLastCount; } else { val = mCount; - if ((which == STATS_CURRENT) || (which == STATS_UNPLUGGED)) { + if (which == STATS_UNPLUGGED) { + val -= mUnpluggedCount; + } else if (which != STATS_TOTAL) { val -= mLoadedCount; } } @@ -211,16 +292,37 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { return val; } + public void logState() { + Log.i("foo", "mNesting=" + mNesting + " mCount=" + mCount + + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount + + " mUnpluggedCount=" + mUnpluggedCount); + Log.i("foo", "mTotalTime=" + mTotalTime + + " mLoadedTime=" + mLoadedTime); + Log.i("foo", "mLastTime=" + mLastTime + + " mUnpluggedTime=" + mUnpluggedTime); + Log.i("foo", "mUpdateTime=" + mUpdateTime + + " mAcquireTime=" + mAcquireTime); + } + void startRunningLocked(BatteryStatsImpl stats) { if (mNesting++ == 0) { - mStartTime = mUpdateTime = - stats.getBatteryUptimeLocked(SystemClock.elapsedRealtime() * 1000); - // Accumulate time to all other active counters with the current value of mCount - refreshTimersLocked(stats); - // Add this timer to the active pool - mTimerPool.add(this); + mUpdateTime = stats.getBatteryRealtimeLocked( + SystemClock.elapsedRealtime() * 1000); + if (mTimerPool != null) { + // Accumulate time to all currently active timers before adding + // this new one to the pool. + refreshTimersLocked(stats, mTimerPool); + // Add this timer to the active pool + mTimerPool.add(this); + } // Increment the count mCount++; + mAcquireTime = mTotalTime; + if (DEBUG && mType < 0) { + Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime + + " mTotalTime=" + mTotalTime + " mCount=" + mCount + + " mAcquireTime=" + mAcquireTime); + } } } @@ -230,83 +332,158 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { return; } if (--mNesting == 0) { - // Accumulate time to all active counters with the current value of mCount - refreshTimersLocked(stats); - // Remove this timer from the active pool - mTimerPool.remove(this); - // Decrement the count - mCount--; + if (mTimerPool != null) { + // Accumulate time to all active counters, scaled by the total + // active in the pool, before taking this one out of the pool. + refreshTimersLocked(stats, mTimerPool); + // Remove this timer from the active pool + mTimerPool.remove(this); + } else { + final long realtime = SystemClock.elapsedRealtime() * 1000; + final long batteryRealtime = stats.getBatteryRealtimeLocked(realtime); + mNesting = 1; + mTotalTime = computeRunTimeLocked(batteryRealtime); + mNesting = 0; + } + + if (DEBUG && mType < 0) { + Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime + + " mTotalTime=" + mTotalTime + " mCount=" + mCount + + " mAcquireTime=" + mAcquireTime); + } + + if (mTotalTime == mAcquireTime) { + // If there was no change in the time, then discard this + // count. A somewhat cheezy strategy, but hey. + mCount--; + } } } // Update the total time for all other running Timers with the same type as this Timer // due to a change in timer count - private void refreshTimersLocked(BatteryStatsImpl stats) { - for (Timer t : mTimerPool) { - t.updateTimeLocked(stats); - } - } - - /** - * Update totalTime and reset updateTime - * @param stats - */ - private void updateTimeLocked(BatteryStatsImpl stats) { - long realtime = SystemClock.elapsedRealtime() * 1000; - long heldTime = stats.getBatteryUptimeLocked(realtime) - mUpdateTime; - if (heldTime > 0) { - mTotalTime += (heldTime * 1000) / mCount; + private static void refreshTimersLocked(final BatteryStatsImpl stats, + final ArrayList pool) { + final long realtime = SystemClock.elapsedRealtime() * 1000; + final long batteryRealtime = stats.getBatteryRealtimeLocked(realtime); + final int N = pool.size(); + for (int i=N-1; i>= 0; i--) { + final Timer t = pool.get(i); + long heldTime = batteryRealtime - t.mUpdateTime; + if (heldTime > 0) { + t.mTotalTime += heldTime / N; + } + t.mUpdateTime = batteryRealtime; } - mUpdateTime = stats.getBatteryUptimeLocked(realtime); } - private long computeRunTimeLocked(long curBatteryUptime) { - return mTotalTime + - (mNesting > 0 ? ((curBatteryUptime * 1000) - mUpdateTime) / mCount : 0); + private long computeRunTimeLocked(long curBatteryRealtime) { + return mTotalTime + (mNesting > 0 + ? (curBatteryRealtime - mUpdateTime) + / (mTimerPool != null ? mTimerPool.size() : 1) + : 0); } - void writeSummaryFromParcelLocked(Parcel out, long curBatteryUptime) { - long runTime = computeRunTimeLocked(curBatteryUptime); + void writeSummaryFromParcelLocked(Parcel out, long batteryRealtime) { + long runTime = computeRunTimeLocked(batteryRealtime); // Divide by 1000 for backwards compatibility out.writeLong((runTime + 500) / 1000); - out.writeLong(((runTime - mLoadedTotalTime) + 500) / 1000); + out.writeLong(((runTime - mLoadedTime) + 500) / 1000); out.writeInt(mCount); out.writeInt(mCount - mLoadedCount); } void readSummaryFromParcelLocked(Parcel in) { // Multiply by 1000 for backwards compatibility - mTotalTime = mLoadedTotalTime = in.readLong() * 1000; - mLastTotalTime = in.readLong(); + mTotalTime = mLoadedTime = in.readLong() * 1000; + mLastTime = in.readLong() * 1000; + mUnpluggedTime = mTotalTime; mCount = mLoadedCount = in.readInt(); mLastCount = in.readInt(); + mUnpluggedCount = mCount; mNesting = 0; } } - public void unplugTimers() { - ArrayList timers; - - timers = mPartialTimers; - for (int i = timers.size() - 1; i >= 0; i--) { - timers.get(i).unplug(); + public void doUnplug(long batteryUptime, long batteryRealtime) { + for (int iu = mUidStats.size() - 1; iu >= 0; iu--) { + Uid u = mUidStats.valueAt(iu); + u.mStartedTcpBytesReceived = NetStat.getUidRxBytes(u.mUid); + u.mStartedTcpBytesSent = NetStat.getUidTxBytes(u.mUid); + u.mTcpBytesReceivedAtLastUnplug = u.mCurrentTcpBytesReceived; + u.mTcpBytesSentAtLastUnplug = u.mCurrentTcpBytesSent; } - timers = mFullTimers; - for (int i = timers.size() - 1; i >= 0; i--) { - timers.get(i).unplug(); + for (int i = mUnpluggables.size() - 1; i >= 0; i--) { + mUnpluggables.get(i).unplug(batteryUptime, batteryRealtime); } - timers = mWindowTimers; - for (int i = timers.size() - 1; i >= 0; i--) { - timers.get(i).unplug(); + } + + public void doPlug(long batteryUptime, long batteryRealtime) { + for (int iu = mUidStats.size() - 1; iu >= 0; iu--) { + Uid u = mUidStats.valueAt(iu); + if (u.mStartedTcpBytesReceived >= 0) { + u.mCurrentTcpBytesReceived = u.computeCurrentTcpBytesReceived(); + u.mStartedTcpBytesReceived = -1; + } + if (u.mStartedTcpBytesSent >= 0) { + u.mCurrentTcpBytesSent = u.computeCurrentTcpBytesSent(); + u.mStartedTcpBytesSent = -1; + } } - timers = mSensorTimers; - for (int i = timers.size() - 1; i >= 0; i--) { - timers.get(i).unplug(); + for (int i = mUnpluggables.size() - 1; i >= 0; i--) { + mUnpluggables.get(i).plug(batteryUptime, batteryRealtime); } } - @Override - public SparseArray getUidStats() { + public void noteStartGps(int uid) { + mUidStats.get(uid).noteStartGps(); + } + + public void noteStopGps(int uid) { + mUidStats.get(uid).noteStopGps(); + } + + public void noteScreenOnLocked() { + if (!mScreenOn) { + mScreenOn = true; + mScreenOnTimer.startRunningLocked(this); + } + } + + public void noteScreenOffLocked() { + if (mScreenOn) { + mScreenOn = false; + mScreenOnTimer.stopRunningLocked(this); + } + } + + public void notePhoneOnLocked() { + if (!mPhoneOn) { + mPhoneOn = true; + mPhoneOnTimer.startRunningLocked(this); + } + } + + public void notePhoneOffLocked() { + if (mPhoneOn) { + mPhoneOn = false; + mPhoneOnTimer.stopRunningLocked(this); + } + } + + @Override public long getScreenOnTime(long batteryRealtime, int which) { + return mScreenOnTimer.getTotalTime(batteryRealtime, which); + } + + @Override public long getPhoneOnTime(long batteryRealtime, int which) { + return mPhoneOnTimer.getTotalTime(batteryRealtime, which); + } + + @Override public boolean getIsOnBattery() { + return mOnBattery; + } + + @Override public SparseArray getUidStats() { return mUidStats; } @@ -314,7 +491,20 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { * The statistics associated with a particular uid. */ public final class Uid extends BatteryStats.Uid { - + + final int mUid; + long mLoadedTcpBytesReceived; + long mLoadedTcpBytesSent; + long mCurrentTcpBytesReceived; + long mCurrentTcpBytesSent; + long mTcpBytesReceivedAtLastUnplug; + long mTcpBytesSentAtLastUnplug; + + // These are not saved/restored when parcelling, since we want + // to return from the parcel with a snapshot of the state. + long mStartedTcpBytesReceived = -1; + long mStartedTcpBytesSent = -1; + /** * The statistics we have collected for this uid's wake locks. */ @@ -334,6 +524,10 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { * The statistics we have collected for this uid's processes. */ final HashMap mPackageStats = new HashMap(); + + public Uid(int uid) { + mUid = uid; + } @Override public Map getWakelockStats() { @@ -354,20 +548,62 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { public Map getPackageStats() { return mPackageStats; } - - void writeToParcelLocked(Parcel out) { + + public int getUid() { + return mUid; + } + + public long getTcpBytesReceived(int which) { + if (which == STATS_LAST) { + return mLoadedTcpBytesReceived; + } else { + long current = computeCurrentTcpBytesReceived(); + if (which == STATS_UNPLUGGED) { + current -= mTcpBytesReceivedAtLastUnplug; + } else if (which == STATS_TOTAL) { + current += mLoadedTcpBytesReceived; + } + return current; + } + } + + public long computeCurrentTcpBytesReceived() { + return mCurrentTcpBytesReceived + (mStartedTcpBytesReceived >= 0 + ? (NetStat.getUidRxBytes(mUid) - mStartedTcpBytesReceived) : 0); + } + + public long getTcpBytesSent(int which) { + if (which == STATS_LAST) { + return mLoadedTcpBytesSent; + } else { + long current = computeCurrentTcpBytesSent(); + if (which == STATS_UNPLUGGED) { + current -= mTcpBytesSentAtLastUnplug; + } else if (which == STATS_TOTAL) { + current += mLoadedTcpBytesSent; + } + return current; + } + } + + public long computeCurrentTcpBytesSent() { + return mCurrentTcpBytesSent + (mStartedTcpBytesSent >= 0 + ? (NetStat.getUidTxBytes(mUid) - mStartedTcpBytesSent) : 0); + } + + void writeToParcelLocked(Parcel out, long batteryRealtime) { out.writeInt(mWakelockStats.size()); for (Map.Entry wakelockEntry : mWakelockStats.entrySet()) { out.writeString(wakelockEntry.getKey()); Uid.Wakelock wakelock = wakelockEntry.getValue(); - wakelock.writeToParcelLocked(out); + wakelock.writeToParcelLocked(out, batteryRealtime); } out.writeInt(mSensorStats.size()); for (Map.Entry sensorEntry : mSensorStats.entrySet()) { out.writeInt(sensorEntry.getKey()); Uid.Sensor sensor = sensorEntry.getValue(); - sensor.writeToParcelLocked(out); + sensor.writeToParcelLocked(out, batteryRealtime); } out.writeInt(mProcessStats.size()); @@ -383,15 +619,22 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { Uid.Pkg pkg = pkgEntry.getValue(); pkg.writeToParcelLocked(out); } + + out.writeLong(mLoadedTcpBytesReceived); + out.writeLong(mLoadedTcpBytesSent); + out.writeLong(computeCurrentTcpBytesReceived()); + out.writeLong(computeCurrentTcpBytesSent()); + out.writeLong(mTcpBytesReceivedAtLastUnplug); + out.writeLong(mTcpBytesSentAtLastUnplug); } - void readFromParcelLocked(Parcel in) { + void readFromParcelLocked(ArrayList unpluggables, Parcel in) { int numWakelocks = in.readInt(); mWakelockStats.clear(); for (int j = 0; j < numWakelocks; j++) { String wakelockName = in.readString(); Uid.Wakelock wakelock = new Wakelock(); - wakelock.readFromParcelLocked(in); + wakelock.readFromParcelLocked(unpluggables, in); mWakelockStats.put(wakelockName, wakelock); } @@ -399,8 +642,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { mSensorStats.clear(); for (int k = 0; k < numSensors; k++) { int sensorNumber = in.readInt(); - Uid.Sensor sensor = new Sensor(); - sensor.readFromParcelLocked(in); + Uid.Sensor sensor = new Sensor(sensorNumber); + sensor.readFromParcelLocked(mUnpluggables, in); mSensorStats.put(sensorNumber, sensor); } @@ -421,6 +664,13 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { pkg.readFromParcelLocked(in); mPackageStats.put(packageName, pkg); } + + mLoadedTcpBytesReceived = in.readLong(); + mLoadedTcpBytesSent = in.readLong(); + mCurrentTcpBytesReceived = in.readLong(); + mCurrentTcpBytesSent = in.readLong(); + mTcpBytesReceivedAtLastUnplug = in.readLong(); + mTcpBytesSentAtLastUnplug = in.readLong(); } /** @@ -430,17 +680,17 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { /** * How long (in ms) this uid has been keeping the device partially awake. */ - Timer wakeTimePartial; + Timer mTimerPartial; /** * How long (in ms) this uid has been keeping the device fully awake. */ - Timer wakeTimeFull; + Timer mTimerFull; /** * How long (in ms) this uid has had a window keeping the device awake. */ - Timer wakeTimeWindow; + Timer mTimerWindow; /** * Reads a possibly null Timer from a Parcel. The timer is associated with the @@ -449,93 +699,85 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { * @param in the Parcel to be read from. * return a new Timer, or null. */ - private Timer readTimerFromParcel(Parcel in) { + private Timer readTimerFromParcel(int type, ArrayList pool, + ArrayList unpluggables, Parcel in) { if (in.readInt() == 0) { return null; } - Timer timer = new Timer(); - timer.readFromParcel(in); - // Set the timer pool for the timer according to its type - switch (timer.mType) { - case WAKE_TYPE_PARTIAL: - timer.mTimerPool = mPartialTimers; - break; - case WAKE_TYPE_FULL: - timer.mTimerPool = mFullTimers; - break; - case WAKE_TYPE_WINDOW: - timer.mTimerPool = mWindowTimers; - break; - } - // If the timer is active, add it to the pool - if (timer.mNesting > 0) { - timer.mTimerPool.add(timer); - } - return timer; + return new Timer(type, pool, unpluggables, in); } - void readFromParcelLocked(Parcel in) { - wakeTimePartial = readTimerFromParcel(in); - wakeTimeFull = readTimerFromParcel(in); - wakeTimeWindow = readTimerFromParcel(in); + void readFromParcelLocked(ArrayList unpluggables, Parcel in) { + mTimerPartial = readTimerFromParcel(WAKE_TYPE_PARTIAL, + mPartialTimers, unpluggables, in); + mTimerFull = readTimerFromParcel(WAKE_TYPE_FULL, + mFullTimers, unpluggables, in); + mTimerWindow = readTimerFromParcel(WAKE_TYPE_WINDOW, + mWindowTimers, unpluggables, in); } - void writeToParcelLocked(Parcel out) { - Timer.writeTimerToParcel(out, wakeTimePartial); - Timer.writeTimerToParcel(out, wakeTimeFull); - Timer.writeTimerToParcel(out, wakeTimeWindow); + void writeToParcelLocked(Parcel out, long batteryRealtime) { + Timer.writeTimerToParcel(out, mTimerPartial, batteryRealtime); + Timer.writeTimerToParcel(out, mTimerFull, batteryRealtime); + Timer.writeTimerToParcel(out, mTimerWindow, batteryRealtime); } @Override public Timer getWakeTime(int type) { switch (type) { - case WAKE_TYPE_FULL: return wakeTimeFull; - case WAKE_TYPE_PARTIAL: return wakeTimePartial; - case WAKE_TYPE_WINDOW: return wakeTimeWindow; + case WAKE_TYPE_FULL: return mTimerFull; + case WAKE_TYPE_PARTIAL: return mTimerPartial; + case WAKE_TYPE_WINDOW: return mTimerWindow; default: throw new IllegalArgumentException("type = " + type); } } } public final class Sensor extends BatteryStats.Uid.Sensor { - Timer sensorTime; + final int mHandle; + Timer mTimer; + + public Sensor(int handle) { + mHandle = handle; + } - private Timer readTimerFromParcel(Parcel in) { + private Timer readTimerFromParcel(ArrayList unpluggables, + Parcel in) { if (in.readInt() == 0) { return null; } - Timer timer = new Timer(); - timer.readFromParcel(in); - // Set the timer pool for the timer - timer.mTimerPool = mSensorTimers; - - // If the timer is active, add it to the pool - if (timer.mNesting > 0) { - timer.mTimerPool.add(timer); + ArrayList pool = mSensorTimers.get(mHandle); + if (pool == null) { + pool = new ArrayList(); + mSensorTimers.put(mHandle, pool); } - return timer; + return new Timer(0, pool, unpluggables, in); } - void readFromParcelLocked(Parcel in) { - sensorTime = readTimerFromParcel(in); + void readFromParcelLocked(ArrayList unpluggables, Parcel in) { + mTimer = readTimerFromParcel(unpluggables, in); } - void writeToParcelLocked(Parcel out) { - Timer.writeTimerToParcel(out, sensorTime); + void writeToParcelLocked(Parcel out, long batteryRealtime) { + Timer.writeTimerToParcel(out, mTimer, batteryRealtime); } @Override public Timer getSensorTime() { - return sensorTime; + return mTimer; + } + + public int getHandle() { + return mHandle; } } /** * The statistics associated with a particular process. */ - public final class Proc extends BatteryStats.Uid.Proc { + public final class Proc extends BatteryStats.Uid.Proc implements Unpluggable { /** * Total time (in 1/100 sec) spent executing in user code. */ @@ -581,6 +823,34 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { */ int mLastStarts; + /** + * The amount of user time when last unplugged. + */ + long mUnpluggedUserTime; + + /** + * The amount of system time when last unplugged. + */ + long mUnpluggedSystemTime; + + /** + * The number of times the process has started before unplugged. + */ + int mUnpluggedStarts; + + Proc() { + mUnpluggables.add(this); + } + + public void unplug(long batteryUptime, long batteryRealtime) { + mUnpluggedUserTime = mUserTime; + mUnpluggedSystemTime = mSystemTime; + mUnpluggedStarts = mStarts; + } + + public void plug(long batteryUptime, long batteryRealtime) { + } + void writeToParcelLocked(Parcel out) { out.writeLong(mUserTime); out.writeLong(mSystemTime); @@ -591,6 +861,9 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { out.writeLong(mLastUserTime); out.writeLong(mLastSystemTime); out.writeInt(mLastStarts); + out.writeLong(mUnpluggedUserTime); + out.writeLong(mUnpluggedSystemTime); + out.writeInt(mUnpluggedStarts); } void readFromParcelLocked(Parcel in) { @@ -603,6 +876,9 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { mLastUserTime = in.readLong(); mLastSystemTime = in.readLong(); mLastStarts = in.readInt(); + mUnpluggedUserTime = in.readLong(); + mUnpluggedSystemTime = in.readLong(); + mUnpluggedStarts = in.readInt(); } public BatteryStatsImpl getBatteryStats() { @@ -627,6 +903,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { val = mUserTime; if (which == STATS_CURRENT) { val -= mLoadedUserTime; + } else if (which == STATS_UNPLUGGED) { + val -= mUnpluggedUserTime; } } return val; @@ -641,6 +919,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { val = mSystemTime; if (which == STATS_CURRENT) { val -= mLoadedSystemTime; + } else if (which == STATS_UNPLUGGED) { + val -= mUnpluggedSystemTime; } } return val; @@ -655,6 +935,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { val = mStarts; if (which == STATS_CURRENT) { val -= mLoadedStarts; + } else if (which == STATS_UNPLUGGED) { + val -= mUnpluggedStarts; } } return val; @@ -664,7 +946,7 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { /** * The statistics associated with a particular package. */ - public final class Pkg extends BatteryStats.Uid.Pkg { + public final class Pkg extends BatteryStats.Uid.Pkg implements Unpluggable { /** * Number of times this package has done something that could wake up the * device from sleep. @@ -683,15 +965,33 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { */ int mLastWakeups; + /** + * Number of things that could wake up the device as of the + * last run. + */ + int mUnpluggedWakeups; + /** * The statics we have collected for this package's services. */ final HashMap mServiceStats = new HashMap(); + Pkg() { + mUnpluggables.add(this); + } + + public void unplug(long batteryUptime, long batteryRealtime) { + mUnpluggedWakeups = mWakeups; + } + + public void plug(long batteryUptime, long batteryRealtime) { + } + void readFromParcelLocked(Parcel in) { mWakeups = in.readInt(); mLoadedWakeups = in.readInt(); mLastWakeups = in.readInt(); + mUnpluggedWakeups = in.readInt(); int numServs = in.readInt(); mServiceStats.clear(); @@ -708,6 +1008,7 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { out.writeInt(mWakeups); out.writeInt(mLoadedWakeups); out.writeInt(mLastWakeups); + out.writeInt(mUnpluggedWakeups); out.writeInt(mServiceStats.size()); for (Map.Entry servEntry : mServiceStats.entrySet()) { @@ -732,6 +1033,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { val = mWakeups; if (which == STATS_CURRENT) { val -= mLoadedWakeups; + } else if (which == STATS_UNPLUGGED) { + val -= mUnpluggedWakeups; } } @@ -741,9 +1044,9 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { /** * The statistics associated with a particular service. */ - public final class Serv extends BatteryStats.Uid.Pkg.Serv { + public final class Serv extends BatteryStats.Uid.Pkg.Serv implements Unpluggable { /** - * Total time (ms) the service has been left started. + * Total time (ms in battery uptime) the service has been left started. */ long mStartTime; @@ -764,13 +1067,13 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { int mStarts; /** - * Total time (ms) the service has been left launched. + * Total time (ms in battery uptime) the service has been left launched. */ long mLaunchedTime; /** * If service has been launched and not yet exited, this is - * when it was launched. + * when it was launched (ms in battery uptime). */ long mLaunchedSince; @@ -785,7 +1088,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { int mLaunches; /** - * The amount of time spent started loaded from a previous save. + * The amount of time spent started loaded from a previous save + * (ms in battery uptime). */ long mLoadedStartTime; @@ -800,7 +1104,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { int mLoadedLaunches; /** - * The amount of time spent started as of the last run. + * The amount of time spent started as of the last run (ms + * in battery uptime). */ long mLastStartTime; @@ -814,6 +1119,35 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { */ int mLastLaunches; + /** + * The amount of time spent started when last unplugged (ms + * in battery uptime). + */ + long mUnpluggedStartTime; + + /** + * The number of starts when last unplugged. + */ + int mUnpluggedStarts; + + /** + * The number of launches when last unplugged. + */ + int mUnpluggedLaunches; + + Serv() { + mUnpluggables.add(this); + } + + public void unplug(long batteryUptime, long batteryRealtime) { + mUnpluggedStartTime = getStartTimeToNowLocked(batteryUptime); + mUnpluggedStarts = mStarts; + mUnpluggedLaunches = mLaunches; + } + + public void plug(long batteryUptime, long batteryRealtime) { + } + void readFromParcelLocked(Parcel in) { mStartTime = in.readLong(); mRunningSince = in.readLong(); @@ -829,6 +1163,9 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { mLastStartTime = in.readLong(); mLastStarts = in.readInt(); mLastLaunches = in.readInt(); + mUnpluggedStartTime = in.readLong(); + mUnpluggedStarts = in.readInt(); + mUnpluggedLaunches = in.readInt(); } void writeToParcelLocked(Parcel out) { @@ -846,6 +1183,9 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { out.writeLong(mLastStartTime); out.writeInt(mLastStarts); out.writeInt(mLastLaunches); + out.writeLong(mUnpluggedStartTime); + out.writeInt(mUnpluggedStarts); + out.writeInt(mUnpluggedLaunches); } long getLaunchTimeToNowLocked(long batteryUptime) { @@ -912,6 +1252,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { val = mLaunches; if (which == STATS_CURRENT) { val -= mLoadedLaunches; + } else if (which == STATS_UNPLUGGED) { + val -= mUnpluggedLaunches; } } @@ -927,6 +1269,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { val = getStartTimeToNowLocked(now); if (which == STATS_CURRENT) { val -= mLoadedStartTime; + } else if (which == STATS_UNPLUGGED) { + val -= mUnpluggedStartTime; } } @@ -942,6 +1286,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { val = mStarts; if (which == STATS_CURRENT) { val -= mLoadedStarts; + } else if (which == STATS_UNPLUGGED) { + val -= mUnpluggedStarts; } } @@ -1014,24 +1360,24 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { Timer t = null; switch (type) { case WAKE_TYPE_PARTIAL: - t = wl.wakeTimePartial; + t = wl.mTimerPartial; if (t == null) { - t = new Timer(WAKE_TYPE_PARTIAL, mPartialTimers); - wl.wakeTimePartial = t; + t = new Timer(WAKE_TYPE_PARTIAL, mPartialTimers, mUnpluggables); + wl.mTimerPartial = t; } return t; case WAKE_TYPE_FULL: - t = wl.wakeTimeFull; + t = wl.mTimerFull; if (t == null) { - t = new Timer(WAKE_TYPE_FULL, mFullTimers); - wl.wakeTimeFull = t; + t = new Timer(WAKE_TYPE_FULL, mFullTimers, mUnpluggables); + wl.mTimerFull = t; } return t; case WAKE_TYPE_WINDOW: - t = wl.wakeTimeWindow; + t = wl.mTimerWindow; if (t == null) { - t = new Timer(WAKE_TYPE_WINDOW, mWindowTimers); - wl.wakeTimeWindow = t; + t = new Timer(WAKE_TYPE_WINDOW, mWindowTimers, mUnpluggables); + wl.mTimerWindow = t; } return t; default: @@ -1040,20 +1386,25 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { } public Timer getSensorTimerLocked(int sensor, boolean create) { - Integer sId = Integer.valueOf(sensor); - Sensor se = mSensorStats.get(sId); + Sensor se = mSensorStats.get(sensor); if (se == null) { if (!create) { return null; } - se = new Sensor(); - mSensorStats.put(sId, se); + se = new Sensor(sensor); + mSensorStats.put(sensor, se); + } + Timer t = se.mTimer; + if (t != null) { + return t; } - Timer t = se.sensorTime; - if (t == null) { - t = new Timer(0, mSensorTimers); - se.sensorTime = t; + ArrayList timers = mSensorTimers.get(sensor); + if (timers == null) { + timers = new ArrayList(); + mSensorTimers.put(sensor, timers); } + t = new Timer(BatteryStats.SENSOR, timers, mUnpluggables); + se.mTimer = t; return t; } @@ -1085,6 +1436,20 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { t.stopRunningLocked(BatteryStatsImpl.this); } } + + public void noteStartGps() { + Timer t = getSensorTimerLocked(Sensor.GPS, true); + if (t != null) { + t.startRunningLocked(BatteryStatsImpl.this); + } + } + + public void noteStopGps() { + Timer t = getSensorTimerLocked(Sensor.GPS, false); + if (t != null) { + t.stopRunningLocked(BatteryStatsImpl.this); + } + } public BatteryStatsImpl getBatteryStats() { return BatteryStatsImpl.this; @@ -1095,11 +1460,15 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { mFile = new File(filename); mBackupFile = new File(filename + ".bak"); mStartCount++; - mOnBattery = true; + mScreenOnTimer = new Timer(-1, null, mUnpluggables); + mPhoneOnTimer = new Timer(-2, null, mUnpluggables); + mOnBattery = mOnBatteryInternal = false; mTrackBatteryPastUptime = 0; mTrackBatteryPastRealtime = 0; mUptimeStart = mTrackBatteryUptimeStart = SystemClock.uptimeMillis() * 1000; mRealtimeStart = mTrackBatteryRealtimeStart = SystemClock.elapsedRealtime() * 1000; + mUnpluggedBatteryUptime = getBatteryUptimeLocked(mUptimeStart); + mUnpluggedBatteryRealtime = getBatteryRealtimeLocked(mRealtimeStart); } public BatteryStatsImpl(Parcel p) { @@ -1119,18 +1488,22 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { public void setOnBattery(boolean onBattery) { synchronized(this) { if (mOnBattery != onBattery) { + mOnBattery = mOnBatteryInternal = onBattery; + long uptime = SystemClock.uptimeMillis() * 1000; long mSecRealtime = SystemClock.elapsedRealtime(); long realtime = mSecRealtime * 1000; if (onBattery) { mTrackBatteryUptimeStart = uptime; mTrackBatteryRealtimeStart = realtime; - unplugTimers(); + mUnpluggedBatteryUptime = getBatteryUptimeLocked(uptime); + mUnpluggedBatteryRealtime = getBatteryRealtimeLocked(realtime); + doUnplug(mUnpluggedBatteryUptime, mUnpluggedBatteryRealtime); } else { mTrackBatteryPastUptime += uptime - mTrackBatteryUptimeStart; mTrackBatteryPastRealtime += realtime - mTrackBatteryRealtimeStart; + doPlug(getBatteryUptimeLocked(uptime), getBatteryRealtimeLocked(realtime)); } - mOnBattery = onBattery; if ((mLastWriteTime + (60 * 1000)) < mSecRealtime) { if (mFile != null) { writeLocked(); @@ -1151,10 +1524,10 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { @Override public long computeUptime(long curTime, int which) { switch (which) { - case STATS_TOTAL: return mUptime + (curTime-mUptimeStart); - case STATS_LAST: return mLastUptime; - case STATS_CURRENT: return (curTime-mUptimeStart); - case STATS_UNPLUGGED: return (curTime-mTrackBatteryUptimeStart); + case STATS_TOTAL: return mUptime + (curTime-mUptimeStart); + case STATS_LAST: return mLastUptime; + case STATS_CURRENT: return (curTime-mUptimeStart); + case STATS_UNPLUGGED: return (curTime-mTrackBatteryUptimeStart); } return 0; } @@ -1162,10 +1535,10 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { @Override public long computeRealtime(long curTime, int which) { switch (which) { - case STATS_TOTAL: return mRealtime + (curTime-mRealtimeStart); - case STATS_LAST: return mLastRealtime; - case STATS_CURRENT: return (curTime-mRealtimeStart); - case STATS_UNPLUGGED: return (curTime-mTrackBatteryRealtimeStart); + case STATS_TOTAL: return mRealtime + (curTime-mRealtimeStart); + case STATS_LAST: return mLastRealtime; + case STATS_CURRENT: return (curTime-mRealtimeStart); + case STATS_UNPLUGGED: return (curTime-mTrackBatteryRealtimeStart); } return 0; } @@ -1173,13 +1546,14 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { @Override public long computeBatteryUptime(long curTime, int which) { switch (which) { - case STATS_TOTAL: - return mBatteryUptime + getBatteryUptime(curTime); - case STATS_LAST: - return mBatteryLastUptime; - case STATS_CURRENT: - case STATS_UNPLUGGED: - return getBatteryUptime(curTime); + case STATS_TOTAL: + return mBatteryUptime + getBatteryUptime(curTime); + case STATS_LAST: + return mBatteryLastUptime; + case STATS_CURRENT: + return getBatteryUptime(curTime); + case STATS_UNPLUGGED: + return getBatteryUptimeLocked(curTime) - mUnpluggedBatteryUptime; } return 0; } @@ -1187,20 +1561,21 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { @Override public long computeBatteryRealtime(long curTime, int which) { switch (which) { - case STATS_TOTAL: - return mBatteryRealtime + getBatteryRealtimeLocked(curTime); - case STATS_LAST: - return mBatteryLastRealtime; - case STATS_CURRENT: - case STATS_UNPLUGGED: - return getBatteryRealtimeLocked(curTime); + case STATS_TOTAL: + return mBatteryRealtime + getBatteryRealtimeLocked(curTime); + case STATS_LAST: + return mBatteryLastRealtime; + case STATS_CURRENT: + return getBatteryRealtimeLocked(curTime); + case STATS_UNPLUGGED: + return getBatteryRealtimeLocked(curTime) - mUnpluggedBatteryRealtime; } return 0; } long getBatteryUptimeLocked(long curTime) { long time = mTrackBatteryPastUptime; - if (mOnBattery) { + if (mOnBatteryInternal) { time += curTime - mTrackBatteryUptimeStart; } return time; @@ -1217,7 +1592,7 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { long getBatteryRealtimeLocked(long curTime) { long time = mTrackBatteryPastRealtime; - if (mOnBattery) { + if (mOnBatteryInternal) { time += curTime - mTrackBatteryRealtimeStart; } return time; @@ -1234,7 +1609,7 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { public Uid getUidStatsLocked(int uid) { Uid u = mUidStats.get(uid); if (u == null) { - u = new Uid(); + u = new Uid(uid); mUidStats.put(uid, u); } return u; @@ -1246,7 +1621,7 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { public void removeUidStatsLocked(int uid) { mUidStats.remove(uid); } - + /** * Retrieve the statistics object for a particular process, creating * if needed. @@ -1373,8 +1748,8 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { private void readSummaryFromParcel(Parcel in) { final int version = in.readInt(); if (version != VERSION) { - Log.e("BatteryStats", "readFromParcel: version got " + version - + ", expected " + VERSION); + Log.w("BatteryStats", "readFromParcel: version got " + version + + ", expected " + VERSION + "; erasing old stats"); return; } @@ -1388,15 +1763,20 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { mRealtime = in.readLong(); mLastRealtime = in.readLong(); mStartCount++; + + mScreenOn = false; + mScreenOnTimer.readSummaryFromParcelLocked(in); + mPhoneOn = false; + mPhoneOnTimer.readSummaryFromParcelLocked(in); final int NU = in.readInt(); - for (int iu=0; iu= 12) { - int NSE = in.readInt(); - for (int is=0; is 0) { for (Map.Entry ent - : u.mWakelockStats.entrySet()) { + : u.mWakelockStats.entrySet()) { out.writeString(ent.getKey()); Uid.Wakelock wl = ent.getValue(); - if (wl.wakeTimeFull != null) { + if (wl.mTimerFull != null) { out.writeInt(1); - wl.wakeTimeFull.writeSummaryFromParcelLocked(out, NOW); + wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL); } else { out.writeInt(0); } - if (wl.wakeTimePartial != null) { + if (wl.mTimerPartial != null) { out.writeInt(1); - wl.wakeTimePartial.writeSummaryFromParcelLocked(out, NOW); + wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL); } else { out.writeInt(0); } - if (wl.wakeTimeWindow != null) { + if (wl.mTimerWindow != null) { out.writeInt(1); - wl.wakeTimeWindow.writeSummaryFromParcelLocked(out, NOW); + wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL); } else { out.writeInt(0); } @@ -1513,12 +1899,12 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { out.writeInt(NSE); if (NSE > 0) { for (Map.Entry ent - : u.mSensorStats.entrySet()) { + : u.mSensorStats.entrySet()) { out.writeInt(ent.getKey()); Uid.Sensor se = ent.getValue(); - if (se.sensorTime != null) { + if (se.mTimer != null) { out.writeInt(1); - se.sensorTime.writeSummaryFromParcelLocked(out, NOW); + se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL); } else { out.writeInt(0); } @@ -1568,6 +1954,9 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { } } } + + out.writeLong(u.getTcpBytesReceived(STATS_TOTAL)); + out.writeLong(u.getTcpBytesSent(STATS_TOTAL)); } } @@ -1586,6 +1975,10 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { mBatteryLastUptime = in.readLong(); mBatteryRealtime = in.readLong(); mBatteryLastRealtime = in.readLong(); + mScreenOn = false; + mScreenOnTimer = new Timer(-1, null, mUnpluggables, in); + mPhoneOn = false; + mPhoneOnTimer = new Timer(-2, null, mUnpluggables, in); mUptime = in.readLong(); mUptimeStart = in.readLong(); mLastUptime = in.readLong(); @@ -1593,10 +1986,13 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { mRealtimeStart = in.readLong(); mLastRealtime = in.readLong(); mOnBattery = in.readInt() != 0; + mOnBatteryInternal = false; // we are no longer really running. mTrackBatteryPastUptime = in.readLong(); mTrackBatteryUptimeStart = in.readLong(); mTrackBatteryPastRealtime = in.readLong(); mTrackBatteryRealtimeStart = in.readLong(); + mUnpluggedBatteryUptime = in.readLong(); + mUnpluggedBatteryRealtime = in.readLong(); mLastWriteTime = in.readLong(); mPartialTimers.clear(); @@ -1606,10 +2002,10 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { int numUids = in.readInt(); mUidStats.clear(); for (int i = 0; i < numUids; i++) { - int key = in.readInt(); - Uid uid = new Uid(); - uid.readFromParcelLocked(in); - mUidStats.append(key, uid); + int uid = in.readInt(); + Uid u = new Uid(uid); + u.readFromParcelLocked(mUnpluggables, in); + mUidStats.append(uid, u); } } @@ -1619,12 +2015,19 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { @SuppressWarnings("unused") void writeToParcelLocked(Parcel out, int flags) { + final long uSecUptime = SystemClock.uptimeMillis() * 1000; + final long uSecRealtime = SystemClock.elapsedRealtime() * 1000; + final long batteryUptime = getBatteryUptimeLocked(uSecUptime); + final long batteryRealtime = getBatteryRealtimeLocked(uSecRealtime); + out.writeInt(MAGIC); out.writeInt(mStartCount); out.writeLong(mBatteryUptime); out.writeLong(mBatteryLastUptime); out.writeLong(mBatteryRealtime); out.writeLong(mBatteryLastRealtime); + mScreenOnTimer.writeToParcel(out, batteryRealtime); + mPhoneOnTimer.writeToParcel(out, batteryRealtime); out.writeLong(mUptime); out.writeLong(mUptimeStart); out.writeLong(mLastUptime); @@ -1632,10 +2035,12 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { out.writeLong(mRealtimeStart); out.writeLong(mLastRealtime); out.writeInt(mOnBattery ? 1 : 0); - out.writeLong(mTrackBatteryPastUptime); + out.writeLong(batteryUptime); out.writeLong(mTrackBatteryUptimeStart); - out.writeLong(mTrackBatteryPastRealtime); + out.writeLong(batteryRealtime); out.writeLong(mTrackBatteryRealtimeStart); + out.writeLong(mUnpluggedBatteryUptime); + out.writeLong(mUnpluggedBatteryRealtime); out.writeLong(mLastWriteTime); int size = mUidStats.size(); @@ -1644,7 +2049,7 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { out.writeInt(mUidStats.keyAt(i)); Uid uid = mUidStats.valueAt(i); - uid.writeToParcelLocked(out); + uid.writeToParcelLocked(out, batteryRealtime); } } @@ -1658,4 +2063,14 @@ public final class BatteryStatsImpl extends BatteryStats implements Parcelable { return new BatteryStatsImpl[size]; } }; + + public void dumpLocked(Printer pw) { + if (DEBUG) { + Log.i(TAG, "*** Screen timer:"); + mScreenOnTimer.logState(); + Log.i(TAG, "*** Phone timer:"); + mPhoneOnTimer.logState(); + } + super.dumpLocked(pw); + } } diff --git a/core/java/com/android/internal/os/HandlerCaller.java b/core/java/com/android/internal/os/HandlerCaller.java index 1ec74a1b9d38bf1148add2cadf30c3e45979999b..932555d15b9cb2a905b8a95f658d71b9051c5be6 100644 --- a/core/java/com/android/internal/os/HandlerCaller.java +++ b/core/java/com/android/internal/os/HandlerCaller.java @@ -21,7 +21,8 @@ public class HandlerCaller { public Object arg1; public Object arg2; - Object arg3; + public Object arg3; + public Object arg4; public int argi1; public int argi2; public int argi3; @@ -119,6 +120,10 @@ public class HandlerCaller { return mH.obtainMessage(what, arg1, 0); } + public Message obtainMessageII(int what, int arg1, int arg2) { + return mH.obtainMessage(what, arg1, arg2); + } + public Message obtainMessageIO(int what, int arg1, Object arg2) { return mH.obtainMessage(what, arg1, 0, arg2); } @@ -149,6 +154,16 @@ public class HandlerCaller { return mH.obtainMessage(what, 0, 0, args); } + public Message obtainMessageOOOO(int what, Object arg1, Object arg2, + Object arg3, Object arg4) { + SomeArgs args = obtainArgs(); + args.arg1 = arg1; + args.arg2 = arg2; + args.arg3 = arg3; + args.arg4 = arg4; + return mH.obtainMessage(what, 0, 0, args); + } + public Message obtainMessageIIII(int what, int arg1, int arg2, int arg3, int arg4) { SomeArgs args = obtainArgs(); diff --git a/core/java/com/android/internal/os/HandlerThread.java b/core/java/com/android/internal/os/HandlerThread.java deleted file mode 100644 index 1de6bfd407b3bf48442ecbc1fd2cda49906b6eec..0000000000000000000000000000000000000000 --- a/core/java/com/android/internal/os/HandlerThread.java +++ /dev/null @@ -1,91 +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. - */ - -package com.android.internal.os; - -import android.os.Handler; -import android.os.HandlerInterface; -import android.os.Looper; - -/** - * Handy class for starting a new thread containing a Handler - * @hide - * @deprecated - */ -public class HandlerThread extends Thread -{ - Runnable mSetup; - HandlerInterface mhi; - Handler mh; - Throwable mtr; - final Object mMonitor = new Object(); - - public - HandlerThread(HandlerInterface h, Runnable setup, String name) - { - super(name); - - mhi = h; - mSetup = setup; - - synchronized (mMonitor) { - start(); - while (mh == null && mtr == null) { - try { - mMonitor.wait(); - } catch (InterruptedException ex) { - } - } - } - - if (mtr != null) { - throw new RuntimeException("exception while starting", mtr); - } - } - - @Override - public void - run() - { - synchronized(mMonitor) { - try { - Looper.prepare(); - mh = new HandlerHelper (mhi); - - if (mSetup != null) { - mSetup.run(); - mSetup = null; - } - } catch (RuntimeException exc) { - mtr = exc; - } - - mMonitor.notify(); - } - - if (mtr == null) { - Looper.loop(); - } - } - - public Handler - getHandler() - { - return mh; - } - -} - diff --git a/core/java/com/android/internal/os/IResultReceiver.aidl b/core/java/com/android/internal/os/IResultReceiver.aidl new file mode 100644 index 0000000000000000000000000000000000000000..2b70f95a5cf2a624f0081ed738826c01dd0804bb --- /dev/null +++ b/core/java/com/android/internal/os/IResultReceiver.aidl @@ -0,0 +1,25 @@ +/* //device/java/android/android/app/IActivityPendingResult.aidl +** +** Copyright 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. +*/ + +package com.android.internal.os; + +import android.os.Bundle; + +/** @hide */ +oneway interface IResultReceiver { + void send(int resultCode, in Bundle resultData); +} diff --git a/core/res/res/drawable/radiobutton_background.xml b/core/java/com/android/internal/os/PkgUsageStats.aidl old mode 100644 new mode 100755 similarity index 70% rename from core/res/res/drawable/radiobutton_background.xml rename to core/java/com/android/internal/os/PkgUsageStats.aidl index 948a141dac25fe1d09cb9382633b5d2eaa5841c7..83052717bf1f4addfa22e406d6e4fd567229c9bf --- a/core/res/res/drawable/radiobutton_background.xml +++ b/core/java/com/android/internal/os/PkgUsageStats.aidl @@ -1,6 +1,4 @@ - - - - - +package com.android.internal.os; + +parcelable PkgUsageStats; diff --git a/core/java/com/android/internal/os/PkgUsageStats.java b/core/java/com/android/internal/os/PkgUsageStats.java new file mode 100755 index 0000000000000000000000000000000000000000..e847878dd5682d3d5d78da928d0953b4e382b99d --- /dev/null +++ b/core/java/com/android/internal/os/PkgUsageStats.java @@ -0,0 +1,60 @@ +package com.android.internal.os; + +import android.os.Parcel; +import android.os.Parcelable; + +/** + * implementation of PkgUsageStats associated with an + * application package. + * @hide + */ +public class PkgUsageStats implements Parcelable { + public String packageName; + public int launchCount; + public long usageTime; + + public static final Parcelable.Creator CREATOR + = new Parcelable.Creator() { + public PkgUsageStats createFromParcel(Parcel in) { + return new PkgUsageStats(in); + } + + public PkgUsageStats[] newArray(int size) { + return new PkgUsageStats[size]; + } + }; + + public String toString() { + return "PkgUsageStats{" + + Integer.toHexString(System.identityHashCode(this)) + + " " + packageName + "}"; + } + + public PkgUsageStats(String pkgName, int count, long time) { + packageName = pkgName; + launchCount = count; + usageTime = time; + } + + public PkgUsageStats(Parcel source) { + packageName = source.readString(); + launchCount = source.readInt(); + usageTime = source.readLong(); + } + + public PkgUsageStats(PkgUsageStats pStats) { + packageName = pStats.packageName; + launchCount = pStats.launchCount; + usageTime = pStats.usageTime; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int parcelableFlags){ + dest.writeString(packageName); + dest.writeInt(launchCount); + dest.writeLong(usageTime); + } +} diff --git a/core/java/com/android/internal/os/RecoverySystem.java b/core/java/com/android/internal/os/RecoverySystem.java new file mode 100644 index 0000000000000000000000000000000000000000..c938610b612e5505d59c380ebcc702f288a74a42 --- /dev/null +++ b/core/java/com/android/internal/os/RecoverySystem.java @@ -0,0 +1,128 @@ +/* + * 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. + */ + +package com.android.internal.os; + +import android.os.FileUtils; +import android.os.Power; +import android.util.Log; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Iterator; +import java.util.Map; + +/** + * Utility class for interacting with the Android recovery partition. + * The recovery partition is a small standalone system which can perform + * operations that are difficult while the main system is running, like + * upgrading system software or reformatting the data partition. + * Note that most of these operations must be run as root. + * + * @hide + */ +public class RecoverySystem { + private static final String TAG = "RecoverySystem"; // for logging + + // Used to communicate with recovery. See commands/recovery/recovery.c. + private static File RECOVERY_DIR = new File("/cache/recovery"); + private static File COMMAND_FILE = new File(RECOVERY_DIR, "command"); + private static File LOG_FILE = new File(RECOVERY_DIR, "log"); + + // Length limits for reading files. + private static int LOG_FILE_MAX_LENGTH = 8 * 1024; + + /** + * Reboot into the recovery system to install a system update. + * @param update package to install (must be in /cache or /data). + * @throws IOException if something goes wrong. + */ + public static void rebootAndUpdate(File update) throws IOException { + String path = update.getCanonicalPath(); + if (path.startsWith("/cache/")) { + path = "CACHE:" + path.substring(7); + } else if (path.startsWith("/data/")) { + path = "DATA:" + path.substring(6); + } else { + throw new IllegalArgumentException( + "Must start with /cache or /data: " + path); + } + bootCommand("--update_package=" + path); + } + + /** + * Reboot into the recovery system to wipe the /data partition. + * @param extras to add to the RECOVERY_COMPLETED intent after rebooting. + * @throws IOException if something goes wrong. + */ + public static void rebootAndWipe() throws IOException { + bootCommand("--wipe_data"); + } + + /** + * Reboot into the recovery system with the supplied argument. + * @param arg to pass to the recovery utility. + * @throws IOException if something goes wrong. + */ + private static void bootCommand(String arg) throws IOException { + RECOVERY_DIR.mkdirs(); // In case we need it + COMMAND_FILE.delete(); // In case it's not writable + LOG_FILE.delete(); + + FileWriter command = new FileWriter(COMMAND_FILE); + try { + command.write(arg); + command.write("\n"); + } finally { + command.close(); + } + + // Having written the command file, go ahead and reboot + Power.reboot("recovery"); + throw new IOException("Reboot failed (no permissions?)"); + } + + /** + * Called after booting to process and remove recovery-related files. + * @return the log file from recovery, or null if none was found. + */ + public static String handleAftermath() { + // Record the tail of the LOG_FILE + String log = null; + try { + log = FileUtils.readTextFile(LOG_FILE, -LOG_FILE_MAX_LENGTH, "...\n"); + } catch (FileNotFoundException e) { + Log.i(TAG, "No recovery log file"); + } catch (IOException e) { + Log.e(TAG, "Error reading recovery log", e); + } + + // Delete everything in RECOVERY_DIR + String[] names = RECOVERY_DIR.list(); + for (int i = 0; names != null && i < names.length; i++) { + File f = new File(RECOVERY_DIR, names[i]); + if (!f.delete()) { + Log.e(TAG, "Can't delete: " + f); + } else { + Log.i(TAG, "Deleted: " + f); + } + } + + return log; + } +} diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java index f21b62f32c862b149cca8663cd3ef4ffbec9a611..ac8b5893416845213ebd4b076322e4bee2e69181 100644 --- a/core/java/com/android/internal/os/ZygoteInit.java +++ b/core/java/com/android/internal/os/ZygoteInit.java @@ -19,6 +19,7 @@ package com.android.internal.os; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.content.res.TypedArray; +import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.net.LocalServerSocket; import android.os.Debug; @@ -335,32 +336,18 @@ public class ZygoteInit { mResources.startPreloading(); if (PRELOAD_RESOURCES) { Log.i(TAG, "Preloading resources..."); + long startTime = SystemClock.uptimeMillis(); TypedArray ar = mResources.obtainTypedArray( com.android.internal.R.array.preloaded_drawables); - int N = ar.length(); - for (int i=0; i PRELOAD_GC_THRESHOLD) { - if (Config.LOGV) { - Log.v(TAG, " GC at " + Debug.getGlobalAllocSize()); - } - runtime.gcSoftReferences(); - runtime.runFinalizationSync(); - Debug.resetGlobalAllocSize(); - } - int id = ar.getResourceId(i, 0); - if (Config.LOGV) { - Log.v(TAG, "Preloading resource #" + Integer.toHexString(id)); - } - if (id != 0) { - Drawable dr = mResources.getDrawable(id); - if ((dr.getChangingConfigurations()&~ActivityInfo.CONFIG_FONT_SCALE) != 0) { - Log.w(TAG, "Preloaded drawable resource #0x" - + Integer.toHexString(id) - + " that varies with configuration!!"); - } - } - } + int N = preloadDrawables(runtime, ar); + Log.i(TAG, "...preloaded " + N + " resources in " + + (SystemClock.uptimeMillis()-startTime) + "ms."); + + startTime = SystemClock.uptimeMillis(); + ar = mResources.obtainTypedArray( + com.android.internal.R.array.preloaded_color_state_lists); + N = preloadColorStateLists(runtime, ar); Log.i(TAG, "...preloaded " + N + " resources in " + (SystemClock.uptimeMillis()-startTime) + "ms."); } @@ -372,6 +359,56 @@ public class ZygoteInit { } } + private static int preloadColorStateLists(VMRuntime runtime, TypedArray ar) { + int N = ar.length(); + for (int i=0; i PRELOAD_GC_THRESHOLD) { + if (Config.LOGV) { + Log.v(TAG, " GC at " + Debug.getGlobalAllocSize()); + } + runtime.gcSoftReferences(); + runtime.runFinalizationSync(); + Debug.resetGlobalAllocSize(); + } + int id = ar.getResourceId(i, 0); + if (Config.LOGV) { + Log.v(TAG, "Preloading resource #" + Integer.toHexString(id)); + } + if (id != 0) { + mResources.getColorStateList(id); + } + } + return N; + } + + + private static int preloadDrawables(VMRuntime runtime, TypedArray ar) { + int N = ar.length(); + for (int i=0; i PRELOAD_GC_THRESHOLD) { + if (Config.LOGV) { + Log.v(TAG, " GC at " + Debug.getGlobalAllocSize()); + } + runtime.gcSoftReferences(); + runtime.runFinalizationSync(); + Debug.resetGlobalAllocSize(); + } + int id = ar.getResourceId(i, 0); + if (Config.LOGV) { + Log.v(TAG, "Preloading resource #" + Integer.toHexString(id)); + } + if (id != 0) { + Drawable dr = mResources.getDrawable(id); + if ((dr.getChangingConfigurations()&~ActivityInfo.CONFIG_FONT_SCALE) != 0) { + Log.w(TAG, "Preloaded drawable resource #0x" + + Integer.toHexString(id) + + " (" + ar.getString(i) + ") that varies with configuration!!"); + } + } + } + return N; + } + /** * Runs several special GCs to try to clean up a few generations of * softly- and final-reachable objects, along with any other garbage. diff --git a/core/java/com/android/internal/view/IInputConnectionWrapper.java b/core/java/com/android/internal/view/IInputConnectionWrapper.java index 011e9446985a314b3eee3df8666d19ef6cfc546d..106392d35a6a5aec50765813946854df03938f6f 100644 --- a/core/java/com/android/internal/view/IInputConnectionWrapper.java +++ b/core/java/com/android/internal/view/IInputConnectionWrapper.java @@ -1,7 +1,5 @@ package com.android.internal.view; -import com.android.internal.view.IInputContext; - import android.os.Bundle; import android.os.Handler; import android.os.Looper; @@ -13,6 +11,8 @@ import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; +import java.lang.ref.WeakReference; + public class IInputConnectionWrapper extends IInputContext.Stub { static final String TAG = "IInputConnectionWrapper"; @@ -22,18 +22,20 @@ public class IInputConnectionWrapper extends IInputContext.Stub { private static final int DO_GET_EXTRACTED_TEXT = 40; private static final int DO_COMMIT_TEXT = 50; private static final int DO_COMMIT_COMPLETION = 55; + private static final int DO_SET_SELECTION = 57; + private static final int DO_PERFORM_EDITOR_ACTION = 58; + private static final int DO_PERFORM_CONTEXT_MENU_ACTION = 59; private static final int DO_SET_COMPOSING_TEXT = 60; private static final int DO_FINISH_COMPOSING_TEXT = 65; private static final int DO_SEND_KEY_EVENT = 70; private static final int DO_DELETE_SURROUNDING_TEXT = 80; private static final int DO_BEGIN_BATCH_EDIT = 90; private static final int DO_END_BATCH_EDIT = 95; - private static final int DO_HIDE_STATUS_ICON = 100; - private static final int DO_SHOW_STATUS_ICON = 110; + private static final int DO_REPORT_FULLSCREEN_MODE = 100; private static final int DO_PERFORM_PRIVATE_COMMAND = 120; private static final int DO_CLEAR_META_KEY_STATES = 130; - private InputConnection mInputConnection; + private WeakReference mInputConnection; private Looper mMainLooper; private Handler mH; @@ -57,17 +59,21 @@ public class IInputConnectionWrapper extends IInputContext.Stub { } public IInputConnectionWrapper(Looper mainLooper, InputConnection conn) { - mInputConnection = conn; + mInputConnection = new WeakReference(conn); mMainLooper = mainLooper; mH = new MyHandler(mMainLooper); } - public void getTextAfterCursor(int length, int seq, IInputContextCallback callback) { - dispatchMessage(obtainMessageISC(DO_GET_TEXT_AFTER_CURSOR, length, seq, callback)); + public boolean isActive() { + return true; + } + + public void getTextAfterCursor(int length, int flags, int seq, IInputContextCallback callback) { + dispatchMessage(obtainMessageIISC(DO_GET_TEXT_AFTER_CURSOR, length, flags, seq, callback)); } - public void getTextBeforeCursor(int length, int seq, IInputContextCallback callback) { - dispatchMessage(obtainMessageISC(DO_GET_TEXT_BEFORE_CURSOR, length, seq, callback)); + public void getTextBeforeCursor(int length, int flags, int seq, IInputContextCallback callback) { + dispatchMessage(obtainMessageIISC(DO_GET_TEXT_BEFORE_CURSOR, length, flags, seq, callback)); } public void getCursorCapsMode(int reqModes, int seq, IInputContextCallback callback) { @@ -88,6 +94,18 @@ public class IInputConnectionWrapper extends IInputContext.Stub { dispatchMessage(obtainMessageO(DO_COMMIT_COMPLETION, text)); } + public void setSelection(int start, int end) { + dispatchMessage(obtainMessageII(DO_SET_SELECTION, start, end)); + } + + public void performEditorAction(int id) { + dispatchMessage(obtainMessageII(DO_PERFORM_EDITOR_ACTION, id, 0)); + } + + public void performContextMenuAction(int id) { + dispatchMessage(obtainMessageII(DO_PERFORM_CONTEXT_MENU_ACTION, id, 0)); + } + public void setComposingText(CharSequence text, int newCursorPosition) { dispatchMessage(obtainMessageIO(DO_SET_COMPOSING_TEXT, newCursorPosition, text)); } @@ -117,12 +135,8 @@ public class IInputConnectionWrapper extends IInputContext.Stub { dispatchMessage(obtainMessage(DO_END_BATCH_EDIT)); } - public void hideStatusIcon() { - dispatchMessage(obtainMessage(DO_HIDE_STATUS_ICON)); - } - - public void showStatusIcon(String packageName, int resId) { - dispatchMessage(obtainMessageIO(DO_SHOW_STATUS_ICON, resId, packageName)); + public void reportFullscreenMode(boolean enabled) { + dispatchMessage(obtainMessageII(DO_REPORT_FULLSCREEN_MODE, enabled ? 1 : 0, 0)); } public void performPrivateCommand(String action, Bundle data) { @@ -147,8 +161,14 @@ public class IInputConnectionWrapper extends IInputContext.Stub { case DO_GET_TEXT_AFTER_CURSOR: { SomeArgs args = (SomeArgs)msg.obj; try { - args.callback.setTextAfterCursor(mInputConnection.getTextAfterCursor(msg.arg1), - args.seq); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "getTextAfterCursor on inactive InputConnection"); + args.callback.setTextAfterCursor(null, args.seq); + return; + } + args.callback.setTextAfterCursor(ic.getTextAfterCursor( + msg.arg1, msg.arg2), args.seq); } catch (RemoteException e) { Log.w(TAG, "Got RemoteException calling setTextAfterCursor", e); } @@ -157,8 +177,14 @@ public class IInputConnectionWrapper extends IInputContext.Stub { case DO_GET_TEXT_BEFORE_CURSOR: { SomeArgs args = (SomeArgs)msg.obj; try { - args.callback.setTextBeforeCursor(mInputConnection.getTextBeforeCursor(msg.arg1), - args.seq); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "getTextBeforeCursor on inactive InputConnection"); + args.callback.setTextBeforeCursor(null, args.seq); + return; + } + args.callback.setTextBeforeCursor(ic.getTextBeforeCursor( + msg.arg1, msg.arg2), args.seq); } catch (RemoteException e) { Log.w(TAG, "Got RemoteException calling setTextBeforeCursor", e); } @@ -167,7 +193,13 @@ public class IInputConnectionWrapper extends IInputContext.Stub { case DO_GET_CURSOR_CAPS_MODE: { SomeArgs args = (SomeArgs)msg.obj; try { - args.callback.setCursorCapsMode(mInputConnection.getCursorCapsMode(msg.arg1), + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "getCursorCapsMode on inactive InputConnection"); + args.callback.setCursorCapsMode(0, args.seq); + return; + } + args.callback.setCursorCapsMode(ic.getCursorCapsMode(msg.arg1), args.seq); } catch (RemoteException e) { Log.w(TAG, "Got RemoteException calling setCursorCapsMode", e); @@ -177,7 +209,13 @@ public class IInputConnectionWrapper extends IInputContext.Stub { case DO_GET_EXTRACTED_TEXT: { SomeArgs args = (SomeArgs)msg.obj; try { - args.callback.setExtractedText(mInputConnection.getExtractedText( + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "getExtractedText on inactive InputConnection"); + args.callback.setExtractedText(null, args.seq); + return; + } + args.callback.setExtractedText(ic.getExtractedText( (ExtractedTextRequest)args.arg1, msg.arg1), args.seq); } catch (RemoteException e) { Log.w(TAG, "Got RemoteException calling setExtractedText", e); @@ -185,52 +223,134 @@ public class IInputConnectionWrapper extends IInputContext.Stub { return; } case DO_COMMIT_TEXT: { - mInputConnection.commitText((CharSequence)msg.obj, msg.arg1); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "commitText on inactive InputConnection"); + return; + } + ic.commitText((CharSequence)msg.obj, msg.arg1); + return; + } + case DO_SET_SELECTION: { + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "setSelection on inactive InputConnection"); + return; + } + ic.setSelection(msg.arg1, msg.arg2); + return; + } + case DO_PERFORM_EDITOR_ACTION: { + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "performEditorAction on inactive InputConnection"); + return; + } + ic.performEditorAction(msg.arg1); + return; + } + case DO_PERFORM_CONTEXT_MENU_ACTION: { + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "performContextMenuAction on inactive InputConnection"); + return; + } + ic.performContextMenuAction(msg.arg1); return; } case DO_COMMIT_COMPLETION: { - mInputConnection.commitCompletion((CompletionInfo)msg.obj); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "commitCompletion on inactive InputConnection"); + return; + } + ic.commitCompletion((CompletionInfo)msg.obj); return; } case DO_SET_COMPOSING_TEXT: { - mInputConnection.setComposingText((CharSequence)msg.obj, msg.arg1); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "setComposingText on inactive InputConnection"); + return; + } + ic.setComposingText((CharSequence)msg.obj, msg.arg1); return; } case DO_FINISH_COMPOSING_TEXT: { - mInputConnection.finishComposingText(); + InputConnection ic = mInputConnection.get(); + // Note we do NOT check isActive() here, because this is safe + // for an IME to call at any time, and we need to allow it + // through to clean up our state after the IME has switched to + // another client. + if (ic == null) { + Log.w(TAG, "finishComposingText on inactive InputConnection"); + return; + } + ic.finishComposingText(); return; } case DO_SEND_KEY_EVENT: { - mInputConnection.sendKeyEvent((KeyEvent)msg.obj); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "sendKeyEvent on inactive InputConnection"); + return; + } + ic.sendKeyEvent((KeyEvent)msg.obj); return; } case DO_CLEAR_META_KEY_STATES: { - mInputConnection.clearMetaKeyStates(msg.arg1); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "clearMetaKeyStates on inactive InputConnection"); + return; + } + ic.clearMetaKeyStates(msg.arg1); return; } case DO_DELETE_SURROUNDING_TEXT: { - mInputConnection.deleteSurroundingText(msg.arg1, msg.arg2); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "deleteSurroundingText on inactive InputConnection"); + return; + } + ic.deleteSurroundingText(msg.arg1, msg.arg2); return; } case DO_BEGIN_BATCH_EDIT: { - mInputConnection.beginBatchEdit(); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "beginBatchEdit on inactive InputConnection"); + return; + } + ic.beginBatchEdit(); return; } case DO_END_BATCH_EDIT: { - mInputConnection.beginBatchEdit(); - return; - } - case DO_HIDE_STATUS_ICON: { - mInputConnection.hideStatusIcon(); + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "endBatchEdit on inactive InputConnection"); + return; + } + ic.endBatchEdit(); return; } - case DO_SHOW_STATUS_ICON: { - mInputConnection.showStatusIcon((String)msg.obj, msg.arg1); + case DO_REPORT_FULLSCREEN_MODE: { + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "showStatusIcon on inactive InputConnection"); + return; + } + ic.reportFullscreenMode(msg.arg1 == 1); return; } case DO_PERFORM_PRIVATE_COMMAND: { + InputConnection ic = mInputConnection.get(); + if (ic == null || !isActive()) { + Log.w(TAG, "performPrivateCommand on inactive InputConnection"); + return; + } SomeArgs args = (SomeArgs)msg.obj; - mInputConnection.performPrivateCommand((String)args.arg1, + ic.performPrivateCommand((String)args.arg1, (Bundle)args.arg2); return; } @@ -257,6 +377,13 @@ public class IInputConnectionWrapper extends IInputContext.Stub { return mH.obtainMessage(what, arg1, 0, args); } + Message obtainMessageIISC(int what, int arg1, int arg2, int seq, IInputContextCallback callback) { + SomeArgs args = new SomeArgs(); + args.callback = callback; + args.seq = seq; + return mH.obtainMessage(what, arg1, arg2, args); + } + Message obtainMessageIOSC(int what, int arg1, Object arg2, int seq, IInputContextCallback callback) { SomeArgs args = new SomeArgs(); diff --git a/core/java/com/android/internal/view/IInputContext.aidl b/core/java/com/android/internal/view/IInputContext.aidl index b048ce292e2b8b4876c41d819ca48664f8d0fedc..02cb9e4df5e3511ebc8aec8d69b8d43d84ba0129 100644 --- a/core/java/com/android/internal/view/IInputContext.aidl +++ b/core/java/com/android/internal/view/IInputContext.aidl @@ -29,9 +29,9 @@ import com.android.internal.view.IInputContextCallback; * {@hide} */ oneway interface IInputContext { - void getTextBeforeCursor(int length, int seq, IInputContextCallback callback); + void getTextBeforeCursor(int length, int flags, int seq, IInputContextCallback callback); - void getTextAfterCursor(int length, int seq, IInputContextCallback callback); + void getTextAfterCursor(int length, int flags, int seq, IInputContextCallback callback); void getCursorCapsMode(int reqModes, int seq, IInputContextCallback callback); @@ -48,17 +48,21 @@ import com.android.internal.view.IInputContextCallback; void commitCompletion(in CompletionInfo completion); + void setSelection(int start, int end); + + void performEditorAction(int actionCode); + + void performContextMenuAction(int id); + void beginBatchEdit(); void endBatchEdit(); + void reportFullscreenMode(boolean enabled); + void sendKeyEvent(in KeyEvent event); void clearMetaKeyStates(int states); void performPrivateCommand(String action, in Bundle data); - - void showStatusIcon(String packageName, int resId); - - void hideStatusIcon(); } diff --git a/core/java/com/android/internal/view/IInputMethod.aidl b/core/java/com/android/internal/view/IInputMethod.aidl index f650713fc0eff4fd5b42da1bb118f7a0efcbf365..8ff18ed69f846cd91bd24809d22745d686e6c795 100644 --- a/core/java/com/android/internal/view/IInputMethod.aidl +++ b/core/java/com/android/internal/view/IInputMethod.aidl @@ -18,6 +18,7 @@ package com.android.internal.view; import android.graphics.Rect; import android.os.IBinder; +import android.os.ResultReceiver; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.inputmethod.EditorInfo; @@ -38,9 +39,9 @@ oneway interface IInputMethod { void unbindInput(); - void startInput(in EditorInfo attribute); + void startInput(in IInputContext inputContext, in EditorInfo attribute); - void restartInput(in EditorInfo attribute); + void restartInput(in IInputContext inputContext, in EditorInfo attribute); void createSession(IInputMethodCallback callback); @@ -48,7 +49,7 @@ oneway interface IInputMethod { void revokeSession(IInputMethodSession session); - void showSoftInput(boolean explicit); + void showSoftInput(int flags, in ResultReceiver resultReceiver); - void hideSoftInput(); + void hideSoftInput(int flags, in ResultReceiver resultReceiver); } diff --git a/core/java/com/android/internal/view/IInputMethodManager.aidl b/core/java/com/android/internal/view/IInputMethodManager.aidl index 2a15bdb999716b1a0edbbbe098d42b955e152abd..adec0a750ebc57a01b36350782446f29d5c9e9fb 100644 --- a/core/java/com/android/internal/view/IInputMethodManager.aidl +++ b/core/java/com/android/internal/view/IInputMethodManager.aidl @@ -16,6 +16,7 @@ package com.android.internal.view; +import android.os.ResultReceiver; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.EditorInfo; import com.android.internal.view.InputBindResult; @@ -35,18 +36,22 @@ interface IInputMethodManager { void removeClient(in IInputMethodClient client); InputBindResult startInput(in IInputMethodClient client, - in EditorInfo attribute, boolean initial, boolean needResult); + IInputContext inputContext, in EditorInfo attribute, + boolean initial, boolean needResult); void finishInput(in IInputMethodClient client); - void showSoftInput(in IInputMethodClient client, int flags); - void hideSoftInput(in IInputMethodClient client, int flags); - void windowGainedFocus(in IInputMethodClient client, + boolean showSoftInput(in IInputMethodClient client, int flags, + in ResultReceiver resultReceiver); + boolean hideSoftInput(in IInputMethodClient client, int flags, + in ResultReceiver resultReceiver); + void windowGainedFocus(in IInputMethodClient client, in IBinder windowToken, boolean viewHasFocus, boolean isTextEditor, int softInputMode, boolean first, int windowFlags); void showInputMethodPickerFromClient(in IInputMethodClient client); void setInputMethod(in IBinder token, String id); void hideMySoftInput(in IBinder token, int flags); - void updateStatusIcon(int iconId, String iconPackage); + void showMySoftInput(in IBinder token, int flags); + void updateStatusIcon(in IBinder token, String packageName, int iconId); boolean setInputMethodEnabled(String id, boolean enabled); } diff --git a/core/java/com/android/internal/view/IInputMethodSession.aidl b/core/java/com/android/internal/view/IInputMethodSession.aidl index 8a4497692d6e6bc8e01db10e185386125b27ca34..a05ff14bcccd6d3480b62114b1e1cf58fc0cb877 100644 --- a/core/java/com/android/internal/view/IInputMethodSession.aidl +++ b/core/java/com/android/internal/view/IInputMethodSession.aidl @@ -46,4 +46,6 @@ oneway interface IInputMethodSession { void dispatchTrackballEvent(int seq, in MotionEvent event, IInputMethodCallback callback); void appPrivateCommand(String action, in Bundle data); + + void toggleSoftInput(int showFlags, int hideFlags); } diff --git a/core/java/com/android/internal/view/InputConnectionWrapper.java b/core/java/com/android/internal/view/InputConnectionWrapper.java index a9ba5f6190ff1c461afdf66c5c1c99926558292e..b92cb45c1b42f639b6ad6d2eed7adbc9e988c83d 100644 --- a/core/java/com/android/internal/view/InputConnectionWrapper.java +++ b/core/java/com/android/internal/view/InputConnectionWrapper.java @@ -151,11 +151,11 @@ public class InputConnectionWrapper implements InputConnection { mIInputContext = inputContext; } - public CharSequence getTextAfterCursor(int length) { + public CharSequence getTextAfterCursor(int length, int flags) { CharSequence value = null; try { InputContextCallback callback = InputContextCallback.getInstance(); - mIInputContext.getTextAfterCursor(length, callback.mSeq, callback); + mIInputContext.getTextAfterCursor(length, flags, callback.mSeq, callback); synchronized (callback) { callback.waitForResultLocked(); if (callback.mHaveValue) { @@ -169,11 +169,11 @@ public class InputConnectionWrapper implements InputConnection { return value; } - public CharSequence getTextBeforeCursor(int length) { + public CharSequence getTextBeforeCursor(int length, int flags) { CharSequence value = null; try { InputContextCallback callback = InputContextCallback.getInstance(); - mIInputContext.getTextBeforeCursor(length, callback.mSeq, callback); + mIInputContext.getTextBeforeCursor(length, flags, callback.mSeq, callback); synchronized (callback) { callback.waitForResultLocked(); if (callback.mHaveValue) { @@ -241,6 +241,33 @@ public class InputConnectionWrapper implements InputConnection { } } + public boolean setSelection(int start, int end) { + try { + mIInputContext.setSelection(start, end); + return true; + } catch (RemoteException e) { + return false; + } + } + + public boolean performEditorAction(int actionCode) { + try { + mIInputContext.performEditorAction(actionCode); + return true; + } catch (RemoteException e) { + return false; + } + } + + public boolean performContextMenuAction(int id) { + try { + mIInputContext.performContextMenuAction(id); + return true; + } catch (RemoteException e) { + return false; + } + } + public boolean setComposingText(CharSequence text, int newCursorPosition) { try { mIInputContext.setComposingText(text, newCursorPosition); @@ -304,18 +331,9 @@ public class InputConnectionWrapper implements InputConnection { } } - public boolean hideStatusIcon() { - try { - mIInputContext.showStatusIcon(null, 0); - return true; - } catch (RemoteException e) { - return false; - } - } - - public boolean showStatusIcon(String packageName, int resId) { + public boolean reportFullscreenMode(boolean enabled) { try { - mIInputContext.showStatusIcon(packageName, resId); + mIInputContext.reportFullscreenMode(enabled); return true; } catch (RemoteException e) { return false; diff --git a/core/java/com/android/internal/view/menu/ExpandedMenuView.java b/core/java/com/android/internal/view/menu/ExpandedMenuView.java index c16c165438fd7f4c59402640c5a308e3aa18ad81..9e4b4ce14b826993fe7deb4571164f9573f18b6e 100644 --- a/core/java/com/android/internal/view/menu/ExpandedMenuView.java +++ b/core/java/com/android/internal/view/menu/ExpandedMenuView.java @@ -80,6 +80,11 @@ public final class ExpandedMenuView extends ListView implements ItemInvoker, Men setChildrenDrawingCacheEnabled(false); } + @Override + protected boolean recycleOnMeasure() { + return false; + } + public boolean invokeItem(MenuItemImpl item) { return mMenu.performItemAction(item, 0); } diff --git a/core/java/com/android/internal/view/menu/IconMenuItemView.java b/core/java/com/android/internal/view/menu/IconMenuItemView.java index 558a4c30bca11f528a5f0f38b9f821cd7da5b1db..9e1f2aedca4756b8540d89d212a9d1f0baa968fa 100644 --- a/core/java/com/android/internal/view/menu/IconMenuItemView.java +++ b/core/java/com/android/internal/view/menu/IconMenuItemView.java @@ -142,9 +142,6 @@ public final class IconMenuItemView extends TextView implements MenuView.ItemVie } void setCaptionMode(boolean shortcut) { - - mShortcutCaptionMode = shortcut && (mItemData.shouldShowShortcut()); - /* * If there is no item model, don't do any of the below (for example, * the 'More' item doesn't have a model) @@ -153,6 +150,8 @@ public final class IconMenuItemView extends TextView implements MenuView.ItemVie return; } + mShortcutCaptionMode = shortcut && (mItemData.shouldShowShortcut()); + CharSequence text = mItemData.getTitleForItemView(this); if (mShortcutCaptionMode) { diff --git a/core/java/com/android/internal/view/menu/ListMenuItemView.java b/core/java/com/android/internal/view/menu/ListMenuItemView.java index 32513cd5d2ded28361c8d6bc8110b83799897e07..e15587520625bdc0c4f4f1925d758e9fb8c7c518 100644 --- a/core/java/com/android/internal/view/menu/ListMenuItemView.java +++ b/core/java/com/android/internal/view/menu/ListMenuItemView.java @@ -220,7 +220,7 @@ public class ListMenuItemView extends LinearLayout implements MenuView.ItemView mRadioButton = (RadioButton) inflater.inflate(com.android.internal.R.layout.list_menu_item_radio, this, false); - addView(mRadioButton, 0); + addView(mRadioButton); } private void insertCheckBox() { @@ -228,7 +228,7 @@ public class ListMenuItemView extends LinearLayout implements MenuView.ItemView mCheckBox = (CheckBox) inflater.inflate(com.android.internal.R.layout.list_menu_item_checkbox, this, false); - addView(mCheckBox, 0); + addView(mCheckBox); } public boolean prefersCondensedTitle() { diff --git a/core/java/com/android/internal/widget/EditStyledText.java b/core/java/com/android/internal/widget/EditStyledText.java new file mode 100644 index 0000000000000000000000000000000000000000..8a4675a4c82faee20fafd94d020157d65bf97f08 --- /dev/null +++ b/core/java/com/android/internal/widget/EditStyledText.java @@ -0,0 +1,931 @@ +/* + * 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. + */ + +package com.android.internal.widget; + +import android.app.AlertDialog.Builder; +import android.content.Context; +import android.content.DialogInterface; +import android.net.Uri; +import android.os.Bundle; +import android.text.Editable; +import android.text.Html; +import android.text.Spannable; +import android.text.style.AbsoluteSizeSpan; +import android.text.style.ForegroundColorSpan; +import android.text.style.ImageSpan; +import android.util.AttributeSet; +import android.util.Log; +import android.view.MotionEvent; +import android.widget.EditText; + +/** + * EditStyledText extends EditText for managing the flow and status to edit + * the styled text. This manages the states and flows of editing, supports + * inserting image, import/export HTML. + */ +public class EditStyledText extends EditText { + + private static final String LOG_TAG = "EditStyledText"; + private static final boolean DBG = true; + + /** + * The modes of editing actions. + */ + /** The mode that no editing action is done. */ + public static final int MODE_NOTHING = 0; + /** The mode of copy. */ + public static final int MODE_COPY = 1; + /** The mode of paste. */ + public static final int MODE_PASTE = 2; + /** The mode of changing size. */ + public static final int MODE_SIZE = 3; + /** The mode of changing color. */ + public static final int MODE_COLOR = 4; + /** The mode of selection. */ + public static final int MODE_SELECT = 5; + + /** + * The state of selection. + */ + /** The state that selection isn't started. */ + public static final int STATE_SELECT_OFF = 0; + /** The state that selection is started. */ + public static final int STATE_SELECT_ON = 1; + /** The state that selection is done, but not fixed. */ + public static final int STATE_SELECTED = 2; + /** The state that selection is done and not fixed. */ + public static final int STATE_SELECT_FIX = 3; + + /** + * The help message strings. + */ + public static final int HINT_MSG_NULL = 0; + public static final int HINT_MSG_COPY_BUF_BLANK = 1; + public static final int HINT_MSG_SELECT_START = 2; + public static final int HINT_MSG_SELECT_END = 3; + public static final int HINT_MSG_PUSH_COMPETE = 4; + + /** + * EditStyledTextInterface provides functions for notifying messages to + * calling class. + */ + public interface EditStyledTextNotifier { + public void notifyHintMsg(int msgId); + } + + private EditStyledTextNotifier mESTInterface; + + /** + * EditStyledTextEditorManager manages the flow and status of each + * function for editing styled text. + */ + private EditorManager mManager; + private StyledTextConverter mConverter; + private StyledTextToast mToast; + + /** + * EditStyledText extends EditText for managing flow of each editing + * action. + */ + public EditStyledText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(); + } + + public EditStyledText(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + public EditStyledText(Context context) { + super(context); + init(); + } + + /** + * Set Notifier. + */ + public void setNotifier(EditStyledTextNotifier estInterface) { + mESTInterface = estInterface; + } + + /** + * Set Builder for AlertDialog. + * + * @param builder + * Builder for opening Alert Dialog. + */ + public void setBuilder(Builder builder) { + mToast.setBuilder(builder); + } + + /** + * Set Parameters for ColorAlertDialog. + * + * @param colortitle + * Title for Alert Dialog. + * @param colornames + * List of name of selecting color. + * @param colorints + * List of int of color. + */ + public void setColorAlertParams(CharSequence colortitle, + CharSequence[] colornames, CharSequence[] colorints) { + mToast.setColorAlertParams(colortitle, colornames, colorints); + } + + /** + * Set Parameters for SizeAlertDialog. + * + * @param sizetitle + * Title for Alert Dialog. + * @param sizenames + * List of name of selecting size. + * @param sizedisplayints + * List of int of size displayed in TextView. + * @param sizesendints + * List of int of size exported to HTML. + */ + public void setSizeAlertParams(CharSequence sizetitle, + CharSequence[] sizenames, CharSequence[] sizedisplayints, + CharSequence[] sizesendints) { + mToast.setSizeAlertParams(sizetitle, sizenames, sizedisplayints, + sizesendints); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + final boolean superResult = super.onTouchEvent(event); + if (event.getAction() == MotionEvent.ACTION_UP) { + if (DBG) { + Log.d(LOG_TAG, "--- onTouchEvent"); + } + mManager.onTouchScreen(); + } + return superResult; + } + + /** + * Start editing. This function have to be called before other editing + * actions. + */ + public void onStartEdit() { + mManager.onStartEdit(); + } + + /** + * End editing. + */ + public void onEndEdit() { + mManager.onEndEdit(); + } + + /** + * Start "Copy" action. + */ + public void onStartCopy() { + mManager.onStartCopy(); + } + + /** + * Start "Paste" action. + */ + public void onStartPaste() { + mManager.onStartPaste(); + } + + /** + * Start changing "Size" action. + */ + public void onStartSize() { + mManager.onStartSize(); + } + + /** + * Start changing "Color" action. + */ + public void onStartColor() { + mManager.onStartColor(); + } + + /** + * Start "Select" action. + */ + public void onStartSelect() { + mManager.onStartSelect(); + } + + /** + * Start "SelectAll" action. + */ + public void onStartSelectAll() { + mManager.onStartSelectAll(); + } + + /** + * InsertImage to TextView by using URI + * + * @param uri + * URI of the iamge inserted to TextView. + */ + public void onInsertImage(Uri uri) { + mManager.onInsertImage(uri); + } + + /** + * InsertImage to TextView by using resource ID + * + * @param resId + * Resource ID of the iamge inserted to TextView. + */ + public void onInsertImage(int resId) { + mManager.onInsertImage(resId); + } + + /** + * Fix Selected Item. + */ + public void fixSelectedItem() { + mManager.onFixSelectItem(); + } + + /** + * Set Size of the Item. + * + * @param size + * The size of the Item. + */ + public void setItemSize(int size) { + mManager.setItemSize(size); + } + + /** + * Set Color of the Item. + * + * @param color + * The color of the Item. + */ + public void setItemColor(int color) { + mManager.setItemColor(color); + } + + public void onShowColorAlert() { + mToast.onShowColorAlertDialog(); + } + + public void onShowSizeAlert() { + mToast.onShowSizeAlertDialog(); + } + + /** + * Check editing is started. + * + * @return Whether editing is started or not. + */ + public boolean isEditting() { + return mManager.isEditting(); + } + + /** + * Get the mode of the action. + * + * @return The mode of the action. + */ + public int getEditMode() { + return mManager.getEditMode(); + } + + /** + * Get the state of the selection. + * + * @return The state of the selection. + */ + public int getSelectState() { + return mManager.getSelectState(); + } + + public String getBody() { + return mConverter.getConvertedBody(); + } + + /** + * Initialize members. + */ + private void init() { + if (DBG) { + Log.d(LOG_TAG, "--- init"); + requestFocus(); + } + mManager = new EditorManager(this); + mConverter = new StyledTextConverter(this); + mToast = new StyledTextToast(this); + } + + /** + * Notify hint messages what action is expected to calling class. + * + * @param msgId + * Id of the hint message. + */ + private void setHintMessage(int msgId) { + if (mESTInterface != null) { + mESTInterface.notifyHintMsg(msgId); + } + } + + @Override + public Bundle getInputExtras(boolean create) { + Bundle bundle = super.getInputExtras(create); + if (bundle != null) { + bundle.putBoolean("allowEmoji", true); + } + return bundle; + } + + /** + * Object which manages the flow and status of editing actions. + */ + private class EditorManager { + private boolean mEditFlag = false; + private int mMode = 0; + private int mState = 0; + private int mCurStart = 0; + private int mCurEnd = 0; + private EditStyledText mEST; + private Editable mTextSelectBuffer; + private CharSequence mTextCopyBufer; + + EditorManager(EditStyledText est) { + mEST = est; + } + + public void onStartEdit() { + if (DBG) { + Log.d(LOG_TAG, "--- onEdit"); + } + handleResetEdit(); + } + + public void onEndEdit() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickCancel"); + } + handleCancel(); + } + + public void onStartCopy() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickCopy"); + } + handleCopy(); + } + + public void onStartPaste() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickPaste"); + } + handlePaste(); + } + + public void onStartSize() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickSize"); + } + handleSize(); + } + + public void setItemSize(int size) { + if (DBG) { + Log.d(LOG_TAG, "--- onClickSizeItem"); + } + if (mState == STATE_SELECTED || mState == STATE_SELECT_FIX) { + changeSizeSelectedText(size); + handleResetEdit(); + } + } + + public void setItemColor(int color) { + if (DBG) { + Log.d(LOG_TAG, "--- onClickColorItem"); + } + if (mState == STATE_SELECTED || mState == STATE_SELECT_FIX) { + changeColorSelectedText(color); + handleResetEdit(); + } + } + + public void onStartColor() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickColor"); + } + handleColor(); + } + + public void onStartSelect() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickSelect"); + } + mMode = MODE_SELECT; + if (mState == STATE_SELECT_OFF) { + handleSelect(); + } else { + offSelect(); + handleSelect(); + } + } + + public void onStartSelectAll() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickSelectAll"); + } + handleSelectAll(); + } + + public void onTouchScreen() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickView"); + } + if (mState == STATE_SELECT_ON || mState == STATE_SELECTED) { + handleSelect(); + } + } + + public void onFixSelectItem() { + if (DBG) { + Log.d(LOG_TAG, "--- onClickComplete"); + } + handleComplete(); + } + + public void onInsertImage(Uri uri) { + if (DBG) { + Log.d(LOG_TAG, "--- onInsertImage by URI: " + uri.getPath() + + "," + uri.toString()); + } + + mEST.getText().append("a"); + mEST.getText().setSpan(new ImageSpan(mEST.getContext(), uri), + mEST.getText().length() - 1, mEST.getText().length(), + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + public void onInsertImage(int resID) { + if (DBG) { + Log.d(LOG_TAG, "--- onInsertImage by resID"); + } + mEST.getText().append("b"); + mEST.getText().setSpan(new ImageSpan(mEST.getContext(), resID), + mEST.getText().length() - 1, mEST.getText().length(), + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + public boolean isEditting() { + return mEditFlag; + } + + public int getEditMode() { + return mMode; + } + + public int getSelectState() { + return mState; + } + + private void handleCancel() { + if (DBG) { + Log.d(LOG_TAG, "--- handleCancel"); + } + mMode = MODE_NOTHING; + mState = STATE_SELECT_OFF; + mEditFlag = false; + offSelect(); + } + + private void handleComplete() { + if (DBG) { + Log.d(LOG_TAG, "--- handleComplete"); + } + if (!mEditFlag) { + return; + } + if (mState == STATE_SELECTED) { + mState = STATE_SELECT_FIX; + } + switch (mMode) { + case MODE_COPY: + handleCopy(); + break; + case MODE_COLOR: + handleColor(); + break; + case MODE_SIZE: + handleSize(); + break; + default: + break; + } + } + + private void handleCopy() { + if (DBG) { + Log.d(LOG_TAG, "--- handleCopy: " + mMode + "," + mState); + } + if (!mEditFlag) { + return; + } + if (mMode == MODE_NOTHING || mMode == MODE_SELECT) { + mMode = MODE_COPY; + if (mState == STATE_SELECTED) { + mState = STATE_SELECT_FIX; + storeSelectedText(); + } else { + handleSelect(); + } + } else if (mMode != MODE_COPY) { + handleCancel(); + mMode = MODE_COPY; + handleCopy(); + } else if (mState == STATE_SELECT_FIX) { + mEST.setHintMessage(HINT_MSG_NULL); + storeSelectedText(); + handleResetEdit(); + } + } + + private void handlePaste() { + if (DBG) { + Log.d(LOG_TAG, "--- handlePaste"); + } + if (!mEditFlag) { + return; + } + if (mTextSelectBuffer != null && mTextCopyBufer.length() > 0) { + mTextSelectBuffer.insert(mEST.getSelectionStart(), + mTextCopyBufer); + } else { + mEST.setHintMessage(HINT_MSG_COPY_BUF_BLANK); + } + } + + private void handleSize() { + if (DBG) { + Log.d(LOG_TAG, "--- handleSize: " + mMode + "," + mState); + } + if (!mEditFlag) { + Log.e(LOG_TAG, "--- Editing is not started for handlesize."); + return; + } + if (mMode == MODE_NOTHING || mMode == MODE_SELECT) { + mMode = MODE_SIZE; + if (mState == STATE_SELECTED) { + mState = STATE_SELECT_FIX; + handleSize(); + } else { + handleSelect(); + } + } else if (mMode != MODE_SIZE) { + handleCancel(); + mMode = MODE_SIZE; + handleSize(); + } else { + if (mState == STATE_SELECT_FIX) { + mEST.setHintMessage(HINT_MSG_NULL); + mEST.onShowSizeAlert(); + } else { + Log.d(LOG_TAG, "--- handlesize: do nothing"); + } + } + } + + private void handleColor() { + if (DBG) { + Log.d(LOG_TAG, "--- handleSize: " + mMode + "," + mState); + } + if (!mEditFlag) { + Log.e(LOG_TAG, "--- Editing is not started for handlecolor."); + return; + } + if (mMode == MODE_NOTHING || mMode == MODE_SELECT) { + mMode = MODE_COLOR; + if (mState == STATE_SELECTED) { + mState = STATE_SELECT_FIX; + handleColor(); + } else { + handleSelect(); + } + } else if (mMode != MODE_COLOR) { + handleCancel(); + mMode = MODE_COLOR; + handleSize(); + } else { + if (mState == STATE_SELECT_FIX) { + mEST.setHintMessage(HINT_MSG_NULL); + mEST.onShowColorAlert(); + } else { + Log.d(LOG_TAG, "--- handlecolor: do nothing"); + } + } + } + + private void handleSelect() { + if (DBG) { + Log.d(LOG_TAG, "--- handleSelect:" + mEditFlag + "," + mState); + } + if (!mEditFlag) { + return; + } + if (mState == STATE_SELECT_OFF) { + if (isTextSelected()) { + Log.e(LOG_TAG, "Selection is off, but selected"); + } + setSelectStartPos(); + mEST.setHintMessage(HINT_MSG_SELECT_END); + } else if (mState == STATE_SELECT_ON) { + if (isTextSelected()) { + Log.e(LOG_TAG, "Selection now start, but selected"); + } + setSelectEndPos(); + mEST.setHintMessage(HINT_MSG_PUSH_COMPETE); + doNextHandle(); + } else if (mState == STATE_SELECTED) { + if (!isTextSelected()) { + Log.e(LOG_TAG, "Selection is done, but not selected"); + } + setSelectEndPos(); + doNextHandle(); + } + } + + private void handleSelectAll() { + if (DBG) { + Log.d(LOG_TAG, "--- handleSelectAll"); + } + if (!mEditFlag) { + return; + } + mEST.selectAll(); + } + + private void doNextHandle() { + if (DBG) { + Log.d(LOG_TAG, "--- doNextHandle: " + mMode + "," + mState); + } + switch (mMode) { + case MODE_COPY: + handleCopy(); + break; + case MODE_PASTE: + handlePaste(); + break; + case MODE_SIZE: + handleSize(); + break; + case MODE_COLOR: + handleColor(); + break; + default: + break; + } + } + + private void handleResetEdit() { + if (DBG) { + Log.d(LOG_TAG, "Reset Editor"); + } + handleCancel(); + mEditFlag = true; + mEST.setHintMessage(HINT_MSG_SELECT_START); + } + + // Methods of selection + private void onSelect() { + if (DBG) { + Log.d(LOG_TAG, "--- onSelect:" + mCurStart + "," + mCurEnd); + } + if (mCurStart >= 0 && mCurStart <= mEST.getText().length() + && mCurEnd >= 0 && mCurEnd <= mEST.getText().length()) { + mEST.setSelection(mCurStart, mCurEnd); + mState = STATE_SELECTED; + } else { + Log.e(LOG_TAG, + "Select is on, but cursor positions are illigal.:" + + mEST.getText().length() + "," + mCurStart + + "," + mCurEnd); + } + } + + private void offSelect() { + if (DBG) { + Log.d(LOG_TAG, "--- offSelect"); + } + int currpos = mEST.getSelectionStart(); + mEST.setSelection(currpos, currpos); + mState = STATE_SELECT_OFF; + } + + private void setSelectStartPos() { + if (DBG) { + Log.d(LOG_TAG, "--- setSelectStartPos"); + } + mCurStart = mEST.getSelectionStart(); + mState = STATE_SELECT_ON; + } + + private void setSelectEndPos() { + if (DBG) { + Log.d(LOG_TAG, "--- setSelectEndPos:" + + mEST.getSelectionStart()); + } + int curpos = mEST.getSelectionStart(); + if (curpos < mCurStart) { + if (DBG) { + Log.d(LOG_TAG, "--- setSelectEndPos: swap is done."); + } + mCurEnd = mCurStart; + mCurStart = curpos; + } else { + mCurEnd = curpos; + } + onSelect(); + } + + private boolean isTextSelected() { + if (DBG) { + Log.d(LOG_TAG, "--- isTextSelected:" + mCurStart + "," + + mCurEnd); + } + return (mCurStart != mCurEnd) + && (mState == STATE_SELECTED || + mState == STATE_SELECT_FIX); + } + + private void storeSelectedText() { + if (DBG) { + Log.d(LOG_TAG, "--- storeSelectedText"); + } + mTextSelectBuffer = mEST.getText(); + mTextCopyBufer = mTextSelectBuffer.subSequence(mCurStart, mCurEnd); + } + + private void changeSizeSelectedText(int size) { + if (DBG) { + Log.d(LOG_TAG, "--- changeSizeSelectedText:" + size + "," + + mCurStart + "," + mCurEnd); + } + mEST.getText().setSpan(new AbsoluteSizeSpan(size), mCurStart, + mCurEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + private void changeColorSelectedText(int color) { + if (DBG) { + Log.d(LOG_TAG, "--- changeCollorSelectedText:" + color + "," + + mCurStart + "," + mCurEnd); + } + mEST.getText().setSpan(new ForegroundColorSpan(color), mCurStart, + mCurEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } + + private class StyledTextConverter { + private EditStyledText mEST; + + public StyledTextConverter(EditStyledText est) { + mEST = est; + } + + public String getConvertedBody() { + String htmlBody = Html.toHtml(mEST.getText()); + return htmlBody; + } + } + + private class StyledTextToast { + Builder mBuilder; + CharSequence mColorTitle; + CharSequence mSizeTitle; + CharSequence[] mColorNames; + CharSequence[] mColorInts; + CharSequence[] mSizeNames; + CharSequence[] mSizeDisplayInts; + CharSequence[] mSizeSendInts; + EditStyledText mEST; + + public StyledTextToast(EditStyledText est) { + mEST = est; + } + + public void setBuilder(Builder builder) { + mBuilder = builder; + } + + public void setColorAlertParams(CharSequence colortitle, + CharSequence[] colornames, CharSequence[] colorints) { + mColorTitle = colortitle; + mColorNames = colornames; + mColorInts = colorints; + } + + public void setSizeAlertParams(CharSequence sizetitle, + CharSequence[] sizenames, CharSequence[] sizedisplayints, + CharSequence[] sizesendints) { + mSizeTitle = sizetitle; + mSizeNames = sizenames; + mSizeDisplayInts = sizedisplayints; + mSizeSendInts = sizesendints; + } + + public boolean checkColorAlertParams() { + if (DBG) { + Log.d(LOG_TAG, "--- checkParams"); + } + if (mBuilder == null) { + Log.e(LOG_TAG, "--- builder is null."); + return false; + } else if (mColorTitle == null || mColorNames == null + || mColorInts == null) { + Log.e(LOG_TAG, "--- color alert params are null."); + return false; + } else if (mColorNames.length != mColorInts.length) { + Log.e(LOG_TAG, "--- the length of color alert params are " + + "different."); + return false; + } + return true; + } + + public boolean checkSizeAlertParams() { + if (DBG) { + Log.d(LOG_TAG, "--- checkParams"); + } + if (mBuilder == null) { + Log.e(LOG_TAG, "--- builder is null."); + } else if (mSizeTitle == null || mSizeNames == null + || mSizeDisplayInts == null || mSizeSendInts == null) { + Log.e(LOG_TAG, "--- size alert params are null."); + } else if (mSizeNames.length != mSizeDisplayInts.length + && mSizeSendInts.length != mSizeDisplayInts.length) { + Log.e(LOG_TAG, "--- the length of size alert params are " + + "different."); + } + return true; + } + + private void onShowColorAlertDialog() { + if (DBG) { + Log.d(LOG_TAG, "--- onShowAlertDialog"); + } + if (!checkColorAlertParams()) { + return; + } + mBuilder.setTitle(mColorTitle); + mBuilder.setIcon(0); + mBuilder. + setItems(mColorNames, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + Log.d("EETVM", "mBuilder.onclick:" + which); + int color = Integer.parseInt( + (String) mColorInts[which], 16) - 0x01000000; + mEST.setItemColor(color); + } + }); + mBuilder.show(); + } + + private void onShowSizeAlertDialog() { + if (DBG) { + Log.d(LOG_TAG, "--- onShowAlertDialog"); + } + if (!checkColorAlertParams()) { + return; + } + mBuilder.setTitle(mSizeTitle); + mBuilder.setIcon(0); + mBuilder. + setItems(mSizeNames, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + Log.d("EETVM", "mBuilder.onclick:" + which); + int size = Integer + .parseInt((String) mSizeDisplayInts[which]); + mEST.setItemSize(size); + } + }); + mBuilder.show(); + } + } +} diff --git a/core/java/com/android/internal/widget/EditableInputConnection.java b/core/java/com/android/internal/widget/EditableInputConnection.java index a2673a56b9491e0f1230181367b8571be204a398..f2ec0649860c52ced4dd3665f4181443d13dbddd 100644 --- a/core/java/com/android/internal/widget/EditableInputConnection.java +++ b/core/java/com/android/internal/widget/EditableInputConnection.java @@ -16,175 +16,87 @@ package com.android.internal.widget; -import android.content.res.TypedArray; import android.os.Bundle; -import android.os.Handler; import android.text.Editable; -import android.text.Selection; -import android.text.Spannable; -import android.text.SpannableStringBuilder; -import android.text.Spanned; -import android.text.TextUtils; import android.text.method.KeyListener; import android.util.Log; -import android.util.LogPrinter; import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.widget.TextView; -class ComposingText { -} - public class EditableInputConnection extends BaseInputConnection { private static final boolean DEBUG = false; private static final String TAG = "EditableInputConnection"; - public static final Object COMPOSING = new ComposingText(); - private final TextView mTextView; - private Object[] mDefaultComposingSpans; - public EditableInputConnection(TextView textview) { - super(textview); + super(textview, false); mTextView = textview; } - public static final void removeComposingSpans(Spannable text) { - text.removeSpan(COMPOSING); - Object[] sps = text.getSpans(0, text.length(), Object.class); - if (sps != null) { - for (int i=sps.length-1; i>=0; i--) { - Object o = sps[i]; - if ((text.getSpanFlags(o)&Spanned.SPAN_COMPOSING) != 0) { - text.removeSpan(o); - } - } - } - } - - public static void setComposingSpans(Spannable text) { - final Object[] sps = text.getSpans(0, text.length(), Object.class); - if (sps != null) { - for (int i=sps.length-1; i>=0; i--) { - final Object o = sps[i]; - if (o == COMPOSING) { - text.removeSpan(o); - continue; - } - final int fl = text.getSpanFlags(o); - if ((fl&(Spanned.SPAN_COMPOSING|Spanned.SPAN_POINT_MARK_MASK)) - != (Spanned.SPAN_COMPOSING|Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)) { - text.setSpan(o, text.getSpanStart(o), text.getSpanEnd(o), - (fl&Spanned.SPAN_POINT_MARK_MASK) - | Spanned.SPAN_COMPOSING - | Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - } - } + public Editable getEditable() { + TextView tv = mTextView; + if (tv != null) { + return tv.getEditableText(); } - - text.setSpan(COMPOSING, 0, text.length(), - Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING); - } - - public static int getComposingSpanStart(Spannable text) { - return text.getSpanStart(COMPOSING); + return null; } - public static int getComposingSpanEnd(Spannable text) { - return text.getSpanEnd(COMPOSING); + public boolean beginBatchEdit() { + mTextView.beginBatchEdit(); + return true; } - public boolean setComposingText(CharSequence text, int newCursorPosition) { - if (DEBUG) Log.v(TAG, "setComposingText " + text); - replaceText(text, newCursorPosition, true); + public boolean endBatchEdit() { + mTextView.endBatchEdit(); return true; } - - public boolean finishComposingText() { - if (DEBUG) Log.v(TAG, "finishComposingText"); + + public boolean clearMetaKeyStates(int states) { final Editable content = getEditable(); - if (content != null) { - removeComposingSpans(content); + if (content == null) return false; + KeyListener kl = mTextView.getKeyListener(); + if (kl != null) { + try { + kl.clearMetaKeyState(mTextView, content, states); + } catch (AbstractMethodError e) { + // This is an old listener that doesn't implement the + // new method. + } } return true; } - public boolean commitText(CharSequence text, int newCursorPosition) { - if (DEBUG) Log.v(TAG, "commitText " + text); - replaceText(text, newCursorPosition, false); - return true; - } - public boolean commitCompletion(CompletionInfo text) { if (DEBUG) Log.v(TAG, "commitCompletion " + text); + mTextView.beginBatchEdit(); mTextView.onCommitCompletion(text); + mTextView.endBatchEdit(); return true; } - public CharSequence getTextBeforeCursor(int length) { - final Editable content = getEditable(); - if (content == null) return null; - - int a = Selection.getSelectionStart(content); - int b = Selection.getSelectionEnd(content); - - if (a > b) { - int tmp = a; - a = b; - b = tmp; - } - - if (length > a) { - length = a; - } - - return content.subSequence(a - length, a); - } - - public CharSequence getTextAfterCursor(int length) { - final Editable content = getEditable(); - if (content == null) return null; - - int a = Selection.getSelectionStart(content); - int b = Selection.getSelectionEnd(content); - - if (a > b) { - int tmp = a; - a = b; - b = tmp; - } - - if (b + length > content.length()) { - length = content.length() - b; - } - - return content.subSequence(b, b + length); + public boolean performEditorAction(int actionCode) { + if (DEBUG) Log.v(TAG, "performEditorAction " + actionCode); + mTextView.onEditorAction(actionCode); + return true; } - - public int getCursorCapsMode(int reqModes) { - final Editable content = getEditable(); - if (content == null) return 0; - - int a = Selection.getSelectionStart(content); - int b = Selection.getSelectionEnd(content); - - if (a > b) { - int tmp = a; - a = b; - b = tmp; - } - - return TextUtils.getCapsMode(content, a, reqModes); + + public boolean performContextMenuAction(int id) { + if (DEBUG) Log.v(TAG, "performContextMenuAction " + id); + mTextView.beginBatchEdit(); + mTextView.onTextContextMenuItem(id); + mTextView.endBatchEdit(); + return true; } public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { if (mTextView != null) { ExtractedText et = new ExtractedText(); if (mTextView.extractText(request, et)) { - if ((flags&EXTRACTED_TEXT_MONITOR) != 0) { + if ((flags&GET_EXTRACTED_TEXT_MONITOR) != 0) { mTextView.setExtracting(request); } return et; @@ -193,173 +105,25 @@ public class EditableInputConnection extends BaseInputConnection { return null; } - public boolean deleteSurroundingText(int leftLength, int rightLength) { - if (DEBUG) Log.v(TAG, "deleteSurroundingText " + leftLength - + " / " + rightLength); - final Editable content = getEditable(); - if (content == null) return false; - - int a = Selection.getSelectionStart(content); - int b = Selection.getSelectionEnd(content); - - if (a > b) { - int tmp = a; - a = b; - b = tmp; - } - - // ignore the composing text. - int ca = content.getSpanStart(COMPOSING); - int cb = content.getSpanEnd(COMPOSING); - if (cb < ca) { - int tmp = ca; - ca = cb; - cb = tmp; - } - if (ca != -1 && cb != -1) { - if (ca < a) a = ca; - if (cb > b) b = cb; - } - - int deleted = 0; - - if (leftLength > 0) { - int start = a - leftLength; - if (start < 0) start = 0; - content.delete(start, a); - deleted = a - start; - } - - if (rightLength > 0) { - b = b - deleted; - - int end = b + rightLength; - if (end > content.length()) end = content.length(); - - content.delete(b, end); - } - - return true; - } - - public boolean beginBatchEdit() { - if (mTextView == null) return false; - mTextView.onBeginBatchEdit(); - return true; - } - - public boolean endBatchEdit() { - if (mTextView == null) return false; - mTextView.onEndBatchEdit(); - return true; - } - - public boolean clearMetaKeyStates(int states) { - final Editable content = getEditable(); - if (content == null) return false; - KeyListener kl = mTextView.getKeyListener(); - if (kl != null) kl.clearMetaKeyState(mTextView, content, states); - return true; - } - public boolean performPrivateCommand(String action, Bundle data) { - if (mTextView == null) return false; mTextView.onPrivateIMECommand(action, data); return true; } - - private Editable getEditable() { - TextView tv = mTextView; - if (tv != null) { - return tv.getEditableText(); - } - return null; - } - - private void replaceText(CharSequence text, int newCursorPosition, - boolean composing) { - final Editable content = getEditable(); - - // delete composing text set previously. - int a = content.getSpanStart(COMPOSING); - int b = content.getSpanEnd(COMPOSING); - if (DEBUG) Log.v(TAG, "Composing span: " + a + " to " + b); - - if (b < a) { - int tmp = a; - a = b; - b = tmp; + @Override + public boolean commitText(CharSequence text, int newCursorPosition) { + if (mTextView == null) { + return super.commitText(text, newCursorPosition); } - if (a != -1 && b != -1) { - removeComposingSpans(content); - } else { - a = Selection.getSelectionStart(content); - b = Selection.getSelectionEnd(content); - if (a >=0 && b>= 0 && a != b) { - if (b < a) { - int tmp = a; - a = b; - b = tmp; - } - } - } + CharSequence errorBefore = mTextView.getError(); + boolean success = super.commitText(text, newCursorPosition); + CharSequence errorAfter = mTextView.getError(); - if (composing) { - Spannable sp = null; - if (!(text instanceof Spannable)) { - sp = new SpannableStringBuilder(text); - text = sp; - if (mDefaultComposingSpans == null) { - TypedArray ta = mTextView.getContext().getTheme() - .obtainStyledAttributes(new int[] { - com.android.internal.R.attr.candidatesTextStyleSpans - }); - CharSequence style = ta.getText(0); - ta.recycle(); - if (style != null && style instanceof Spanned) { - mDefaultComposingSpans = ((Spanned)style).getSpans( - 0, style.length(), Object.class); - } - } - if (mDefaultComposingSpans != null) { - for (int i = 0; i < mDefaultComposingSpans.length; ++i) { - sp.setSpan(mDefaultComposingSpans[i], 0, sp.length(), - Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - } - } - } else { - sp = (Spannable)text; - } - setComposingSpans(sp); + if (errorAfter != null && errorBefore == errorAfter) { + mTextView.setError(null, null); } - - // Adjust newCursorPosition to be relative the start of the text. - newCursorPosition += a; - if (DEBUG) Log.v(TAG, "Replacing from " + a + " to " + b + " with \"" - + text + "\", composing=" + composing - + ", type=" + text.getClass().getCanonicalName()); - - if (DEBUG) { - LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG); - lp.println("Current text:"); - TextUtils.dumpSpans(content, lp, " "); - lp.println("Composing text:"); - TextUtils.dumpSpans(text, lp, " "); - } - - content.replace(a, b, text); - if (newCursorPosition < 0) newCursorPosition = 0; - if (newCursorPosition > content.length()) - newCursorPosition = content.length(); - Selection.setSelection(content, newCursorPosition); - - if (DEBUG) { - LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG); - lp.println("Final text:"); - TextUtils.dumpSpans(content, lp, " "); - } + return success; } } diff --git a/core/java/com/android/internal/widget/LockPatternUtils.java b/core/java/com/android/internal/widget/LockPatternUtils.java index ed1cd58c73850dff7a1c56f59fe42f082c1a5b88..f0b311cfaa83805bc6ca14713d8358a8ca8c10be 100644 --- a/core/java/com/android/internal/widget/LockPatternUtils.java +++ b/core/java/com/android/internal/widget/LockPatternUtils.java @@ -77,11 +77,11 @@ public class LockPatternUtils { public static final int MIN_PATTERN_REGISTER_FAIL = 3; private final static String LOCKOUT_PERMANENT_KEY = "lockscreen.lockedoutpermanently"; + private final static String LOCKOUT_ATTEMPT_DEADLINE = "lockscreen.lockoutattemptdeadline"; + private final static String PATTERN_EVER_CHOSEN = "lockscreen.patterneverchosen"; private final ContentResolver mContentResolver; - private long mLockoutDeadline = 0; - private static String sLockPatternFilename; /** @@ -139,6 +139,16 @@ public class LockPatternUtils { } } + /** + * Return true if the user has ever chosen a pattern. This is true even if the pattern is + * currently cleared. + * + * @return True if the user has ever chosen a pattern. + */ + public boolean isPatternEverChosen() { + return getBoolean(PATTERN_EVER_CHOSEN); + } + /** * Save a lock pattern. * @param pattern The new pattern to save. @@ -156,6 +166,7 @@ public class LockPatternUtils { raf.write(hash, 0, hash.length); } raf.close(); + setBoolean(PATTERN_EVER_CHOSEN, true); } catch (FileNotFoundException fnfe) { // Cant do much, unless we want to fail over to using the settings provider Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename); @@ -270,12 +281,14 @@ public class LockPatternUtils { } /** - * Store the lockout deadline, meaning the user can't attempt his/her unlock - * pattern until the deadline has passed. Does not persist across reboots. - * @param deadline The elapsed real time in millis in future. + * Set and store the lockout deadline, meaning the user can't attempt his/her unlock + * pattern until the deadline has passed. + * @return the chosen deadline. */ - public void setLockoutAttemptDeadline(long deadline) { - mLockoutDeadline = deadline; + public long setLockoutAttemptDeadline() { + final long deadline = SystemClock.elapsedRealtime() + FAILED_ATTEMPT_TIMEOUT_MS; + setLong(LOCKOUT_ATTEMPT_DEADLINE, deadline); + return deadline; } /** @@ -284,7 +297,12 @@ public class LockPatternUtils { * enter a pattern. */ public long getLockoutAttemptDeadline() { - return (mLockoutDeadline <= SystemClock.elapsedRealtime()) ? 0 : mLockoutDeadline; + final long deadline = getLong(LOCKOUT_ATTEMPT_DEADLINE, 0L); + final long now = SystemClock.elapsedRealtime(); + if (deadline < now || deadline > (now + FAILED_ATTEMPT_TIMEOUT_MS)) { + return 0L; + } + return deadline; } /** @@ -341,5 +359,13 @@ public class LockPatternUtils { enabled ? 1 : 0); } + private long getLong(String systemSettingKey, long def) { + return android.provider.Settings.System.getLong(mContentResolver, systemSettingKey, def); + } + + private void setLong(String systemSettingKey, long value) { + android.provider.Settings.System.putLong(mContentResolver, systemSettingKey, value); + } + } diff --git a/core/java/com/android/internal/widget/NumberPicker.java b/core/java/com/android/internal/widget/NumberPicker.java index 20ea6a6d287932081e5e3f2b9271733f6a807a6a..2f08c8dd424b491d7aa1c7c88d56e46974da6473 100644 --- a/core/java/com/android/internal/widget/NumberPicker.java +++ b/core/java/com/android/internal/widget/NumberPicker.java @@ -28,12 +28,9 @@ import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnLongClickListener; -import android.view.animation.Animation; -import android.view.animation.TranslateAnimation; -import android.widget.EditText; -import android.widget.LinearLayout; import android.widget.TextView; -import android.widget.ViewSwitcher; +import android.widget.LinearLayout; +import android.widget.EditText; import com.android.internal.R; @@ -71,25 +68,18 @@ public class NumberPicker extends LinearLayout implements OnClickListener, private final Runnable mRunnable = new Runnable() { public void run() { if (mIncrement) { - changeCurrent(mCurrent + 1, mSlideUpInAnimation, mSlideUpOutAnimation); + changeCurrent(mCurrent + 1); mHandler.postDelayed(this, mSpeed); } else if (mDecrement) { - changeCurrent(mCurrent - 1, mSlideDownInAnimation, mSlideDownOutAnimation); + changeCurrent(mCurrent - 1); mHandler.postDelayed(this, mSpeed); } } }; - - private final LayoutInflater mInflater; - private final TextView mText; - private final InputFilter mInputFilter; + + private final EditText mText; private final InputFilter mNumberInputFilter; - - private final Animation mSlideUpOutAnimation; - private final Animation mSlideUpInAnimation; - private final Animation mSlideDownOutAnimation; - private final Animation mSlideDownInAnimation; - + private String[] mDisplayedValues; private int mStart; private int mEnd; @@ -110,14 +100,14 @@ public class NumberPicker extends LinearLayout implements OnClickListener, this(context, attrs, 0); } - public NumberPicker(Context context, AttributeSet attrs, - int defStyle) { + @SuppressWarnings({"UnusedDeclaration"}) + public NumberPicker(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); setOrientation(VERTICAL); - mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - mInflater.inflate(R.layout.number_picker, this, true); + LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + inflater.inflate(R.layout.number_picker, this, true); mHandler = new Handler(); - mInputFilter = new NumberPickerInputFilter(); + InputFilter inputFilter = new NumberPickerInputFilter(); mNumberInputFilter = new NumberRangeKeyListener(); mIncrementButton = (NumberPickerButton) findViewById(R.id.increment); mIncrementButton.setOnClickListener(this); @@ -128,32 +118,11 @@ public class NumberPicker extends LinearLayout implements OnClickListener, mDecrementButton.setOnLongClickListener(this); mDecrementButton.setNumberPicker(this); - mText = (TextView) findViewById(R.id.timepicker_input); + mText = (EditText) findViewById(R.id.timepicker_input); mText.setOnFocusChangeListener(this); - mText.setFilters(new InputFilter[] { mInputFilter }); + mText.setFilters(new InputFilter[] {inputFilter}); mText.setRawInputType(InputType.TYPE_CLASS_NUMBER); - - mSlideUpOutAnimation = new TranslateAnimation( - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, - 0, Animation.RELATIVE_TO_SELF, 0, - Animation.RELATIVE_TO_SELF, -100); - mSlideUpOutAnimation.setDuration(200); - mSlideUpInAnimation = new TranslateAnimation( - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, - 0, Animation.RELATIVE_TO_SELF, 100, - Animation.RELATIVE_TO_SELF, 0); - mSlideUpInAnimation.setDuration(200); - mSlideDownOutAnimation = new TranslateAnimation( - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, - 0, Animation.RELATIVE_TO_SELF, 0, - Animation.RELATIVE_TO_SELF, 100); - mSlideDownOutAnimation.setDuration(200); - mSlideDownInAnimation = new TranslateAnimation( - Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, - 0, Animation.RELATIVE_TO_SELF, -100, - Animation.RELATIVE_TO_SELF, 0); - mSlideDownInAnimation.setDuration(200); - + if (!isEnabled()) { setEnabled(false); } @@ -220,17 +189,14 @@ public class NumberPicker extends LinearLayout implements OnClickListener, } public void onClick(View v) { - - /* The text view may still have focus so clear it's focus which will - * trigger the on focus changed and any typed values to be pulled. - */ - mText.clearFocus(); + validateInput(mText); + if (!mText.hasFocus()) mText.requestFocus(); // now perform the increment/decrement if (R.id.increment == v.getId()) { - changeCurrent(mCurrent + 1, mSlideUpInAnimation, mSlideUpOutAnimation); + changeCurrent(mCurrent + 1); } else if (R.id.decrement == v.getId()) { - changeCurrent(mCurrent - 1, mSlideDownInAnimation, mSlideDownOutAnimation); + changeCurrent(mCurrent - 1); } } @@ -240,7 +206,7 @@ public class NumberPicker extends LinearLayout implements OnClickListener, : String.valueOf(value); } - private void changeCurrent(int current, Animation in, Animation out) { + private void changeCurrent(int current) { // Wrap around the values if we go past the start or end if (current > mEnd) { @@ -271,6 +237,7 @@ public class NumberPicker extends LinearLayout implements OnClickListener, } else { mText.setText(mDisplayedValues[mCurrent - mStart]); } + mText.setSelection(mText.getText().length()); } private void validateCurrentView(CharSequence str) { @@ -289,16 +256,20 @@ public class NumberPicker extends LinearLayout implements OnClickListener, * has valid values. */ if (!hasFocus) { - String str = String.valueOf(((TextView) v).getText()); - if ("".equals(str)) { - - // Restore to the old value as we don't allow empty values - updateView(); - } else { - - // Check the new value and ensure it's in range - validateCurrentView(str); - } + validateInput(v); + } + } + + private void validateInput(View v) { + String str = String.valueOf(((TextView) v).getText()); + if ("".equals(str)) { + + // Restore to the old value as we don't allow empty values + updateView(); + } else { + + // Check the new value and ensure it's in range + validateCurrentView(str); } } diff --git a/core/java/com/android/internal/widget/TextProgressBar.java b/core/java/com/android/internal/widget/TextProgressBar.java new file mode 100644 index 0000000000000000000000000000000000000000..aee7b769cad58506573d724379697ddea03382d8 --- /dev/null +++ b/core/java/com/android/internal/widget/TextProgressBar.java @@ -0,0 +1,180 @@ +/* + * 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. + */ + +package com.android.internal.widget; + +import android.content.Context; +import android.os.SystemClock; +import android.util.AttributeSet; +import android.util.Log; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Chronometer; +import android.widget.Chronometer.OnChronometerTickListener; +import android.widget.ProgressBar; +import android.widget.RelativeLayout; +import android.widget.RemoteViews.RemoteView; + +/** + * Container that links together a {@link ProgressBar} and {@link Chronometer} + * as children. It subscribes to {@link Chronometer#OnChronometerTickListener} + * and updates the {@link ProgressBar} based on a preset finishing time. + *

          + * This widget expects to contain two children with specific ids + * {@link android.R.id.progress} and {@link android.R.id.text1}. + *

          + * If the {@link Chronometer} {@link android.R.attr#layout_width} is + * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, then the + * {@link android.R.attr#gravity} will be used to automatically move it with + * respect to the {@link ProgressBar} position. For example, if + * {@link android.view.Gravity#LEFT} then the {@link Chronometer} will be placed + * just ahead of the leading edge of the {@link ProgressBar} position. + */ +@RemoteView +public class TextProgressBar extends RelativeLayout implements OnChronometerTickListener { + public static final String TAG = "TextProgressBar"; + + static final int CHRONOMETER_ID = android.R.id.text1; + static final int PROGRESSBAR_ID = android.R.id.progress; + + Chronometer mChronometer = null; + ProgressBar mProgressBar = null; + + long mDurationBase = -1; + int mDuration = -1; + + boolean mChronometerFollow = false; + int mChronometerGravity = Gravity.NO_GRAVITY; + + public TextProgressBar(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + public TextProgressBar(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public TextProgressBar(Context context) { + super(context); + } + + /** + * Catch any interesting children when they are added. + */ + @Override + public void addView(View child, int index, ViewGroup.LayoutParams params) { + super.addView(child, index, params); + + int childId = child.getId(); + if (childId == CHRONOMETER_ID && child instanceof Chronometer) { + mChronometer = (Chronometer) child; + mChronometer.setOnChronometerTickListener(this); + + // Check if Chronometer should move with with ProgressBar + mChronometerFollow = (params.width == ViewGroup.LayoutParams.WRAP_CONTENT); + mChronometerGravity = (mChronometer.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK); + + } else if (childId == PROGRESSBAR_ID && child instanceof ProgressBar) { + mProgressBar = (ProgressBar) child; + } + } + + /** + * Set the expected termination time of the running {@link Chronometer}. + * This value is used to adjust the {@link ProgressBar} against the elapsed + * time. + *

          + * Call this after adjusting the {@link Chronometer} base, if + * necessary. + * + * @param durationBase Use the {@link SystemClock#elapsedRealtime} time + * base. + */ + @android.view.RemotableViewMethod + public void setDurationBase(long durationBase) { + mDurationBase = durationBase; + + if (mProgressBar == null || mChronometer == null) { + throw new RuntimeException("Expecting child ProgressBar with id " + + "'android.R.id.progress' and Chronometer id 'android.R.id.text1'"); + } + + // Update the ProgressBar maximum relative to Chronometer base + mDuration = (int) (durationBase - mChronometer.getBase()); + if (mDuration <= 0) { + mDuration = 1; + } + mProgressBar.setMax(mDuration); + } + + /** + * Callback when {@link Chronometer} changes, indicating that we should + * update the {@link ProgressBar} and change the layout if necessary. + */ + public void onChronometerTick(Chronometer chronometer) { + if (mProgressBar == null) { + throw new RuntimeException( + "Expecting child ProgressBar with id 'android.R.id.progress'"); + } + + // Stop Chronometer if we're past duration + long now = SystemClock.elapsedRealtime(); + if (now >= mDurationBase) { + mChronometer.stop(); + } + + // Update the ProgressBar status + int remaining = (int) (mDurationBase - now); + mProgressBar.setProgress(mDuration - remaining); + + // Move the Chronometer if gravity is set correctly + if (mChronometerFollow) { + RelativeLayout.LayoutParams params; + + // Calculate estimate of ProgressBar leading edge position + params = (RelativeLayout.LayoutParams) mProgressBar.getLayoutParams(); + int contentWidth = mProgressBar.getWidth() - (params.leftMargin + params.rightMargin); + int leadingEdge = ((contentWidth * mProgressBar.getProgress()) / + mProgressBar.getMax()) + params.leftMargin; + + // Calculate any adjustment based on gravity + int adjustLeft = 0; + int textWidth = mChronometer.getWidth(); + if (mChronometerGravity == Gravity.RIGHT) { + adjustLeft = -textWidth; + } else if (mChronometerGravity == Gravity.CENTER_HORIZONTAL) { + adjustLeft = -(textWidth / 2); + } + + // Limit margin to keep text inside ProgressBar bounds + leadingEdge += adjustLeft; + int rightLimit = contentWidth - params.rightMargin - textWidth; + if (leadingEdge < params.leftMargin) { + leadingEdge = params.leftMargin; + } else if (leadingEdge > rightLimit) { + leadingEdge = rightLimit; + } + + params = (RelativeLayout.LayoutParams) mChronometer.getLayoutParams(); + params.leftMargin = leadingEdge; + + // Request layout to move Chronometer + mChronometer.requestLayout(); + + } + } +} diff --git a/core/java/com/google/android/gdata/client/AndroidGDataClient.java b/core/java/com/google/android/gdata/client/AndroidGDataClient.java index 1d8e9c5c1d7d48bbbdd9b34973f8776fd57dd622..fe7d8601c2e02333860c3f4491cee7c6df9a7d6e 100644 --- a/core/java/com/google/android/gdata/client/AndroidGDataClient.java +++ b/core/java/com/google/android/gdata/client/AndroidGDataClient.java @@ -21,6 +21,7 @@ import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.AbstractHttpEntity; import android.content.ContentResolver; +import android.content.Context; import android.net.http.AndroidHttpClient; import android.text.TextUtils; import android.util.Config; @@ -117,10 +118,7 @@ public class AndroidGDataClient implements GDataClient { } /** - * Creates a new AndroidGDataClient. - * - * @param resolver The ContentResolver to get URL rewriting rules from - * through the Android proxy server, using null to indicate not using proxy. + * @deprecated Use AndroidGDAtaClient(Context) instead. */ public AndroidGDataClient(ContentResolver resolver) { mHttpClient = new GoogleHttpClient(resolver, USER_AGENT_APP_VERSION, @@ -129,6 +127,21 @@ public class AndroidGDataClient implements GDataClient { mResolver = resolver; } + /** + * Creates a new AndroidGDataClient. + * + * @param context The ContentResolver to get URL rewriting rules from + * through the Android proxy server, using null to indicate not using proxy. + * The context will also be used by GoogleHttpClient for configuration of + * SSL session persistence. + */ + public AndroidGDataClient(Context context) { + mHttpClient = new GoogleHttpClient(context, USER_AGENT_APP_VERSION, + true /* gzip capable */); + mHttpClient.enableCurlLogging(TAG, Log.VERBOSE); + mResolver = context.getContentResolver(); + } + public void close() { mHttpClient.close(); } diff --git a/core/java/com/google/android/net/GoogleHttpClient.java b/core/java/com/google/android/net/GoogleHttpClient.java index 4656aff15bc13ec7b5f7e53c87693005378d882a..ac9ad733348e45c5baac4603fd3880764c28625b 100644 --- a/core/java/com/google/android/net/GoogleHttpClient.java +++ b/core/java/com/google/android/net/GoogleHttpClient.java @@ -16,44 +16,44 @@ package com.google.android.net; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.net.http.AndroidHttpClient; +import android.os.Build; +import android.os.NetStat; +import android.os.SystemClock; +import android.provider.Checkin; +import android.util.Config; +import android.util.Log; +import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.ProtocolException; -import org.apache.http.impl.client.RequestWrapper; -import org.apache.http.impl.client.EntityEnclosingRequestWrapper; -import org.apache.http.client.HttpClient; import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.impl.client.EntityEnclosingRequestWrapper; +import org.apache.http.impl.client.RequestWrapper; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.os.SystemClock; -import android.os.Build; -import android.net.http.AndroidHttpClient; -import android.provider.Checkin; -import android.util.Config; -import android.util.Log; - /** * {@link AndroidHttpClient} wrapper that uses {@link UrlRules} to rewrite URLs * and otherwise tweak HTTP requests. */ public class GoogleHttpClient implements HttpClient { - private static final String TAG = "GoogleHttpClient"; - private final AndroidHttpClient mClient; - private final ContentResolver mResolver; - private final String mUserAgent; + private static final String TAG = "GoogleHttpClient"; /** Exception thrown when a request is blocked by the URL rules. */ public static class BlockedRequestException extends IOException { @@ -64,11 +64,15 @@ public class GoogleHttpClient implements HttpClient { } } + private final AndroidHttpClient mClient; + private final ContentResolver mResolver; + private final String mUserAgent; + /** * Create an HTTP client. Normally one client is shared throughout an app. * @param resolver to use for accessing URL rewriting rules. * @param userAgent to report in your HTTP requests. - * @deprecated Use {@link #GoogleHttpClient(android.content.ContentResolver, String, boolean)} + * @deprecated Use {@link #GoogleHttpClient(android.content.ContentResolver, String, boolean)} */ public GoogleHttpClient(ContentResolver resolver, String userAgent) { mClient = AndroidHttpClient.newInstance(userAgent); @@ -76,6 +80,17 @@ public class GoogleHttpClient implements HttpClient { mUserAgent = userAgent; } + /** + * GoogleHttpClient(Context, String, boolean) - without SSL session + * persistence. + * + * @deprecated use Context instead of ContentResolver. + */ + public GoogleHttpClient(ContentResolver resolver, String appAndVersion, + boolean gzipCapable) { + this(resolver, null /* cache */, appAndVersion, gzipCapable); + } + /** * Create an HTTP client. Normaly this client is shared throughout an app. * The HTTP client will construct its User-Agent as follows: @@ -85,7 +100,10 @@ public class GoogleHttpClient implements HttpClient { * ( ); gzip * (if gzip capable) * - * @param resolver to use for acccessing URL rewriting rules. + * The context has settings for URL rewriting rules and is used to enable + * SSL session persistence. + * + * @param context application context. * @param appAndVersion Base app and version to use in the User-Agent. * e.g., "MyApp/1.0" * @param gzipCapable Whether or not this client is able to consume gzip'd @@ -93,14 +111,19 @@ public class GoogleHttpClient implements HttpClient { * headers. Needed because Google servers require gzip in the User-Agent * in order to return gzip'd content. */ - public GoogleHttpClient(ContentResolver resolver, String appAndVersion, - boolean gzipCapable) { - String userAgent = appAndVersion - + " (" + Build.DEVICE + " " + Build.ID + ")"; + public GoogleHttpClient(Context context, String appAndVersion, + boolean gzipCapable) { + this(context.getContentResolver(), SSLClientSessionCacheFactory.getCache(context), + appAndVersion, gzipCapable); + } + + private GoogleHttpClient(ContentResolver resolver, SSLClientSessionCache cache, + String appAndVersion, boolean gzipCapable) { + String userAgent = appAndVersion + " (" + Build.DEVICE + " " + Build.ID + ")"; if (gzipCapable) { userAgent = userAgent + "; gzip"; } - mClient = AndroidHttpClient.newInstance(userAgent); + mClient = AndroidHttpClient.newInstance(userAgent, cache); mResolver = resolver; mUserAgent = userAgent; } @@ -120,8 +143,37 @@ public class GoogleHttpClient implements HttpClient { String code = "Error"; long start = SystemClock.elapsedRealtime(); try { - HttpResponse response = mClient.execute(request, context); - code = Integer.toString(response.getStatusLine().getStatusCode()); + HttpResponse response; + // TODO: if we're logging network stats, and if the apache library is configured + // to follow redirects, count each redirect as an additional round trip. + + // see if we're logging network stats. + boolean logNetworkStats = NetworkStatsEntity.shouldLogNetworkStats(); + + if (logNetworkStats) { + int uid = android.os.Process.myUid(); + long startTx = NetStat.getUidTxBytes(uid); + long startRx = NetStat.getUidRxBytes(uid); + + response = mClient.execute(request, context); + code = Integer.toString(response.getStatusLine().getStatusCode()); + + HttpEntity origEntity = response == null ? null : response.getEntity(); + if (origEntity != null) { + // yeah, we compute the same thing below. we do need to compute this here + // so we can wrap the HttpEntity in the response. + long now = SystemClock.elapsedRealtime(); + long elapsed = now - start; + NetworkStatsEntity entity = new NetworkStatsEntity(origEntity, + mUserAgent, uid, startTx, startRx, + elapsed /* response latency */, now /* processing start time */); + response.setEntity(entity); + } + } else { + response = mClient.execute(request, context); + code = Integer.toString(response.getStatusLine().getStatusCode()); + } + return response; } catch (IOException e) { code = "IOException"; diff --git a/core/java/com/google/android/net/NetStats.java b/core/java/com/google/android/net/NetStats.java deleted file mode 100644 index fee821989a56f8e22112b19a5473727398e4ce9f..0000000000000000000000000000000000000000 --- a/core/java/com/google/android/net/NetStats.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.google.android.net; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.NoSuchElementException; -import java.util.StringTokenizer; - -/** - * Gets network send/receive statistics for this process. - * The statistics come from /proc/pid/stat, using the ATOP kernel modification. - */ -public class NetStats { - private static String statsFile = "/proc/" + android.os.Process.myPid() + "/stat"; - - private static String TAG = "netstat"; - - /** - * Returns network stats for this process. - * Returns stats of 0 if problem encountered. - * - * @return [bytes sent, bytes received] - */ - public static long[] getStats() { - long result[] = new long[2]; - - try { - BufferedReader br = new BufferedReader(new FileReader(statsFile), 512); - String line = br.readLine(); // Skip first line - line = br.readLine(); - StringTokenizer st = new StringTokenizer(line); - st.nextToken(); // disk read - st.nextToken(); // disk sectors - st.nextToken(); // disk write - st.nextToken(); // disk sectors - st.nextToken(); // tcp send - result[0] = Long.parseLong(st.nextToken()); // tcp bytes sent - st.nextToken(); //tcp recv - result[1] = Long.parseLong(st.nextToken()); // tcp bytes recv - } catch (IOException e) { - // Probably wrong kernel; no point logging exception - } catch (NoSuchElementException e) { - } catch (NullPointerException e) { - } - return result; - } -} diff --git a/core/java/com/google/android/net/NetworkStatsEntity.java b/core/java/com/google/android/net/NetworkStatsEntity.java new file mode 100644 index 0000000000000000000000000000000000000000..f5d2349ed417cb41a54f42b99dbc11e56667ddec --- /dev/null +++ b/core/java/com/google/android/net/NetworkStatsEntity.java @@ -0,0 +1,85 @@ +/* + * 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. + */ + +package com.google.android.net; + +import android.os.NetStat; +import android.os.SystemClock; +import android.os.SystemProperties; +import android.util.EventLog; + +import org.apache.http.HttpEntity; +import org.apache.http.entity.HttpEntityWrapper; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; + + +public class NetworkStatsEntity extends HttpEntityWrapper { + + private static final int HTTP_STATS_EVENT = 52001; + + private class NetworkStatsInputStream extends FilterInputStream { + + public NetworkStatsInputStream(InputStream wrapped) { + super(wrapped); + } + + @Override + public void close() throws IOException { + try { + super.close(); + } finally { + long processingTime = SystemClock.elapsedRealtime() - mProcessingStartTime; + long tx = NetStat.getUidTxBytes(mUid); + long rx = NetStat.getUidRxBytes(mUid); + + EventLog.writeEvent(HTTP_STATS_EVENT, mUa, mResponseLatency, processingTime, + tx - mStartTx, rx - mStartRx); + } + } + } + + private final String mUa; + private final int mUid; + private final long mStartTx; + private final long mStartRx; + private final long mResponseLatency; + private final long mProcessingStartTime; + + public NetworkStatsEntity(HttpEntity orig, String ua, + int uid, long startTx, long startRx, long responseLatency, + long processingStartTime) { + super(orig); + this.mUa = ua; + this.mUid = uid; + this.mStartTx = startTx; + this.mStartRx = startRx; + this.mResponseLatency = responseLatency; + this.mProcessingStartTime = processingStartTime; + } + + public static boolean shouldLogNetworkStats() { + return "1".equals(SystemProperties.get("googlehttpclient.logstats")); + } + + @Override + public InputStream getContent() throws IOException { + InputStream orig = super.getContent(); + return new NetworkStatsInputStream(orig); + } +} diff --git a/core/java/com/google/android/net/SSLClientSessionCacheFactory.java b/core/java/com/google/android/net/SSLClientSessionCacheFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..6570a9bde3c3ef804db96a9095e6ffa35e60b8cb --- /dev/null +++ b/core/java/com/google/android/net/SSLClientSessionCacheFactory.java @@ -0,0 +1,62 @@ +package com.google.android.net; + +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; +import org.apache.harmony.xnet.provider.jsse.FileClientSessionCache; +import android.content.Context; +import android.provider.Settings; +import android.util.Log; + +import java.io.File; +import java.io.IOException; + +import com.android.internal.net.DbSSLSessionCache; + +/** + * Factory that returns the appropriate implementation of a {@link SSLClientSessionCache} based + * on gservices. + * + * @hide + */ +// TODO: return a proxied implementation that is updated as the gservices value changes. +public final class SSLClientSessionCacheFactory { + + private static final String TAG = "SSLClientSessionCacheFactory"; + + public static final String DB = "db"; + public static final String FILE = "file"; + + // utility class + private SSLClientSessionCacheFactory() {} + + /** + * Returns a new {@link SSLClientSessionCache} based on the persistent cache that's specified, + * if any, in gservices. If no cache is specified, returns null. + * @param context The application context used for the per-process persistent cache. + * @return A new {@link SSLClientSessionCache}, or null if no persistent cache is configured. + */ + public static SSLClientSessionCache getCache(Context context) { + String type = Settings.Gservices.getString(context.getContentResolver(), + Settings.Gservices.SSL_SESSION_CACHE); + + if (type != null) { + if (DB.equals(type)) { + return DbSSLSessionCache.getInstanceForPackage(context); + } else if (FILE.equals(type)) { + File dir = context.getFilesDir(); + File cacheDir = new File(dir, "sslcache"); + if (!cacheDir.exists()) { + cacheDir.mkdir(); + } + try { + return FileClientSessionCache.usingDirectory(cacheDir); + } catch (IOException ioe) { + Log.w(TAG, "Unable to create FileClientSessionCache in " + cacheDir.getName(), ioe); + return null; + } + } else { + Log.w(TAG, "Ignoring unrecognized type: '" + type + "'"); + } + } + return null; + } +} diff --git a/core/java/com/google/android/util/GoogleWebContentHelper.java b/core/java/com/google/android/util/GoogleWebContentHelper.java index 7500ec3b0db9eabca5b584b48356ad97844ee8bf..291142008934ff09c8f21f664c12759fc1962068 100644 --- a/core/java/com/google/android/util/GoogleWebContentHelper.java +++ b/core/java/com/google/android/util/GoogleWebContentHelper.java @@ -206,7 +206,7 @@ public class GoogleWebContentHelper { WebSettings settings = mWebView.getSettings(); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); - mProgressBar = mLayout.findViewById(com.android.internal.R.id.progress); + mProgressBar = mLayout.findViewById(com.android.internal.R.id.progressContainer); TextView message = (TextView) mProgressBar.findViewById(com.android.internal.R.id.message); message.setText(com.android.internal.R.string.googlewebcontenthelper_loading); diff --git a/core/java/com/google/android/util/SimplePullParser.java b/core/java/com/google/android/util/SimplePullParser.java index 95f2ddb7f345035b0ed020c2eef67d7a456478bc..031790b9cf2f5a366c4aa9581e92f039913543a5 100644 --- a/core/java/com/google/android/util/SimplePullParser.java +++ b/core/java/com/google/android/util/SimplePullParser.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.Reader; +import java.io.Closeable; import android.util.Xml; import android.util.Log; @@ -41,6 +42,7 @@ public class SimplePullParser { private String mLogTag = null; private final XmlPullParser mParser; + private Closeable source; private String mCurrentStartTag; /** @@ -56,6 +58,7 @@ public class SimplePullParser { moveToStartDocument(parser); mParser = parser; mCurrentStartTag = null; + source = stream; } catch (XmlPullParserException e) { throw new ParseException(e); } @@ -68,6 +71,7 @@ public class SimplePullParser { public SimplePullParser(XmlPullParser parser) { mParser = parser; mCurrentStartTag = null; + source = null; } /** @@ -89,6 +93,7 @@ public class SimplePullParser { moveToStartDocument(parser); mParser = parser; mCurrentStartTag = null; + source = reader; } catch (XmlPullParserException e) { throw new ParseException(e); } @@ -171,6 +176,12 @@ public class SimplePullParser { } if (eventType == XmlPullParser.END_DOCUMENT && parentDepth == 0) { + // we could just rely on the caller calling close(), which it should, but try + // to auto-close for clients that might have missed doing so. + if (source != null) { + source.close(); + source = null; + } return null; } @@ -332,6 +343,20 @@ public class SimplePullParser { } } + /** + * Close this SimplePullParser and any underlying resources (e.g., its InputStream or + * Reader source) used by this SimplePullParser. + */ + public void close() { + if (source != null) { + try { + source.close(); + } catch (IOException ioe) { + // ignore + } + } + } + /** * Returns the string value of the named attribute. An exception will * be thrown if the attribute is not present or is not a valid long. diff --git a/core/jni/Android.mk b/core/jni/Android.mk index 4452b79582e9976a868cb718f3cdccdbb0b55a62..18f2878ad5ad1ad271667e7cce3e712301ee75b4 100644 --- a/core/jni/Android.mk +++ b/core/jni/Android.mk @@ -27,6 +27,7 @@ LOCAL_SRC_FILES:= \ android_database_SQLiteProgram.cpp \ android_database_SQLiteQuery.cpp \ android_database_SQLiteStatement.cpp \ + android_emoji_EmojiFactory.cpp \ android_view_Display.cpp \ android_view_Surface.cpp \ android_view_ViewRoot.cpp \ @@ -42,7 +43,6 @@ LOCAL_SRC_FILES:= \ android_os_SystemClock.cpp \ android_os_SystemProperties.cpp \ android_os_UEventObserver.cpp \ - android_os_NetStat.cpp \ android_os_Hardware.cpp \ android_net_LocalSocketImpl.cpp \ android_net_NetUtils.cpp \ @@ -133,6 +133,7 @@ LOCAL_C_INCLUDES += \ external/tremor/Tremor \ external/icu4c/i18n \ external/icu4c/common \ + frameworks/opt/emoji LOCAL_SHARED_LIBRARIES := \ libexpat \ @@ -146,7 +147,8 @@ LOCAL_SHARED_LIBRARIES := \ libcorecg \ libsqlite \ libdvm \ - libGLES_CM \ + libEGL \ + libGLESv1_CM \ libhardware \ libhardware_legacy \ libsonivox \ @@ -156,13 +158,13 @@ LOCAL_SHARED_LIBRARIES := \ libicui18n \ libicudata \ libmedia \ - libwpa_client + libwpa_client \ + libemoji ifeq ($(BOARD_HAVE_BLUETOOTH),true) LOCAL_C_INCLUDES += \ external/dbus \ - external/bluez/libs/include \ - system/bluetooth/bluedroid/include + system/bluetooth/bluez-clean-headers LOCAL_CFLAGS += -DHAVE_BLUETOOTH LOCAL_SHARED_LIBRARIES += libbluedroid libdbus endif @@ -191,5 +193,4 @@ LOCAL_MODULE:= libandroid_runtime include $(BUILD_SHARED_LIBRARY) - include $(call all-makefiles-under,$(LOCAL_PATH)) diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp index 097ffac2cf371bef1ca9817ea19409ebd5e9387e..f4643f4dbcd4f410d0783525ff7d3a75dd77923f 100644 --- a/core/jni/AndroidRuntime.cpp +++ b/core/jni/AndroidRuntime.cpp @@ -92,6 +92,7 @@ extern int register_android_util_EventLog(JNIEnv* env); extern int register_android_util_Log(JNIEnv* env); extern int register_android_content_StringBlock(JNIEnv* env); extern int register_android_content_XmlBlock(JNIEnv* env); +extern int register_android_emoji_EmojiFactory(JNIEnv* env); extern int register_android_graphics_Canvas(JNIEnv* env); extern int register_android_graphics_ColorFilter(JNIEnv* env); extern int register_android_graphics_DrawFilter(JNIEnv* env); @@ -129,7 +130,6 @@ extern int register_android_os_SystemClock(JNIEnv* env); extern int register_android_os_FileObserver(JNIEnv *env); extern int register_android_os_FileUtils(JNIEnv *env); extern int register_android_os_UEventObserver(JNIEnv* env); -extern int register_android_os_NetStat(JNIEnv* env); extern int register_android_os_MemoryFile(JNIEnv* env); extern int register_android_net_LocalSocketImpl(JNIEnv* env); extern int register_android_net_NetworkUtils(JNIEnv* env); @@ -220,7 +220,7 @@ int register_com_android_internal_os_RuntimeInit(JNIEnv* env) AndroidRuntime::AndroidRuntime() { - SkGraphics::Init(false); // true means run unittests (slow) + SkGraphics::Init(); // this sets our preference for 16bit images during decode // in case the src is opaque and 24bit SkImageDecoder::SetDeviceConfig(SkBitmap::kRGB_565_Config); @@ -502,6 +502,7 @@ void AndroidRuntime::start(const char* className, const bool startSystemServer) JavaVMOption opt; char propBuf[PROPERTY_VALUE_MAX]; char stackTraceFileBuf[PROPERTY_VALUE_MAX]; + char dexoptFlagsBuf[PROPERTY_VALUE_MAX]; char enableAssertBuf[sizeof("-ea:")-1 + PROPERTY_VALUE_MAX]; char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX]; char* stackTraceFile = NULL; @@ -509,7 +510,6 @@ void AndroidRuntime::start(const char* className, const bool startSystemServer) char* cp; bool checkJni = false; bool logStdio = false; - bool verifyJava = true; enum { kEMDefault, kEMIntPortable, kEMIntFast } executionMode = kEMDefault; blockSigpipe(); @@ -536,15 +536,6 @@ void AndroidRuntime::start(const char* className, const bool startSystemServer) } } - property_get("dalvik.vm.verify-bytecode", propBuf, ""); - if (strcmp(propBuf, "true") == 0) { - verifyJava = true; - } else if (strcmp(propBuf, "false") == 0) { - verifyJava = false; - } else { - /* bad value or not defined; use default */ - } - property_get("dalvik.vm.execution-mode", propBuf, ""); if (strcmp(propBuf, "int:portable") == 0) { executionMode = kEMIntPortable; @@ -609,21 +600,49 @@ void AndroidRuntime::start(const char* className, const bool startSystemServer) mOptions.add(opt); /* - * Enable or disable bytecode verification. - * - * We don't optimize classes that haven't been verified, but that only - * matters if we do "just-in-time" DEX optimization. + * Enable or disable dexopt features, such as bytecode verification and + * calculation of register maps for precise GC. */ - if (verifyJava) { - opt.optionString = "-Xverify:all"; - mOptions.add(opt); - opt.optionString = "-Xdexopt:verified"; - mOptions.add(opt); - } else { - opt.optionString = "-Xverify:none"; - mOptions.add(opt); - opt.optionString = "-Xdexopt:verified"; - mOptions.add(opt); + property_get("dalvik.vm.dexopt-flags", dexoptFlagsBuf, ""); + if (dexoptFlagsBuf[0] != '\0') { + const char* opc; + const char* val; + + opc = strstr(dexoptFlagsBuf, "v="); /* verification */ + if (opc != NULL) { + switch (*(opc+2)) { + case 'n': val = "-Xverify:none"; break; + case 'r': val = "-Xverify:remote"; break; + case 'a': val = "-Xverify:all"; break; + default: val = NULL; break; + } + + if (val != NULL) { + opt.optionString = val; + mOptions.add(opt); + } + } + + opc = strstr(dexoptFlagsBuf, "o="); /* optimization */ + if (opc != NULL) { + switch (*(opc+2)) { + case 'n': val = "-Xdexopt:none"; break; + case 'v': val = "-Xdexopt:verified"; break; + case 'a': val = "-Xdexopt:all"; break; + default: val = NULL; break; + } + + if (val != NULL) { + opt.optionString = val; + mOptions.add(opt); + } + } + + opc = strstr(dexoptFlagsBuf, "m=y"); /* register map */ + if (opc != NULL) { + opt.optionString = "-Xgenregmap"; + mOptions.add(opt); + } } /* enable debugging; set suspend=y to pause during VM init */ @@ -1008,6 +1027,7 @@ static const RegJNIRec gRegJNI[] = { REG_JNI(register_android_content_AssetManager), REG_JNI(register_android_content_StringBlock), REG_JNI(register_android_content_XmlBlock), + REG_JNI(register_android_emoji_EmojiFactory), REG_JNI(register_android_security_Md5MessageDigest), REG_JNI(register_android_text_AndroidCharacter), REG_JNI(register_android_text_KeyCharacterMap), @@ -1066,7 +1086,6 @@ static const RegJNIRec gRegJNI[] = { REG_JNI(register_android_net_LocalSocketImpl), REG_JNI(register_android_net_NetworkUtils), REG_JNI(register_android_net_wifi_WifiManager), - REG_JNI(register_android_os_NetStat), REG_JNI(register_android_os_MemoryFile), REG_JNI(register_com_android_internal_os_ZygoteInit), REG_JNI(register_android_hardware_Camera), diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp index be8526d0c67a697dba75925f14078a1a4f5cce41..332b01c7ce70546e8ee6d6a3abdf172e4a5e7c17 100644 --- a/core/jni/android/graphics/BitmapFactory.cpp +++ b/core/jni/android/graphics/BitmapFactory.cpp @@ -1,3 +1,5 @@ +#define LOG_TAG "BitmapFactory" + #include "SkImageDecoder.h" #include "SkPixelRef.h" #include "SkStream.h" @@ -481,6 +483,48 @@ static void nativeRequestCancel(JNIEnv*, jobject joptions) { (void)AutoDecoderCancel::RequestCancel(joptions); } +static jbyteArray nativeScaleNinePatch(JNIEnv* env, jobject, jbyteArray chunkObject, jfloat scale, + jobject padding) { + + jbyte* array = env->GetByteArrayElements(chunkObject, 0); + if (array != NULL) { + size_t chunkSize = env->GetArrayLength(chunkObject); + void* storage = alloca(chunkSize); + android::Res_png_9patch* chunk = static_cast(storage); + memcpy(chunk, array, chunkSize); + android::Res_png_9patch::deserialize(chunk); + + chunk->paddingLeft = int(chunk->paddingLeft * scale + 0.5f); + chunk->paddingTop = int(chunk->paddingTop * scale + 0.5f); + chunk->paddingRight = int(chunk->paddingRight * scale + 0.5f); + chunk->paddingBottom = int(chunk->paddingBottom * scale + 0.5f); + + for (int i = 0; i < chunk->numXDivs; i++) { + chunk->xDivs[i] = int(chunk->xDivs[i] * scale + 0.5f); + if (i > 0 && chunk->xDivs[i] == chunk->xDivs[i - 1]) { + chunk->xDivs[i]++; + } + } + + for (int i = 0; i < chunk->numYDivs; i++) { + chunk->yDivs[i] = int(chunk->yDivs[i] * scale + 0.5f); + if (i > 0 && chunk->yDivs[i] == chunk->yDivs[i - 1]) { + chunk->yDivs[i]++; + } + } + + memcpy(array, chunk, chunkSize); + + if (padding) { + GraphicsJNI::set_jrect(env, padding, chunk->paddingLeft, chunk->paddingTop, + chunk->paddingRight, chunk->paddingBottom); + } + + env->ReleaseByteArrayElements(chunkObject, array, 0); + } + return chunkObject; +} + /////////////////////////////////////////////////////////////////////////////// static JNINativeMethod gMethods[] = { @@ -502,7 +546,13 @@ static JNINativeMethod gMethods[] = { { "nativeDecodeByteArray", "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;", (void*)nativeDecodeByteArray + }, + + { "nativeScaleNinePatch", + "([BFLandroid/graphics/Rect;)[B", + (void*)nativeScaleNinePatch } + }; static JNINativeMethod gOptionsMethods[] = { diff --git a/core/jni/android/graphics/Canvas.cpp b/core/jni/android/graphics/Canvas.cpp index b9e5f67067dc3f2983bfcc5a1b1396729c4a4d4a..605e4b8af76dfc5aed1e7874f71df253b9282ad2 100644 --- a/core/jni/android/graphics/Canvas.cpp +++ b/core/jni/android/graphics/Canvas.cpp @@ -93,7 +93,7 @@ public: SkCanvas* canvas = GraphicsJNI::getNativeCanvas(env, jcanvas); return canvas->getDevice()->accessBitmap(false).height(); } - + static void setViewport(JNIEnv* env, jobject, SkCanvas* canvas, int width, int height) { canvas->setViewport(width, height); @@ -454,13 +454,32 @@ public: #endif } - static void drawBitmap__BitmapFFPaint(JNIEnv* env, jobject, + static void drawBitmap__BitmapFFPaint(JNIEnv* env, jobject jcanvas, SkCanvas* canvas, SkBitmap* bitmap, jfloat left, jfloat top, - SkPaint* paint) { + SkPaint* paint, + jboolean autoScale, jfloat densityScale) { SkScalar left_ = SkFloatToScalar(left); SkScalar top_ = SkFloatToScalar(top); - canvas->drawBitmap(*bitmap, left_, top_, paint); + + if (!autoScale || densityScale <= 0.0f) { + canvas->drawBitmap(*bitmap, left_, top_, paint); + } else { + canvas->save(); + SkScalar canvasScale = GraphicsJNI::getCanvasDensityScale(env, jcanvas); + SkScalar scale = canvasScale / SkFloatToScalar(densityScale); + canvas->scale(scale, scale); + + SkPaint filteredPaint; + if (paint) { + filteredPaint = *paint; + } + filteredPaint.setFilterBitmap(true); + + canvas->drawBitmap(*bitmap, left_, top_, &filteredPaint); + + canvas->restore(); + } } static void doDrawBitmap(JNIEnv* env, SkCanvas* canvas, SkBitmap* bitmap, @@ -492,7 +511,7 @@ public: static void drawBitmapArray(JNIEnv* env, jobject, SkCanvas* canvas, jintArray jcolors, int offset, int stride, - int x, int y, int width, int height, + jfloat x, jfloat y, int width, int height, jboolean hasAlpha, SkPaint* paint) { SkBitmap bitmap; @@ -508,7 +527,8 @@ public: return; } - canvas->drawBitmap(bitmap, SkIntToScalar(x), SkIntToScalar(y), paint); + canvas->drawBitmap(bitmap, SkFloatToScalar(x), SkFloatToScalar(y), + paint); } static void drawBitmapMatrix(JNIEnv* env, jobject, SkCanvas* canvas, @@ -882,13 +902,13 @@ static JNINativeMethod gCanvasMethods[] = { {"native_drawRoundRect","(ILandroid/graphics/RectF;FFI)V", (void*) SkCanvasGlue::drawRoundRect}, {"native_drawPath","(III)V", (void*) SkCanvasGlue::drawPath}, - {"native_drawBitmap","(IIFFI)V", + {"native_drawBitmap","(IIFFIZF)V", (void*) SkCanvasGlue::drawBitmap__BitmapFFPaint}, {"native_drawBitmap","(IILandroid/graphics/Rect;Landroid/graphics/RectF;I)V", (void*) SkCanvasGlue::drawBitmapRF}, {"native_drawBitmap","(IILandroid/graphics/Rect;Landroid/graphics/Rect;I)V", (void*) SkCanvasGlue::drawBitmapRR}, - {"native_drawBitmap", "(I[IIIIIIIZI)V", + {"native_drawBitmap", "(I[IIIFFIIZI)V", (void*)SkCanvasGlue::drawBitmapArray}, {"nativeDrawBitmapMatrix", "(IIII)V", diff --git a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp index 65c2326a6cab69d5f2fddcee0792ad2ff373c8fa..a285def804a62bf0cd8bb022289f33aa06f1b248 100644 --- a/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp +++ b/core/jni/android/graphics/CreateJavaOutputStreamAdaptor.cpp @@ -56,11 +56,14 @@ public: break; // eof } - const jbyte* array = env->GetByteArrayElements(fJavaByteArray, - NULL); - memcpy(buffer, array, n); - env->ReleaseByteArrayElements(fJavaByteArray, - const_cast(array), JNI_ABORT); + env->GetByteArrayRegion(fJavaByteArray, 0, n, + reinterpret_cast(buffer)); + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + SkDebugf("---- read:GetByteArrayRegion threw an exception\n"); + return 0; + } buffer = (void*)((char*)buffer + n); bytesRead += n; @@ -189,10 +192,15 @@ public: requested = fCapacity; } - jbyte* array = env->GetByteArrayElements(storage, NULL); - memcpy(array, buffer, requested); - env->ReleaseByteArrayElements(storage, array, 0); - + env->SetByteArrayRegion(storage, 0, requested, + reinterpret_cast(buffer)); + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + SkDebugf("--- write:SetByteArrayElements threw an exception\n"); + return false; + } + fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_writeMethodID, storage, 0, requested); if (env->ExceptionCheck()) { diff --git a/core/jni/android/graphics/Graphics.cpp b/core/jni/android/graphics/Graphics.cpp index 44113e5b46bf12d03e26d41b4e6fc3c249912962..6eebbdcfb5636cb2e9d6359cfe0cf1aa62ff4875 100644 --- a/core/jni/android/graphics/Graphics.cpp +++ b/core/jni/android/graphics/Graphics.cpp @@ -162,6 +162,7 @@ static jfieldID gBitmapConfig_nativeInstanceID; static jclass gCanvas_class; static jfieldID gCanvas_nativeInstanceID; +static jfieldID gCanvas_densityScaleID; static jclass gPaint_class; static jfieldID gPaint_nativeInstanceID; @@ -318,6 +319,13 @@ SkCanvas* GraphicsJNI::getNativeCanvas(JNIEnv* env, jobject canvas) { return c; } +SkScalar GraphicsJNI::getCanvasDensityScale(JNIEnv* env, jobject canvas) { + SkASSERT(env); + SkASSERT(canvas); + SkASSERT(env->IsInstanceOf(canvas, gCanvas_class)); + return SkFloatToScalar(env->GetFloatField(canvas, gCanvas_densityScaleID)); +} + SkPaint* GraphicsJNI::getNativePaint(JNIEnv* env, jobject paint) { SkASSERT(env); SkASSERT(paint); @@ -543,7 +551,8 @@ int register_android_graphics_Graphics(JNIEnv* env) gCanvas_class = make_globalref(env, "android/graphics/Canvas"); gCanvas_nativeInstanceID = getFieldIDCheck(env, gCanvas_class, "mNativeCanvas", "I"); - + gCanvas_densityScaleID = getFieldIDCheck(env, gCanvas_class, "mDensityScale", "F"); + gPaint_class = make_globalref(env, "android/graphics/Paint"); gPaint_nativeInstanceID = getFieldIDCheck(env, gPaint_class, "mNativePaint", "I"); diff --git a/core/jni/android/graphics/GraphicsJNI.h b/core/jni/android/graphics/GraphicsJNI.h index e67b20b190cb7357c3d777730a28cac6a1084943..e2dc9acf1beb314a9db9c289520197ad08ac8b36 100644 --- a/core/jni/android/graphics/GraphicsJNI.h +++ b/core/jni/android/graphics/GraphicsJNI.h @@ -38,6 +38,7 @@ public: static SkBitmap* getNativeBitmap(JNIEnv*, jobject bitmap); static SkPicture* getNativePicture(JNIEnv*, jobject picture); static SkRegion* getNativeRegion(JNIEnv*, jobject region); + static SkScalar getCanvasDensityScale(JNIEnv*, jobject canvas); /** Return the corresponding native config from the java Config enum, or kNo_Config if the java object is null. diff --git a/core/jni/android/graphics/NinePatch.cpp b/core/jni/android/graphics/NinePatch.cpp index 9e943f3e0db21dcc802551456dc6c5cbb3f5ab8b..b11edfc07436e437f8f9661b38d2d1af868f7e17 100644 --- a/core/jni/android/graphics/NinePatch.cpp +++ b/core/jni/android/graphics/NinePatch.cpp @@ -47,19 +47,17 @@ public: static void draw(JNIEnv* env, SkCanvas* canvas, SkRect& bounds, const SkBitmap* bitmap, jbyteArray chunkObj, const SkPaint* paint) { - const jbyte* array = env->GetByteArrayElements(chunkObj, 0); - if (array != NULL) { - size_t chunkSize = env->GetArrayLength(chunkObj); + size_t chunkSize = env->GetArrayLength(chunkObj); + void* storage = alloca(chunkSize); + env->GetByteArrayRegion(chunkObj, 0, chunkSize, + reinterpret_cast(storage)); + if (!env->ExceptionCheck()) { // need to deserialize the chunk - void* storage = alloca(chunkSize); Res_png_9patch* chunk = static_cast(storage); - memcpy(chunk, array, chunkSize); assert(chunkSize == chunk->serializedSize()); // this relies on deserialization being done in place Res_png_9patch::deserialize(chunk); NinePatch_Draw(canvas, bounds, *bitmap, *chunk, paint, NULL); - env->ReleaseByteArrayElements(chunkObj, const_cast(array), - JNI_ABORT); } } @@ -102,23 +100,20 @@ public: SkRect bounds; GraphicsJNI::jrect_to_rect(env, boundsRect, &bounds); - const jbyte* array = (jbyte*)env->GetByteArrayElements(chunkObj, 0); - if (array != NULL) { - size_t chunkSize = env->GetArrayLength(chunkObj); + size_t chunkSize = env->GetArrayLength(chunkObj); + void* storage = alloca(chunkSize); + env->GetByteArrayRegion(chunkObj, 0, chunkSize, + reinterpret_cast(storage)); + if (!env->ExceptionCheck()) { // need to deserialize the chunk - void* storage = alloca(chunkSize); Res_png_9patch* chunk = static_cast(storage); - memcpy(chunk, array, chunkSize); assert(chunkSize == chunk->serializedSize()); // this relies on deserialization being done in place Res_png_9patch::deserialize(chunk); SkRegion* region = NULL; NinePatch_Draw(NULL, bounds, *bitmap, *chunk, NULL, ®ion); - env->ReleaseByteArrayElements(chunkObj, const_cast(array), - JNI_ABORT); return (jint)region; } - return 0; } diff --git a/core/jni/android/graphics/Typeface.cpp b/core/jni/android/graphics/Typeface.cpp index 32954cef63f132c397f8835b56bf8a48e1848665..e9514317b8f3c7280bb2c63bcf177e132495da4e 100644 --- a/core/jni/android/graphics/Typeface.cpp +++ b/core/jni/android/graphics/Typeface.cpp @@ -32,11 +32,11 @@ static SkTypeface* Typeface_create(JNIEnv* env, jobject, jstring name, SkTypeface* face; if (NULL == name) { - face = SkTypeface::Create(NULL, (SkTypeface::Style)style); + face = SkTypeface::CreateFromName(NULL, (SkTypeface::Style)style); } else { AutoJavaStringToUTF8 str(env, name); - face = SkTypeface::Create(str.c_str(), style); + face = SkTypeface::CreateFromName(str.c_str(), style); } return face; } @@ -50,7 +50,7 @@ static void Typeface_unref(JNIEnv* env, jobject obj, SkTypeface* face) { } static int Typeface_getStyle(JNIEnv* env, jobject obj, SkTypeface* face) { - return face->getStyle(); + return face->style(); } class AssetStream : public SkStream { diff --git a/core/jni/android_bluetooth_BluetoothAudioGateway.cpp b/core/jni/android_bluetooth_BluetoothAudioGateway.cpp index 7f87d8028b5ebe8dc5b88453773639bb84424702..bf2365094917f01106e58edf3735c616f42d5f7b 100755 --- a/core/jni/android_bluetooth_BluetoothAudioGateway.cpp +++ b/core/jni/android_bluetooth_BluetoothAudioGateway.cpp @@ -49,8 +49,6 @@ #ifdef HAVE_BLUETOOTH #include -#include -#include #include #include #endif diff --git a/core/jni/android_database_SQLiteDatabase.cpp b/core/jni/android_database_SQLiteDatabase.cpp index 66f0118d8ad3a6b7b67f4f2ef958b9e904b4d55c..66858f9badf1662dffa8b2a9cd4c035bfd4fe458 100644 --- a/core/jni/android_database_SQLiteDatabase.cpp +++ b/core/jni/android_database_SQLiteDatabase.cpp @@ -45,6 +45,8 @@ #define INVALID_VERSION -1 #define SQLITE_SOFT_HEAP_LIMIT (4 * 1024 * 1024) #define ANDROID_TABLE "android_metadata" +/* uncomment the next line to force-enable logging of all statements */ +// #define DB_LOG_STATEMENTS namespace android { @@ -197,7 +199,11 @@ static void native_execSQL(JNIEnv* env, jobject object, jstring sqlString) env->ReleaseStringUTFChars(sqlString, sql8); } - } else IF_LOGV() { + } else +#ifndef DB_LOG_STATEMENTS + IF_LOGV() +#endif + { char const * sql8 = env->GetStringUTFChars(sqlString, NULL); LOGV("Success on %p when executing '%s'\n", handle, sql8); env->ReleaseStringUTFChars(sqlString, sql8); diff --git a/core/jni/android_emoji_EmojiFactory.cpp b/core/jni/android_emoji_EmojiFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59f63a83cac541b3c3afe86bf1825dfc35cbbd62 --- /dev/null +++ b/core/jni/android_emoji_EmojiFactory.cpp @@ -0,0 +1,292 @@ +#include "SkTypes.h" +#include "SkImageDecoder.h" + +#define LOG_TAG "DoCoMoEmojiFactory_jni" +#include +#include + +#include "EmojiFactory.h" +#include + +#include +// #include + +namespace android { + +// Note: This class is originally developed so that libandroid_runtime does +// not have to depend on libemoji which is optional library. However, we +// cannot use this class, since current (2009-02-16) bionic libc does not allow +// dlopen()-ing inside dlopen(), while not only this class but also libemoji +// uses dlopen(). +class EmojiFactoryCaller { + public: + EmojiFactoryCaller(); + virtual ~EmojiFactoryCaller(); + EmojiFactory *TryCallGetImplementation(const char* name); + EmojiFactory *TryCallGetAvailableImplementation(); + private: + void *m_handle; + EmojiFactory *(*m_get_implementation)(const char*); + EmojiFactory *(*m_get_available_implementation)(); +}; + +EmojiFactoryCaller::EmojiFactoryCaller() { + m_handle = dlopen("libemoji.so", RTLD_LAZY | RTLD_LOCAL); + const char* error_str = dlerror(); + if (error_str) { + LOGI("Failed to load libemoji.so: %s", error_str); + return; + } + + m_get_implementation = + reinterpret_cast( + dlsym(m_handle, "GetImplementation")); + error_str = dlerror(); + if (error_str) { + LOGE("Failed to get symbol of GetImplementation: %s", error_str); + dlclose(m_handle); + m_handle = NULL; + return; + } + + m_get_available_implementation = + reinterpret_cast( + dlsym(m_handle,"GetAvailableImplementation")); + error_str = dlerror(); + if (error_str) { + LOGE("Failed to get symbol of GetAvailableImplementation: %s", error_str); + dlclose(m_handle); + m_handle = NULL; + return; + } +} + +EmojiFactoryCaller::~EmojiFactoryCaller() { + if (m_handle) { + dlclose(m_handle); + } +} + +EmojiFactory *EmojiFactoryCaller::TryCallGetImplementation( + const char* name) { + if (NULL == m_handle) { + return NULL; + } + return m_get_implementation(name); +} + +EmojiFactory *EmojiFactoryCaller::TryCallGetAvailableImplementation() { + if (NULL == m_handle) { + return NULL; + } + return m_get_available_implementation(); +} + +// Note: bionic libc's dlopen() does not allow recursive dlopen(). So currently +// we cannot use EmojiFactoryCaller here. +// static EmojiFactoryCaller* gCaller; +// static pthread_once_t g_once = PTHREAD_ONCE_INIT; + +static jclass gString_class; + +static jclass gBitmap_class; +static jmethodID gBitmap_constructorMethodID; + +static jclass gEmojiFactory_class; +static jmethodID gEmojiFactory_constructorMethodID; + +// static void InitializeCaller() { +// gCaller = new EmojiFactoryCaller(); +// } + +static jobject create_java_EmojiFactory( + JNIEnv* env, EmojiFactory* factory, jstring name) { + jobject obj = env->AllocObject(gEmojiFactory_class); + if (obj) { + env->CallVoidMethod(obj, gEmojiFactory_constructorMethodID, + (jint)factory, name); + if (env->ExceptionCheck() != 0) { + LOGE("*** Uncaught exception returned from Java call!\n"); + env->ExceptionDescribe(); + obj = NULL; + } + } + return obj; +} + +static jobject android_emoji_EmojiFactory_newInstance( + JNIEnv* env, jobject clazz, jstring name) { + // pthread_once(&g_once, InitializeCaller); + + if (NULL == name) { + return NULL; + } + + const jchar* jchars = env->GetStringChars(name, NULL); + jsize len = env->GetStringLength(name); + String8 str(String16(jchars, len)); + + // EmojiFactory *factory = gCaller->TryCallGetImplementation(str.string()); + EmojiFactory *factory = EmojiFactory::GetImplementation(str.string()); + + env->ReleaseStringChars(name, jchars); + + return create_java_EmojiFactory(env, factory, name); +} + +static jobject android_emoji_EmojiFactory_newAvailableInstance( + JNIEnv* env, jobject clazz) { + // pthread_once(&g_once, InitializeCaller); + + // EmojiFactory *factory = gCaller->TryCallGetAvailableImplementation(); + EmojiFactory *factory = EmojiFactory::GetAvailableImplementation(); + if (NULL == factory) { + return NULL; + } + String16 name_16(String8(factory->Name())); + jstring jname = env->NewString(name_16.string(), name_16.size()); + if (NULL == jname) { + return NULL; + } + + return create_java_EmojiFactory(env, factory, jname); +} + +static jobject android_emoji_EmojiFactory_getBitmapFromAndroidPua( + JNIEnv* env, jobject clazz, jint nativeEmojiFactory, jint pua) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + + int size; + const char *bytes = factory->GetImageBinaryFromAndroidPua(pua, &size); + if (bytes == NULL) { + return NULL; + } + + SkBitmap *bitmap = new SkBitmap; + if (!SkImageDecoder::DecodeMemory(bytes, size, bitmap)) { + LOGE("SkImageDecoder::DecodeMemory() failed."); + return NULL; + } + + jobject obj = env->AllocObject(gBitmap_class); + if (obj) { + env->CallVoidMethod(obj, gBitmap_constructorMethodID, + reinterpret_cast(bitmap), false, NULL); + if (env->ExceptionCheck() != 0) { + LOGE("*** Uncaught exception returned from Java call!\n"); + env->ExceptionDescribe(); + return NULL; + } + } + + return obj; +} + +static void android_emoji_EmojiFactory_destructor( + JNIEnv* env, jobject obj, jint nativeEmojiFactory) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + delete factory; +} + +static jint android_emoji_EmojiFactory_getAndroidPuaFromVendorSpecificSjis( + JNIEnv* env, jobject obj, jint nativeEmojiFactory, jchar sjis) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + return factory->GetAndroidPuaFromVendorSpecificSjis(sjis); +} + +static jint android_emoji_EmojiFactory_getVendorSpecificSjisFromAndroidPua( + JNIEnv* env, jobject obj, jint nativeEmojiFactory, jint pua) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + return factory->GetVendorSpecificSjisFromAndroidPua(pua); +} + +static jint android_emoji_EmojiFactory_getAndroidPuaFromVendorSpecificPua( + JNIEnv* env, jobject obj, jint nativeEmojiFactory, jint vsu) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + return factory->GetAndroidPuaFromVendorSpecificPua(vsu); +} + +static jint android_emoji_EmojiFactory_getVendorSpecificPuaFromAndroidPua( + JNIEnv* env, jobject obj, jint nativeEmojiFactory, jint pua) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + return factory->GetVendorSpecificPuaFromAndroidPua(pua); +} + +static jint android_emoji_EmojiFactory_getMaximumVendorSpecificPua( + JNIEnv* env, jobject obj, jint nativeEmojiFactory) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + return factory->GetMaximumVendorSpecificPua(); +} + +static jint android_emoji_EmojiFactory_getMinimumVendorSpecificPua( + JNIEnv* env, jobject obj, jint nativeEmojiFactory) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + return factory->GetMinimumVendorSpecificPua(); +} + +static jint android_emoji_EmojiFactory_getMaximumAndroidPua( + JNIEnv* env, jobject obj, jint nativeEmojiFactory) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + return factory->GetMaximumAndroidPua(); +} + +static jint android_emoji_EmojiFactory_getMinimumAndroidPua( + JNIEnv* env, jobject obj, jint nativeEmojiFactory) { + EmojiFactory *factory = reinterpret_cast(nativeEmojiFactory); + return factory->GetMinimumAndroidPua(); +} + +static JNINativeMethod gMethods[] = { + { "newInstance", "(Ljava/lang/String;)Landroid/emoji/EmojiFactory;", + (void*)android_emoji_EmojiFactory_newInstance}, + { "newAvailableInstance", "()Landroid/emoji/EmojiFactory;", + (void*)android_emoji_EmojiFactory_newAvailableInstance}, + { "nativeDestructor", "(I)V", + (void*)android_emoji_EmojiFactory_destructor}, + { "nativeGetBitmapFromAndroidPua", "(II)Landroid/graphics/Bitmap;", + (void*)android_emoji_EmojiFactory_getBitmapFromAndroidPua}, + { "nativeGetAndroidPuaFromVendorSpecificSjis", "(IC)I", + (void*)android_emoji_EmojiFactory_getAndroidPuaFromVendorSpecificSjis}, + { "nativeGetVendorSpecificSjisFromAndroidPua", "(II)I", + (void*)android_emoji_EmojiFactory_getVendorSpecificSjisFromAndroidPua}, + { "nativeGetAndroidPuaFromVendorSpecificPua", "(II)I", + (void*)android_emoji_EmojiFactory_getAndroidPuaFromVendorSpecificPua}, + { "nativeGetVendorSpecificPuaFromAndroidPua", "(II)I", + (void*)android_emoji_EmojiFactory_getVendorSpecificPuaFromAndroidPua}, + { "nativeGetMaximumVendorSpecificPua", "(I)I", + (void*)android_emoji_EmojiFactory_getMaximumVendorSpecificPua}, + { "nativeGetMinimumVendorSpecificPua", "(I)I", + (void*)android_emoji_EmojiFactory_getMinimumVendorSpecificPua}, + { "nativeGetMaximumAndroidPua", "(I)I", + (void*)android_emoji_EmojiFactory_getMaximumAndroidPua}, + { "nativeGetMinimumAndroidPua", "(I)I", + (void*)android_emoji_EmojiFactory_getMinimumAndroidPua} +}; + +static jclass make_globalref(JNIEnv* env, const char classname[]) +{ + jclass c = env->FindClass(classname); + SkASSERT(c); + return (jclass)env->NewGlobalRef(c); +} + +static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz, + const char fieldname[], const char type[]) +{ + jfieldID id = env->GetFieldID(clazz, fieldname, type); + SkASSERT(id); + return id; +} + +int register_android_emoji_EmojiFactory(JNIEnv* env) { + gBitmap_class = make_globalref(env, "android/graphics/Bitmap"); + gBitmap_constructorMethodID = env->GetMethodID(gBitmap_class, "", + "(IZ[B)V"); + gEmojiFactory_class = make_globalref(env, "android/emoji/EmojiFactory"); + gEmojiFactory_constructorMethodID = env->GetMethodID( + gEmojiFactory_class, "", "(ILjava/lang/String;)V"); + return jniRegisterNativeMethods(env, "android/emoji/EmojiFactory", + gMethods, NELEM(gMethods)); +} + +} // namespace android diff --git a/core/jni/android_hardware_Camera.cpp b/core/jni/android_hardware_Camera.cpp index a81f2520bcd4414621bcb899db6ca8d450424b2d..f6cd211b20c4832cd66f88c1332d5ff2ad1124a3 100644 --- a/core/jni/android_hardware_Camera.cpp +++ b/core/jni/android_hardware_Camera.cpp @@ -15,7 +15,9 @@ ** limitations under the License. */ +//#define LOG_NDEBUG 0 #define LOG_TAG "Camera-JNI" +#include #include "jni.h" #include "JNIHelp.h" @@ -45,38 +47,43 @@ enum CameraError { struct fields_t { jfieldID context; jfieldID surface; - jfieldID listener_context; jmethodID post_event; }; static fields_t fields; static Mutex sLock; -struct callback_cookie { - jclass camera_class; - jobject camera_ref; +struct camera_context_t { + jobject mCameraJObjectWeak; // weak reference to java object + jclass mCameraJClass; // strong reference to java class + sp mCamera; // strong reference to native object }; -sp get_native_camera(JNIEnv *env, jobject thiz) +sp get_native_camera(JNIEnv *env, jobject thiz, camera_context_t** pContext) { + sp camera; Mutex::Autolock _l(sLock); - sp c = reinterpret_cast(env->GetIntField(thiz, fields.context)); - if (c == 0) + camera_context_t* context = reinterpret_cast(env->GetIntField(thiz, fields.context)); + if (context != NULL) { + camera = context->mCamera; + } + LOGV("get_native_camera: context=%p, camera=%p", context, camera.get()); + if (camera == 0) { jniThrowException(env, "java/lang/RuntimeException", "Method called after release()"); + } - return c; + if (pContext != NULL) *pContext = context; + return camera; } static void err_callback(status_t err, void *cookie) { - JNIEnv *env = AndroidRuntime::getJNIEnv(); - if (env == NULL) { - LOGE("err_callback on dead VM"); - return; - } - callback_cookie *c = (callback_cookie *)cookie; - int error; + camera_context_t* context = reinterpret_cast(cookie); + if ((context == NULL) || (context->mCamera == 0)) return; + + LOGV("err_callback: context=%p, camera=%p", context, context->mCamera.get()); + int error; switch (err) { case DEAD_OBJECT: error = kCameraErrorMediaServer; @@ -85,29 +92,32 @@ static void err_callback(status_t err, void *cookie) error = kCameraErrorUnknown; break; } - LOGV("err_callback: camera_ref=%x, cookie=%x", (int)c->camera_ref, (int)cookie); - env->CallStaticVoidMethod(c->camera_class, fields.post_event, - c->camera_ref, kErrorCallback, error, 0, NULL); + JNIEnv *env = AndroidRuntime::getJNIEnv(); + if (env == NULL) { + LOGE("err_callback on dead VM"); + return; + } + env->CallStaticVoidMethod(context->mCameraJClass, fields.post_event, + context->mCameraJObjectWeak, kErrorCallback, error, 0, NULL); } // connect to camera service static void android_hardware_Camera_native_setup(JNIEnv *env, jobject thiz, jobject weak_this) { - sp c = Camera::connect(); + sp camera = Camera::connect(); - if (c == NULL) { + if (camera == NULL) { jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); return; } // make sure camera hardware is alive - if (c->getStatus() != NO_ERROR) { + if (camera->getStatus() != NO_ERROR) { jniThrowException(env, "java/io/IOException", "Camera initialization failed"); return; } - callback_cookie *cookie = new callback_cookie; jclass clazz = env->GetObjectClass(thiz); if (clazz == NULL) { LOGE("Can't find android/hardware/Camera"); @@ -115,76 +125,87 @@ static void android_hardware_Camera_native_setup(JNIEnv *env, jobject thiz, jobj jniThrowException(env, "java/lang/Exception", NULL); return; } - cookie->camera_class = (jclass)env->NewGlobalRef(clazz); // We use a weak reference so the Camera object can be garbage collected. // The reference is only used as a proxy for callbacks. - cookie->camera_ref = env->NewGlobalRef(weak_this); - env->SetIntField(thiz, fields.listener_context, (int)cookie); - - LOGV("native_setup: camera_ref=%x, camera_obj=%x, cookie=%x", (int)cookie->camera_ref, (int)thiz, (int)cookie); + camera_context_t* context = new camera_context_t; + context->mCameraJObjectWeak = env->NewGlobalRef(weak_this); + context->mCameraJClass = (jclass)env->NewGlobalRef(clazz); + context->mCamera = camera; - // save camera object in opaque field - env->SetIntField(thiz, fields.context, reinterpret_cast(c.get())); + // save context in opaque field + env->SetIntField(thiz, fields.context, (int)context); - c->setErrorCallback(err_callback, cookie); + LOGV("native_setup: mCameraJObjectWeak=%x, camera_obj=%x, context=%p", + (int)context->mCameraJObjectWeak, (int)thiz, context); - // hold a strong reference so the camera doesn't go away while the app is still running - c->incStrong(thiz); + // set error callback + camera->setErrorCallback(err_callback, context); } // disconnect from camera service +// It's okay to call this when the native camera context is already null. +// This handles the case where the user has called release() and the +// finalizer is invoked later. static void android_hardware_Camera_release(JNIEnv *env, jobject thiz) { - Mutex::Autolock _l(sLock); - sp c = reinterpret_cast(env->GetIntField(thiz, fields.context)); - // It's okay to call this when the native camera context is already null. - // This handles the case where the user has called release() and the - // finalizer is invoked later. - if (c != 0) { - // Make sure that we do not attempt to deliver an eror callback on a deleted - // Java object. - c->setErrorCallback(NULL, NULL); - c->disconnect(); - - // remove our strong reference created in native setup - c->decStrong(thiz); - env->SetIntField(thiz, fields.context, 0); - - callback_cookie *cookie = (callback_cookie *)env->GetIntField(thiz, fields.listener_context); + camera_context_t* context = NULL; + sp camera; + { + Mutex::Autolock _l(sLock); + context = reinterpret_cast(env->GetIntField(thiz, fields.context)); - LOGV("release: camera_ref=%x, camera_obj=%x, cookie=%x", (int)cookie->camera_ref, (int)thiz, (int)cookie); + // Make sure we do not attempt to callback on a deleted Java object. + env->SetIntField(thiz, fields.context, 0); + } - if (cookie) { - env->DeleteGlobalRef(cookie->camera_ref); - env->DeleteGlobalRef(cookie->camera_class); - delete cookie; - env->SetIntField(thiz, fields.listener_context, 0); + // clean up if release has not been called before + if (context != NULL) { + camera = context->mCamera; + context->mCamera.clear(); + LOGV("native_release: context=%p camera=%p", context, camera.get()); + + // clear callbacks + if (camera != NULL) { + camera->setPreviewCallback(NULL, NULL, FRAME_CALLBACK_FLAG_NOOP); + camera->setErrorCallback(NULL, NULL); + camera->disconnect(); + env->DeleteGlobalRef(context->mCameraJObjectWeak); + env->DeleteGlobalRef(context->mCameraJClass); } + + // remove context to prevent further Java access + delete context; } } -static void android_hardware_Camera_setPreviewDisplay(JNIEnv *env, jobject thiz, jobject surface) +static void android_hardware_Camera_setPreviewDisplay(JNIEnv *env, jobject thiz, jobject jSurface) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return; + LOGV("setPreviewDisplay"); + sp camera = get_native_camera(env, thiz, NULL); + if (camera == 0) return; - sp s = (Surface *)env->GetIntField(surface, fields.surface); - if (c->setPreviewDisplay(s) != NO_ERROR) { + sp surface = reinterpret_cast(env->GetIntField(jSurface, fields.surface)); + if (camera->setPreviewDisplay(surface) != NO_ERROR) { jniThrowException(env, "java/io/IOException", "setPreviewDisplay failed"); - return; } } static void preview_callback(const sp& mem, void *cookie) { + LOGV("preview_callback"); JNIEnv *env = AndroidRuntime::getJNIEnv(); if (env == NULL) { LOGE("preview_callback on dead VM"); return; } - callback_cookie *c = (callback_cookie *)cookie; + camera_context_t* context = reinterpret_cast(cookie); + if ((context == NULL) || (context->mCamera == 0)) { + LOGW("context or camera is NULL in preview_callback"); + return; + } + LOGV("native_release: context=%p camera=%p", context, context->mCamera.get()); + int arg1 = 0, arg2 = 0; jobject obj = NULL; @@ -207,18 +228,18 @@ static void preview_callback(const sp& mem, void *cookie) obj = array; - env->CallStaticVoidMethod(c->camera_class, fields.post_event, - c->camera_ref, kPreviewCallback, arg1, arg2, obj); + env->CallStaticVoidMethod(context->mCameraJClass, fields.post_event, + context->mCameraJObjectWeak, kPreviewCallback, arg1, arg2, obj); env->DeleteLocalRef(array); } static void android_hardware_Camera_startPreview(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return; + LOGV("startPreview"); + sp camera = get_native_camera(env, thiz, NULL); + if (camera == 0) return; - if (c->startPreview() != NO_ERROR) { + if (camera->startPreview() != NO_ERROR) { jniThrowException(env, "java/io/IOException", "startPreview failed"); return; } @@ -226,32 +247,30 @@ static void android_hardware_Camera_startPreview(JNIEnv *env, jobject thiz) static void android_hardware_Camera_stopPreview(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return; + LOGV("stopPreview"); + sp c = get_native_camera(env, thiz, NULL); + if (c == 0) return; c->stopPreview(); } static bool android_hardware_Camera_previewEnabled(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return false; + LOGV("previewEnabled"); + sp c = get_native_camera(env, thiz, NULL); + if (c == 0) return false; return c->previewEnabled(); } static void android_hardware_Camera_setHasPreviewCallback(JNIEnv *env, jobject thiz, jboolean installed, jboolean oneshot) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return; - // Important: Only install preview_callback if the Java code has called // setPreviewCallback() with a non-null value, otherwise we'd pay to memcpy // each preview frame for nothing. - callback_cookie *cookie = (callback_cookie *)env->GetIntField(thiz, fields.listener_context); + camera_context_t* context; + sp camera = get_native_camera(env, thiz, &context); + if (camera == 0) return; int callback_flag; if (installed) { @@ -259,31 +278,31 @@ static void android_hardware_Camera_setHasPreviewCallback(JNIEnv *env, jobject t } else { callback_flag = FRAME_CALLBACK_FLAG_NOOP; } - c->setFrameCallback(installed ? preview_callback : NULL, cookie, callback_flag); + camera->setPreviewCallback(installed ? preview_callback : NULL, context, callback_flag); } static void autofocus_callback_impl(bool success, void *cookie) { + LOGV("autoFocusCallback"); + camera_context_t* context = reinterpret_cast(cookie); + JNIEnv *env = AndroidRuntime::getJNIEnv(); if (env == NULL) { LOGE("autofocus_callback on dead VM"); return; } - callback_cookie *c = (callback_cookie *)cookie; - env->CallStaticVoidMethod(c->camera_class, fields.post_event, - c->camera_ref, kAutoFocusCallback, - success, 0, NULL); + env->CallStaticVoidMethod(context->mCameraJClass, fields.post_event, + context->mCameraJObjectWeak, kAutoFocusCallback, success, 0, NULL); } - - static void android_hardware_Camera_autoFocus(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return; - callback_cookie *cookie = (callback_cookie *)env->GetIntField(thiz, fields.listener_context); - c->setAutoFocusCallback(autofocus_callback_impl, cookie); + LOGV("autoFocus"); + camera_context_t* context; + sp c = get_native_camera(env, thiz, &context); + if (c == 0) return; + + c->setAutoFocusCallback(autofocus_callback_impl, context); if (c->autoFocus() != NO_ERROR) { jniThrowException(env, "java/io/IOException", "autoFocus failed"); } @@ -291,18 +310,20 @@ static void android_hardware_Camera_autoFocus(JNIEnv *env, jobject thiz) static void jpeg_callback(const sp& mem, void *cookie) { + LOGV("jpegCallback"); + camera_context_t* context = reinterpret_cast(cookie); + JNIEnv *env = AndroidRuntime::getJNIEnv(); if (env == NULL) { LOGE("jpeg`_callback on dead VM"); return; } - callback_cookie *c = (callback_cookie *)cookie; int arg1 = 0, arg2 = 0; jobject obj = NULL; if (mem == NULL) { - env->CallStaticVoidMethod(c->camera_class, fields.post_event, - c->camera_ref, kJpegCallback, arg1, arg2, NULL); + env->CallStaticVoidMethod(context->mCameraJClass, fields.post_event, + context->mCameraJObjectWeak, kJpegCallback, arg1, arg2, NULL); return; } ssize_t offset; @@ -331,48 +352,51 @@ static void jpeg_callback(const sp& mem, void *cookie) obj = array; - env->CallStaticVoidMethod(c->camera_class, fields.post_event, - c->camera_ref, kJpegCallback, arg1, arg2, obj); + env->CallStaticVoidMethod(context->mCameraJClass, fields.post_event, + context->mCameraJObjectWeak, kJpegCallback, arg1, arg2, obj); env->DeleteLocalRef(array); } static void shutter_callback_impl(void *cookie) { + LOGV("shutterCallback"); + camera_context_t* context = reinterpret_cast(cookie); + JNIEnv *env = AndroidRuntime::getJNIEnv(); if (env == NULL) { LOGE("shutter_callback on dead VM"); return; } - callback_cookie *c = (callback_cookie *)cookie; - env->CallStaticVoidMethod(c->camera_class, fields.post_event, - c->camera_ref, kShutterCallback, 0, 0, NULL); + env->CallStaticVoidMethod(context->mCameraJClass, fields.post_event, + context->mCameraJObjectWeak, kShutterCallback, 0, 0, NULL); } static void raw_callback(const sp& mem __attribute__((unused)), void *cookie) { + LOGV("rawCallback"); + camera_context_t* context = reinterpret_cast(cookie); + JNIEnv *env = AndroidRuntime::getJNIEnv(); if (env == NULL) { LOGE("raw_callback on dead VM"); return; } - callback_cookie *c = (callback_cookie *)cookie; - env->CallStaticVoidMethod(c->camera_class, fields.post_event, - c->camera_ref, kRawCallback, 0, 0, NULL); + env->CallStaticVoidMethod(context->mCameraJClass, fields.post_event, + context->mCameraJObjectWeak, kRawCallback, 0, 0, NULL); } static void android_hardware_Camera_takePicture(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return; - - callback_cookie *cookie = - (callback_cookie *)env->GetIntField(thiz, fields.listener_context); - c->setShutterCallback(shutter_callback_impl, cookie); - c->setRawCallback(raw_callback, cookie); - c->setJpegCallback(jpeg_callback, cookie); - if (c->takePicture() != NO_ERROR) { + LOGV("takePicture"); + camera_context_t* context; + sp camera = get_native_camera(env, thiz, &context); + if (camera == 0) return; + + camera->setShutterCallback(shutter_callback_impl, context); + camera->setRawCallback(raw_callback, context); + camera->setJpegCallback(jpeg_callback, context); + if (camera->takePicture() != NO_ERROR) { jniThrowException(env, "java/io/IOException", "takePicture failed"); return; } @@ -382,9 +406,9 @@ static void android_hardware_Camera_takePicture(JNIEnv *env, jobject thiz) static void android_hardware_Camera_setParameters(JNIEnv *env, jobject thiz, jstring params) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return; + LOGV("setParameters"); + sp camera = get_native_camera(env, thiz, NULL); + if (camera == 0) return; const jchar* str = env->GetStringCritical(params, 0); String8 params8; @@ -392,7 +416,7 @@ static void android_hardware_Camera_setParameters(JNIEnv *env, jobject thiz, jst params8 = String8(str, env->GetStringLength(params)); env->ReleaseStringCritical(params, str); } - if (c->setParameters(params8) != NO_ERROR) { + if (camera->setParameters(params8) != NO_ERROR) { jniThrowException(env, "java/lang/IllegalArgumentException", "setParameters failed"); return; } @@ -400,20 +424,20 @@ static void android_hardware_Camera_setParameters(JNIEnv *env, jobject thiz, jst static jstring android_hardware_Camera_getParameters(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return 0; + LOGV("getParameters"); + sp camera = get_native_camera(env, thiz, NULL); + if (camera == 0) return 0; - return env->NewStringUTF(c->getParameters().string()); + return env->NewStringUTF(camera->getParameters().string()); } static void android_hardware_Camera_reconnect(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return; + LOGV("reconnect"); + sp camera = get_native_camera(env, thiz, NULL); + if (camera == 0) return; - if (c->reconnect() != NO_ERROR) { + if (camera->reconnect() != NO_ERROR) { jniThrowException(env, "java/io/IOException", "reconnect failed"); return; } @@ -421,18 +445,18 @@ static void android_hardware_Camera_reconnect(JNIEnv *env, jobject thiz) static jint android_hardware_Camera_lock(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return INVALID_OPERATION; - return (jint) c->lock(); + LOGV("lock"); + sp camera = get_native_camera(env, thiz, NULL); + if (camera == 0) return INVALID_OPERATION; + return (jint) camera->lock(); } static jint android_hardware_Camera_unlock(JNIEnv *env, jobject thiz) { - sp c = get_native_camera(env, thiz); - if (c == 0) - return INVALID_OPERATION; - return (jint) c->unlock(); + LOGV("unlock"); + sp camera = get_native_camera(env, thiz, NULL); + if (camera == 0) return INVALID_OPERATION; + return (jint) camera->unlock(); } //------------------------------------------------- @@ -516,7 +540,6 @@ int register_android_hardware_Camera(JNIEnv *env) { field fields_to_find[] = { { "android/hardware/Camera", "mNativeContext", "I", &fields.context }, - { "android/hardware/Camera", "mListenerContext", "I", &fields.listener_context }, { "android/view/Surface", "mSurface", "I", &fields.surface } }; diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp index e4586d9238e7a8e02843546f72c443e31423ad5e..288433af6a0d0f66150aaca3cfd424de2f7c9d2b 100644 --- a/core/jni/android_media_AudioRecord.cpp +++ b/core/jni/android_media_AudioRecord.cpp @@ -63,11 +63,11 @@ struct audiorecord_callback_cookie { #define AUDIORECORD_ERROR -1 #define AUDIORECORD_ERROR_BAD_VALUE -2 #define AUDIORECORD_ERROR_INVALID_OPERATION -3 -#define AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT -4 -#define AUDIORECORD_ERROR_SETUP_INVALIDCHANNELCOUNT -5 -#define AUDIORECORD_ERROR_SETUP_INVALIDFORMAT -6 -#define AUDIORECORD_ERROR_SETUP_INVALIDSTREAMTYPE -7 -#define AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED -8 +#define AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT -16 +#define AUDIORECORD_ERROR_SETUP_INVALIDCHANNELCOUNT -17 +#define AUDIORECORD_ERROR_SETUP_INVALIDFORMAT -18 +#define AUDIORECORD_ERROR_SETUP_INVALIDSTREAMTYPE -19 +#define AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED -20 jint android_media_translateRecorderErrorCode(int code) { switch(code) { @@ -267,7 +267,7 @@ static void android_media_AudioRecord_finalize(JNIEnv *env, jobject thiz) { (AudioRecord *)env->GetIntField(thiz, javaAudioRecordFields.nativeRecorderInJavaObj); if (lpRecorder) { - //LOGV("About to delete lpRecorder: %x\n", (int)lpRecorder); + LOGV("About to delete lpRecorder: %x\n", (int)lpRecorder); lpRecorder->stop(); delete lpRecorder; } @@ -448,6 +448,39 @@ static jint android_media_AudioRecord_get_pos_update_period(JNIEnv *env, jobjec } +// ---------------------------------------------------------------------------- +// returns the minimum required size for the successful creation of an AudioRecord instance. +// returns 0 if the parameter combination is not supported. +// return -1 if there was an error querying the buffer size. +static jint android_media_AudioRecord_get_min_buff_size(JNIEnv *env, jobject thiz, + jint sampleRateInHertz, jint nbChannels, jint audioFormat) { + + size_t inputBuffSize = 0; + LOGV(">> android_media_AudioRecord_get_min_buff_size(%d, %d, %d)", sampleRateInHertz, nbChannels, audioFormat); + + status_t result = AudioSystem::getInputBufferSize( + sampleRateInHertz, + (audioFormat == javaAudioRecordFields.PCM16 ? + AudioSystem::PCM_16_BIT : AudioSystem::PCM_8_BIT), + nbChannels, &inputBuffSize); + switch(result) { + case(NO_ERROR): + if(inputBuffSize == 0) { + LOGV("Recording parameters are not supported: %dHz, %d channel(s), (java) format %d", + sampleRateInHertz, nbChannels, audioFormat); + return 0; + } else { + // the minimum buffer size is twice the hardware input buffer size + return 2*inputBuffSize; + } + break; + case(PERMISSION_DENIED): + default: + return -1; + } +} + + // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- static JNINativeMethod gMethods[] = { @@ -470,6 +503,8 @@ static JNINativeMethod gMethods[] = { "(I)I", (void *)android_media_AudioRecord_set_pos_update_period}, {"native_get_pos_update_period", "()I", (void *)android_media_AudioRecord_get_pos_update_period}, + {"native_get_min_buff_size", + "(III)I", (void *)android_media_AudioRecord_get_min_buff_size}, }; // field names found in android/media/AudioRecord.java diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp index 99785a28bdb9eee90441a8023f971ad05e9988a4..692610ea42ccad3b6e2359f1776bc67a165dacf5 100644 --- a/core/jni/android_media_AudioSystem.cpp +++ b/core/jni/android_media_AudioSystem.cpp @@ -53,11 +53,8 @@ static int android_media_AudioSystem_setVolume(JNIEnv *env, jobject clazz, jint type, jint volume) { LOGV("setVolume(%d)", int(volume)); - if (int(type) == AudioTrack::VOICE_CALL) { - return check_AudioSystem_Command(AudioSystem::setStreamVolume(type, float(volume) / 100.0)); - } else { - return check_AudioSystem_Command(AudioSystem::setStreamVolume(type, AudioSystem::linearToLog(volume))); - } + + return check_AudioSystem_Command(AudioSystem::setStreamVolume(type, AudioSystem::linearToLog(volume))); } static int @@ -66,12 +63,7 @@ android_media_AudioSystem_getVolume(JNIEnv *env, jobject clazz, jint type) float v; int v_int = -1; if (AudioSystem::getStreamVolume(int(type), &v) == NO_ERROR) { - // voice call volume is converted to log scale in the hardware - if (int(type) == AudioTrack::VOICE_CALL) { - v_int = lrint(v * 100.0); - } else { - v_int = AudioSystem::logToLinear(v); - } + v_int = AudioSystem::logToLinear(v); } return v_int; } diff --git a/core/jni/android_media_AudioTrack.cpp b/core/jni/android_media_AudioTrack.cpp index 6bbcaeefca976077c2a14d0ff4584bd766bf526a..f625ffbffc4b15562fbfd1be5c3ccecbe7feae98 100644 --- a/core/jni/android_media_AudioTrack.cpp +++ b/core/jni/android_media_AudioTrack.cpp @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#define LOG_NDEBUG 0 +//#define LOG_NDEBUG 0 #define LOG_TAG "AudioTrack-JNI" @@ -53,6 +53,7 @@ struct fields_t { int STREAM_MUSIC; //... stream type constants int STREAM_ALARM; //... stream type constants int STREAM_NOTIFICATION; //... stream type constants + int STREAM_BLUETOOTH_SCO; //... stream type constants int MODE_STREAM; //... memory mode int MODE_STATIC; //... memory mode jfieldID nativeTrackInJavaObj; // stores in Java the native AudioTrack object @@ -71,6 +72,7 @@ class AudioTrackJniStorage { sp mMemHeap; sp mMemBase; audiotrack_callback_cookie mCallbackData; + int mStreamType; AudioTrackJniStorage() { } @@ -95,13 +97,13 @@ class AudioTrackJniStorage { #define AUDIOTRACK_SUCCESS 0 #define AUDIOTRACK_ERROR -1 -#define AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM -2 -#define AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELCOUNT -3 -#define AUDIOTRACK_ERROR_SETUP_INVALIDFORMAT -4 -#define AUDIOTRACK_ERROR_SETUP_INVALIDSTREAMTYPE -5 -#define AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED -6 -#define AUDIOTRACK_ERROR_BAD_VALUE -7 -#define AUDIOTRACK_ERROR_INVALID_OPERATION -8 +#define AUDIOTRACK_ERROR_BAD_VALUE -2 +#define AUDIOTRACK_ERROR_INVALID_OPERATION -3 +#define AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM -16 +#define AUDIOTRACK_ERROR_SETUP_INVALIDCHANNELCOUNT -17 +#define AUDIOTRACK_ERROR_SETUP_INVALIDFORMAT -18 +#define AUDIOTRACK_ERROR_SETUP_INVALIDSTREAMTYPE -19 +#define AUDIOTRACK_ERROR_SETUP_NATIVEINITFAILED -20 jint android_media_translateErrorCode(int code) { @@ -162,16 +164,16 @@ android_media_AudioTrack_native_setup(JNIEnv *env, jobject thiz, jobject weak_th jint streamType, jint sampleRateInHertz, jint nbChannels, jint audioFormat, jint buffSizeInBytes, jint memoryMode) { - //LOGV("sampleRate=%d, audioFormat(from Java)=%d, nbChannels=%d, buffSize=%d", - // sampleRateInHertz, audioFormat, nbChannels, buffSizeInBytes); + LOGV("sampleRate=%d, audioFormat(from Java)=%d, nbChannels=%d, buffSize=%d", + sampleRateInHertz, audioFormat, nbChannels, buffSizeInBytes); int afSampleRate; int afFrameCount; - if (AudioSystem::getOutputFrameCount(&afFrameCount) != NO_ERROR) { + if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) { LOGE("Error creating AudioTrack: Could not get AudioSystem frame count."); return AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM; } - if (AudioSystem::getOutputSamplingRate(&afSampleRate) != NO_ERROR) { + if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) { LOGE("Error creating AudioTrack: Could not get AudioSystem sampling rate."); return AUDIOTRACK_ERROR_SETUP_AUDIOSYSTEM; } @@ -182,23 +184,25 @@ android_media_AudioTrack_native_setup(JNIEnv *env, jobject thiz, jobject weak_th } // check the stream type - AudioTrack::stream_type atStreamType; + AudioSystem::stream_type atStreamType; if (streamType == javaAudioTrackFields.STREAM_VOICE_CALL) { - atStreamType = AudioTrack::VOICE_CALL; + atStreamType = AudioSystem::VOICE_CALL; } else if (streamType == javaAudioTrackFields.STREAM_SYSTEM) { - atStreamType = AudioTrack::SYSTEM; + atStreamType = AudioSystem::SYSTEM; } else if (streamType == javaAudioTrackFields.STREAM_RING) { - atStreamType = AudioTrack::RING; + atStreamType = AudioSystem::RING; } else if (streamType == javaAudioTrackFields.STREAM_MUSIC) { - atStreamType = AudioTrack::MUSIC; + atStreamType = AudioSystem::MUSIC; } else if (streamType == javaAudioTrackFields.STREAM_ALARM) { - atStreamType = AudioTrack::ALARM; + atStreamType = AudioSystem::ALARM; } else if (streamType == javaAudioTrackFields.STREAM_NOTIFICATION) { - atStreamType = AudioTrack::NOTIFICATION; + atStreamType = AudioSystem::NOTIFICATION; + } else if (streamType == javaAudioTrackFields.STREAM_BLUETOOTH_SCO) { + atStreamType = AudioSystem::BLUETOOTH_SCO; } else { LOGE("Error creating AudioTrack: unknown stream type."); return AUDIOTRACK_ERROR_SETUP_INVALIDSTREAMTYPE; - } + } // check the format. // This function was called from Java, so we compare the format against the Java constants @@ -206,7 +210,20 @@ android_media_AudioTrack_native_setup(JNIEnv *env, jobject thiz, jobject weak_th LOGE("Error creating AudioTrack: unsupported audio format."); return AUDIOTRACK_ERROR_SETUP_INVALIDFORMAT; } - + + // for the moment 8bitPCM in MODE_STATIC is not supported natively in the AudioTrack C++ class + // so we declare everything as 16bitPCM, the 8->16bit conversion for MODE_STATIC will be handled + // in android_media_AudioTrack_native_write() + if ((audioFormat == javaAudioTrackFields.PCM8) + && (memoryMode == javaAudioTrackFields.MODE_STATIC)) { + LOGV("android_media_AudioTrack_native_setup(): requesting MODE_STATIC for 8bit \ + buff size of %dbytes, switching to 16bit, buff size of %dbytes", + buffSizeInBytes, 2*buffSizeInBytes); + audioFormat = javaAudioTrackFields.PCM16; + // we will need twice the memory to store the data + buffSizeInBytes *= 2; + } + // compute the frame count int bytesPerSample = audioFormat == javaAudioTrackFields.PCM16 ? 2 : 1; int format = audioFormat == javaAudioTrackFields.PCM16 ? @@ -235,6 +252,8 @@ android_media_AudioTrack_native_setup(JNIEnv *env, jobject thiz, jobject weak_th // we use a weak reference so the AudioTrack object can be garbage collected. lpJniStorage->mCallbackData.audioTrack_ref = env->NewGlobalRef(weak_this); + lpJniStorage->mStreamType = atStreamType; + // create the native AudioTrack object AudioTrack* lpTrack = new AudioTrack(); if (lpTrack == NULL) { @@ -381,13 +400,13 @@ android_media_AudioTrack_set_volume(JNIEnv *env, jobject thiz, jfloat leftVol, j // ---------------------------------------------------------------------------- static void android_media_AudioTrack_native_finalize(JNIEnv *env, jobject thiz) { - LOGV("android_media_AudioTrack_native_finalize jobject: %x\n", (int)thiz); + //LOGV("android_media_AudioTrack_native_finalize jobject: %x\n", (int)thiz); // delete the AudioTrack object AudioTrack *lpTrack = (AudioTrack *)env->GetIntField( thiz, javaAudioTrackFields.nativeTrackInJavaObj); if (lpTrack) { - LOGV("deleting lpTrack: %x\n", (int)lpTrack); + //LOGV("deleting lpTrack: %x\n", (int)lpTrack); lpTrack->stop(); delete lpTrack; } @@ -396,7 +415,7 @@ static void android_media_AudioTrack_native_finalize(JNIEnv *env, jobject thiz) AudioTrackJniStorage* pJniStorage = (AudioTrackJniStorage *)env->GetIntField( thiz, javaAudioTrackFields.jniData); if (pJniStorage) { - LOGV("deleting pJniStorage: %x\n", (int)pJniStorage); + //LOGV("deleting pJniStorage: %x\n", (int)pJniStorage); delete pJniStorage; } } @@ -416,7 +435,8 @@ static void android_media_AudioTrack_native_release(JNIEnv *env, jobject thiz) // ---------------------------------------------------------------------------- static jint android_media_AudioTrack_native_write(JNIEnv *env, jobject thiz, jbyteArray javaAudioData, - jint offsetInBytes, jint sizeInBytes) { + jint offsetInBytes, jint sizeInBytes, + jint javaAudioFormat) { jbyte* cAudioData = NULL; AudioTrack *lpTrack = NULL; //LOGV("android_media_AudioTrack_native_write(offset=%d, sizeInBytes=%d) called", @@ -447,8 +467,22 @@ static jint android_media_AudioTrack_native_write(JNIEnv *env, jobject thiz, if (lpTrack->sharedBuffer() == 0) { written = lpTrack->write(cAudioData + offsetInBytes, sizeInBytes); } else { - memcpy(lpTrack->sharedBuffer()->pointer(), cAudioData + offsetInBytes, sizeInBytes); - written = sizeInBytes; + if (javaAudioFormat == javaAudioTrackFields.PCM16) { + memcpy(lpTrack->sharedBuffer()->pointer(), cAudioData + offsetInBytes, sizeInBytes); + written = sizeInBytes; + } else if (javaAudioFormat == javaAudioTrackFields.PCM8) { + // cAudioData contains 8bit data we need to expand to 16bit before copying + // to the shared memory + int count = sizeInBytes; + int16_t *dst = (int16_t *)lpTrack->sharedBuffer()->pointer(); + const int8_t *src = (const int8_t *)(cAudioData + offsetInBytes); + while(count--) { + *dst++ = (int16_t)(*src++^0x80) << 8; + } + // even though we wrote 2*sizeInBytes, we only report sizeInBytes as written to hide + // the 8bit mixer restriction from the user of this function + written = sizeInBytes; + } } env->ReleasePrimitiveArrayCritical(javaAudioData, cAudioData, 0); @@ -462,10 +496,12 @@ static jint android_media_AudioTrack_native_write(JNIEnv *env, jobject thiz, // ---------------------------------------------------------------------------- static jint android_media_AudioTrack_native_write_short(JNIEnv *env, jobject thiz, jshortArray javaAudioData, - jint offsetInShorts, jint sizeInShorts) { + jint offsetInShorts, jint sizeInShorts, + jint javaAudioFormat) { return (android_media_AudioTrack_native_write(env, thiz, (jbyteArray) javaAudioData, - offsetInShorts*2, sizeInShorts*2) + offsetInShorts*2, sizeInShorts*2, + javaAudioFormat) / 2); } @@ -652,9 +688,33 @@ static jint android_media_AudioTrack_reload(JNIEnv *env, jobject thiz) { // ---------------------------------------------------------------------------- -static jint android_media_AudioTrack_get_output_sample_rate(JNIEnv *env, jobject thiz) { +static jint android_media_AudioTrack_get_output_sample_rate(JNIEnv *env, jobject thiz, + jint javaStreamType) { int afSamplingRate; - if (AudioSystem::getOutputSamplingRate(&afSamplingRate) != NO_ERROR) { + // convert the stream type from Java to native value + // FIXME: code duplication with android_media_AudioTrack_native_setup() + AudioSystem::stream_type nativeStreamType; + if (javaStreamType == javaAudioTrackFields.STREAM_VOICE_CALL) { + nativeStreamType = AudioSystem::VOICE_CALL; + } else if (javaStreamType == javaAudioTrackFields.STREAM_SYSTEM) { + nativeStreamType = AudioSystem::SYSTEM; + } else if (javaStreamType == javaAudioTrackFields.STREAM_RING) { + nativeStreamType = AudioSystem::RING; + } else if (javaStreamType == javaAudioTrackFields.STREAM_MUSIC) { + nativeStreamType = AudioSystem::MUSIC; + } else if (javaStreamType == javaAudioTrackFields.STREAM_ALARM) { + nativeStreamType = AudioSystem::ALARM; + } else if (javaStreamType == javaAudioTrackFields.STREAM_NOTIFICATION) { + nativeStreamType = AudioSystem::NOTIFICATION; + } else if (javaStreamType == javaAudioTrackFields.STREAM_BLUETOOTH_SCO) { + nativeStreamType = AudioSystem::BLUETOOTH_SCO; + } else { + nativeStreamType = AudioSystem::DEFAULT; + } + + if (AudioSystem::getOutputSamplingRate(&afSamplingRate, nativeStreamType) != NO_ERROR) { + LOGE("AudioSystem::getOutputSamplingRate() for stream type %d failed in AudioTrack JNI", + nativeStreamType); return DEFAULT_OUTPUT_SAMPLE_RATE; } else { return afSamplingRate; @@ -662,6 +722,36 @@ static jint android_media_AudioTrack_get_output_sample_rate(JNIEnv *env, jobjec } +// ---------------------------------------------------------------------------- +// returns the minimum required size for the successful creation of a streaming AudioTrack +// returns -1 if there was an error querying the hardware. +static jint android_media_AudioTrack_get_min_buff_size(JNIEnv *env, jobject thiz, + jint sampleRateInHertz, jint nbChannels, jint audioFormat) { + int afSamplingRate; + int afFrameCount; + uint32_t afLatency; + + if (AudioSystem::getOutputSamplingRate(&afSamplingRate) != NO_ERROR) { + return -1; + } + if (AudioSystem::getOutputFrameCount(&afFrameCount) != NO_ERROR) { + return -1; + } + + if (AudioSystem::getOutputLatency(&afLatency) != NO_ERROR) { + return -1; + } + + // Ensure that buffer depth covers at least audio hardware latency + uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSamplingRate); + uint32_t minFrameCount = (afFrameCount*sampleRateInHertz*minBufCount)/afSamplingRate; + int minBuffSize = minFrameCount + * (audioFormat == javaAudioTrackFields.PCM16 ? 2 : 1) + * nbChannels; + return minBuffSize; +} + + // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- static JNINativeMethod gMethods[] = { @@ -674,8 +764,8 @@ static JNINativeMethod gMethods[] = { (void *)android_media_AudioTrack_native_setup}, {"native_finalize", "()V", (void *)android_media_AudioTrack_native_finalize}, {"native_release", "()V", (void *)android_media_AudioTrack_native_release}, - {"native_write_byte", "([BII)I", (void *)android_media_AudioTrack_native_write}, - {"native_write_short", "([SII)I", (void *)android_media_AudioTrack_native_write_short}, + {"native_write_byte", "([BIII)I", (void *)android_media_AudioTrack_native_write}, + {"native_write_short", "([SIII)I", (void *)android_media_AudioTrack_native_write_short}, {"native_setVolume", "(FF)V", (void *)android_media_AudioTrack_set_volume}, {"native_get_native_frame_count", "()I", (void *)android_media_AudioTrack_get_native_frame_count}, @@ -694,25 +784,28 @@ static JNINativeMethod gMethods[] = { {"native_set_loop", "(III)I", (void *)android_media_AudioTrack_set_loop}, {"native_reload_static", "()I", (void *)android_media_AudioTrack_reload}, {"native_get_output_sample_rate", - "()I", (void *)android_media_AudioTrack_get_output_sample_rate}, + "(I)I", (void *)android_media_AudioTrack_get_output_sample_rate}, + {"native_get_min_buff_size", + "(III)I", (void *)android_media_AudioTrack_get_min_buff_size}, }; // field names found in android/media/AudioTrack.java -#define JAVA_POSTEVENT_CALLBACK_NAME "postEventFromNative" -#define JAVA_CONST_PCM16_NAME "ENCODING_PCM_16BIT" -#define JAVA_CONST_PCM8_NAME "ENCODING_PCM_8BIT" -#define JAVA_CONST_BUFFER_COUNT_NAME "BUFFER_COUNT" -#define JAVA_CONST_STREAM_VOICE_CALL_NAME "STREAM_VOICE_CALL" -#define JAVA_CONST_STREAM_SYSTEM_NAME "STREAM_SYSTEM" -#define JAVA_CONST_STREAM_RING_NAME "STREAM_RING" -#define JAVA_CONST_STREAM_MUSIC_NAME "STREAM_MUSIC" -#define JAVA_CONST_STREAM_ALARM_NAME "STREAM_ALARM" -#define JAVA_CONST_STREAM_NOTIFICATION_NAME "STREAM_NOTIFICATION" -#define JAVA_CONST_MODE_STREAM_NAME "MODE_STREAM" -#define JAVA_CONST_MODE_STATIC_NAME "MODE_STATIC" -#define JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME "mNativeTrackInJavaObj" -#define JAVA_JNIDATA_FIELD_NAME "mJniData" +#define JAVA_POSTEVENT_CALLBACK_NAME "postEventFromNative" +#define JAVA_CONST_PCM16_NAME "ENCODING_PCM_16BIT" +#define JAVA_CONST_PCM8_NAME "ENCODING_PCM_8BIT" +#define JAVA_CONST_BUFFER_COUNT_NAME "BUFFER_COUNT" +#define JAVA_CONST_STREAM_VOICE_CALL_NAME "STREAM_VOICE_CALL" +#define JAVA_CONST_STREAM_SYSTEM_NAME "STREAM_SYSTEM" +#define JAVA_CONST_STREAM_RING_NAME "STREAM_RING" +#define JAVA_CONST_STREAM_MUSIC_NAME "STREAM_MUSIC" +#define JAVA_CONST_STREAM_ALARM_NAME "STREAM_ALARM" +#define JAVA_CONST_STREAM_NOTIFICATION_NAME "STREAM_NOTIFICATION" +#define JAVA_CONST_STREAM_BLUETOOTH_SCO_NAME "STREAM_BLUETOOTH_SCO" +#define JAVA_CONST_MODE_STREAM_NAME "MODE_STREAM" +#define JAVA_CONST_MODE_STATIC_NAME "MODE_STATIC" +#define JAVA_NATIVETRACKINJAVAOBJ_FIELD_NAME "mNativeTrackInJavaObj" +#define JAVA_JNIDATA_FIELD_NAME "mJniData" #define JAVA_AUDIOFORMAT_CLASS_NAME "android/media/AudioFormat" #define JAVA_AUDIOMANAGER_CLASS_NAME "android/media/AudioManager" @@ -810,28 +903,32 @@ int register_android_media_AudioTrack(JNIEnv *env) LOGE("Can't find %s", JAVA_AUDIOMANAGER_CLASS_NAME); return -1; } - if ( !android_media_getIntConstantFromClass(env, audioManagerClass, - JAVA_AUDIOMANAGER_CLASS_NAME, + if ( !android_media_getIntConstantFromClass(env, audioManagerClass, + JAVA_AUDIOMANAGER_CLASS_NAME, JAVA_CONST_STREAM_VOICE_CALL_NAME, &(javaAudioTrackFields.STREAM_VOICE_CALL)) - || !android_media_getIntConstantFromClass(env, audioManagerClass, - JAVA_AUDIOMANAGER_CLASS_NAME, + || !android_media_getIntConstantFromClass(env, audioManagerClass, + JAVA_AUDIOMANAGER_CLASS_NAME, JAVA_CONST_STREAM_MUSIC_NAME, &(javaAudioTrackFields.STREAM_MUSIC)) - || !android_media_getIntConstantFromClass(env, audioManagerClass, - JAVA_AUDIOMANAGER_CLASS_NAME, + || !android_media_getIntConstantFromClass(env, audioManagerClass, + JAVA_AUDIOMANAGER_CLASS_NAME, JAVA_CONST_STREAM_SYSTEM_NAME, &(javaAudioTrackFields.STREAM_SYSTEM)) - || !android_media_getIntConstantFromClass(env, audioManagerClass, - JAVA_AUDIOMANAGER_CLASS_NAME, + || !android_media_getIntConstantFromClass(env, audioManagerClass, + JAVA_AUDIOMANAGER_CLASS_NAME, JAVA_CONST_STREAM_RING_NAME, &(javaAudioTrackFields.STREAM_RING)) || !android_media_getIntConstantFromClass(env, audioManagerClass, - JAVA_AUDIOMANAGER_CLASS_NAME, + JAVA_AUDIOMANAGER_CLASS_NAME, JAVA_CONST_STREAM_ALARM_NAME, &(javaAudioTrackFields.STREAM_ALARM)) || !android_media_getIntConstantFromClass(env, audioManagerClass, - JAVA_AUDIOMANAGER_CLASS_NAME, - JAVA_CONST_STREAM_NOTIFICATION_NAME, &(javaAudioTrackFields.STREAM_NOTIFICATION)) ) { + JAVA_AUDIOMANAGER_CLASS_NAME, + JAVA_CONST_STREAM_NOTIFICATION_NAME, &(javaAudioTrackFields.STREAM_NOTIFICATION)) + || !android_media_getIntConstantFromClass(env, audioManagerClass, + JAVA_AUDIOMANAGER_CLASS_NAME, + JAVA_CONST_STREAM_BLUETOOTH_SCO_NAME, + &(javaAudioTrackFields.STREAM_BLUETOOTH_SCO))) { // error log performed in android_media_getIntConstantFromClass() return -1; } - + return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); } diff --git a/core/jni/android_media_JetPlayer.cpp b/core/jni/android_media_JetPlayer.cpp index 994f16184c8c21d80c141a79cdae4002dc30c948..e345af62131411cda7779a9085d3670cc90bdb89 100644 --- a/core/jni/android_media_JetPlayer.cpp +++ b/core/jni/android_media_JetPlayer.cpp @@ -81,7 +81,7 @@ android_media_JetPlayer_setup(JNIEnv *env, jobject thiz, jobject weak_this, jint maxTracks, jint trackBufferSize) { //LOGV("android_media_JetPlayer_setup(): entering."); - JetPlayer* lpJet = new JetPlayer(weak_this, maxTracks, trackBufferSize); + JetPlayer* lpJet = new JetPlayer(env->NewGlobalRef(weak_this), maxTracks, trackBufferSize); EAS_RESULT result = lpJet->init(); @@ -127,7 +127,7 @@ android_media_JetPlayer_release(JNIEnv *env, jobject thiz) // ---------------------------------------------------------------------------- static jboolean -android_media_JetPlayer_openFile(JNIEnv *env, jobject thiz, jstring path) +android_media_JetPlayer_loadFromFile(JNIEnv *env, jobject thiz, jstring path) { JetPlayer *lpJet = (JetPlayer *)env->GetIntField( thiz, javaJetPlayerFields.nativePlayerInJavaObj); @@ -139,7 +139,6 @@ android_media_JetPlayer_openFile(JNIEnv *env, jobject thiz, jstring path) // set up event callback function lpJet->setEventCallback(jetPlayerEventCallback); - const char *pathStr = env->GetStringUTFChars(path, NULL); if (pathStr == NULL) { // Out of memory LOGE("android_media_JetPlayer_openFile(): aborting, out of memory"); @@ -148,7 +147,7 @@ android_media_JetPlayer_openFile(JNIEnv *env, jobject thiz, jstring path) } LOGV("android_media_JetPlayer_openFile(): trying to open %s", pathStr ); - EAS_RESULT result = lpJet->openFile(pathStr); + EAS_RESULT result = lpJet->loadFromFile(pathStr); env->ReleaseStringUTFChars(path, pathStr); if(result==EAS_SUCCESS) { @@ -164,7 +163,8 @@ android_media_JetPlayer_openFile(JNIEnv *env, jobject thiz, jstring path) // ---------------------------------------------------------------------------- static jboolean -android_media_JetPlayer_closeFile(JNIEnv *env, jobject thiz) +android_media_JetPlayer_loadFromFileD(JNIEnv *env, jobject thiz, + jobject fileDescriptor, jlong offset, jlong length) { JetPlayer *lpJet = (JetPlayer *)env->GetIntField( thiz, javaJetPlayerFields.nativePlayerInJavaObj); @@ -173,6 +173,35 @@ android_media_JetPlayer_closeFile(JNIEnv *env, jobject thiz) "Unable to retrieve JetPlayer pointer for openFile()"); } + // set up event callback function + lpJet->setEventCallback(jetPlayerEventCallback); + + LOGV("android_media_JetPlayer_openFileDescr(): trying to load JET file through its fd" ); + EAS_RESULT result = lpJet->loadFromFD(getParcelFileDescriptorFD(env, fileDescriptor), + (long long)offset, (long long)length); // cast params to types used by EAS_FILE + + if(result==EAS_SUCCESS) { + LOGV("android_media_JetPlayer_openFileDescr(): file successfully opened"); + return JNI_TRUE; + } else { + LOGE("android_media_JetPlayer_openFileDescr(): failed to open file with EAS error %d", + (int)result); + return JNI_FALSE; + } +} + + +// ---------------------------------------------------------------------------- +static jboolean +android_media_JetPlayer_closeFile(JNIEnv *env, jobject thiz) +{ + JetPlayer *lpJet = (JetPlayer *)env->GetIntField( + thiz, javaJetPlayerFields.nativePlayerInJavaObj); + if (lpJet == NULL ) { + jniThrowException(env, "java/lang/IllegalStateException", + "Unable to retrieve JetPlayer pointer for closeFile()"); + } + if( lpJet->closeFile()==EAS_SUCCESS) { //LOGV("android_media_JetPlayer_closeFile(): file successfully closed"); return JNI_TRUE; @@ -191,7 +220,7 @@ android_media_JetPlayer_play(JNIEnv *env, jobject thiz) thiz, javaJetPlayerFields.nativePlayerInJavaObj); if (lpJet == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", - "Unable to retrieve JetPlayer pointer for openFile()"); + "Unable to retrieve JetPlayer pointer for play()"); } EAS_RESULT result = lpJet->play(); @@ -214,7 +243,7 @@ android_media_JetPlayer_pause(JNIEnv *env, jobject thiz) thiz, javaJetPlayerFields.nativePlayerInJavaObj); if (lpJet == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", - "Unable to retrieve JetPlayer pointer for openFile()"); + "Unable to retrieve JetPlayer pointer for pause()"); } EAS_RESULT result = lpJet->pause(); @@ -243,7 +272,7 @@ android_media_JetPlayer_queueSegment(JNIEnv *env, jobject thiz, thiz, javaJetPlayerFields.nativePlayerInJavaObj); if (lpJet == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", - "Unable to retrieve JetPlayer pointer for openFile()"); + "Unable to retrieve JetPlayer pointer for queueSegment()"); } EAS_RESULT result @@ -269,7 +298,7 @@ android_media_JetPlayer_queueSegmentMuteArray(JNIEnv *env, jobject thiz, thiz, javaJetPlayerFields.nativePlayerInJavaObj); if (lpJet == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", - "Unable to retrieve JetPlayer pointer for openFile()"); + "Unable to retrieve JetPlayer pointer for queueSegmentMuteArray()"); } EAS_RESULT result=EAS_FAILURE; @@ -314,7 +343,7 @@ android_media_JetPlayer_setMuteFlags(JNIEnv *env, jobject thiz, thiz, javaJetPlayerFields.nativePlayerInJavaObj); if (lpJet == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", - "Unable to retrieve JetPlayer pointer for openFile()"); + "Unable to retrieve JetPlayer pointer for setMuteFlags()"); } EAS_RESULT result; @@ -338,7 +367,7 @@ android_media_JetPlayer_setMuteArray(JNIEnv *env, jobject thiz, thiz, javaJetPlayerFields.nativePlayerInJavaObj); if (lpJet == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", - "Unable to retrieve JetPlayer pointer for openFile()"); + "Unable to retrieve JetPlayer pointer for setMuteArray()"); } EAS_RESULT result=EAS_FAILURE; @@ -367,7 +396,8 @@ android_media_JetPlayer_setMuteArray(JNIEnv *env, jobject thiz, //LOGV("android_media_JetPlayer_setMuteArray(): mute flags successfully updated"); return JNI_TRUE; } else { - LOGE("android_media_JetPlayer_setMuteArray(): failed to update mute flags with EAS error code %ld", result); + LOGE("android_media_JetPlayer_setMuteArray(): \ + failed to update mute flags with EAS error code %ld", result); return JNI_FALSE; } } @@ -382,7 +412,7 @@ android_media_JetPlayer_setMuteFlag(JNIEnv *env, jobject thiz, thiz, javaJetPlayerFields.nativePlayerInJavaObj); if (lpJet == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", - "Unable to retrieve JetPlayer pointer for openFile()"); + "Unable to retrieve JetPlayer pointer for setMuteFlag()"); } EAS_RESULT result; @@ -407,7 +437,7 @@ android_media_JetPlayer_triggerClip(JNIEnv *env, jobject thiz, jint clipId) thiz, javaJetPlayerFields.nativePlayerInJavaObj); if (lpJet == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", - "Unable to retrieve JetPlayer pointer for openFile()"); + "Unable to retrieve JetPlayer pointer for triggerClip()"); } EAS_RESULT result; @@ -423,6 +453,29 @@ android_media_JetPlayer_triggerClip(JNIEnv *env, jobject thiz, jint clipId) } +// ---------------------------------------------------------------------------- +static jboolean +android_media_JetPlayer_clearQueue(JNIEnv *env, jobject thiz) +{ + JetPlayer *lpJet = (JetPlayer *)env->GetIntField( + thiz, javaJetPlayerFields.nativePlayerInJavaObj); + if (lpJet == NULL ) { + jniThrowException(env, "java/lang/IllegalStateException", + "Unable to retrieve JetPlayer pointer for clearQueue()"); + } + + EAS_RESULT result = lpJet->clearQueue(); + if(result==EAS_SUCCESS) { + //LOGV("android_media_JetPlayer_clearQueue(): clearQueue successful"); + return JNI_TRUE; + } else { + LOGE("android_media_JetPlayer_clearQueue(): clearQueue failed with EAS error code %ld", + result); + return JNI_FALSE; + } +} + + // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- static JNINativeMethod gMethods[] = { @@ -430,7 +483,10 @@ static JNINativeMethod gMethods[] = { {"native_setup", "(Ljava/lang/Object;II)Z", (void *)android_media_JetPlayer_setup}, {"native_finalize", "()V", (void *)android_media_JetPlayer_finalize}, {"native_release", "()V", (void *)android_media_JetPlayer_release}, - {"native_openJetFile", "(Ljava/lang/String;)Z", (void *)android_media_JetPlayer_openFile}, + {"native_loadJetFromFile", + "(Ljava/lang/String;)Z", (void *)android_media_JetPlayer_loadFromFile}, + {"native_loadJetFromFileD", "(Ljava/io/FileDescriptor;JJ)Z", + (void *)android_media_JetPlayer_loadFromFileD}, {"native_closeJetFile","()Z", (void *)android_media_JetPlayer_closeFile}, {"native_playJet", "()Z", (void *)android_media_JetPlayer_play}, {"native_pauseJet", "()Z", (void *)android_media_JetPlayer_pause}, @@ -442,6 +498,7 @@ static JNINativeMethod gMethods[] = { {"native_setMuteArray","([ZZ)Z", (void *)android_media_JetPlayer_setMuteArray}, {"native_setMuteFlag", "(IZZ)Z", (void *)android_media_JetPlayer_setMuteFlag}, {"native_triggerClip", "(I)Z", (void *)android_media_JetPlayer_triggerClip}, + {"native_clearQueue", "()Z", (void *)android_media_JetPlayer_clearQueue}, }; #define JAVA_NATIVEJETPLAYERINJAVAOBJ_FIELD_NAME "mNativePlayerInJavaObj" diff --git a/core/jni/android_net_wifi_Wifi.cpp b/core/jni/android_net_wifi_Wifi.cpp index 722b5b8165ab33c53d5c80c3cfe67ad8ac669818..fcab8130d4b3d24a97647dac35ff813fc88067e7 100644 --- a/core/jni/android_net_wifi_Wifi.cpp +++ b/core/jni/android_net_wifi_Wifi.cpp @@ -287,6 +287,24 @@ static jboolean android_net_wifi_stopDriverCommand(JNIEnv* env, jobject clazz) return doBooleanCommand("DRIVER STOP", "OK"); } +static jboolean android_net_wifi_startPacketFiltering(JNIEnv* env, jobject clazz) +{ + return doBooleanCommand("DRIVER RXFILTER-ADD 0", "OK") + && doBooleanCommand("DRIVER RXFILTER-ADD 1", "OK") + && doBooleanCommand("DRIVER RXFILTER-START", "OK"); +} + +static jboolean android_net_wifi_stopPacketFiltering(JNIEnv* env, jobject clazz) +{ + jboolean result = doBooleanCommand("DRIVER RXFILTER-STOP", "OK"); + if (result) { + (void)doBooleanCommand("DRIVER RXFILTER-REMOVE 1", "OK"); + (void)doBooleanCommand("DRIVER RXFILTER-REMOVE 0", "OK"); + } + + return result; +} + static jint android_net_wifi_getRssiCommand(JNIEnv* env, jobject clazz) { char reply[256]; @@ -379,6 +397,16 @@ static jboolean android_net_wifi_setBluetoothCoexistenceModeCommand(JNIEnv* env, return (jboolean)!cmdTooLong && doBooleanCommand(cmdstr, "OK"); } +static jboolean android_net_wifi_setBluetoothCoexistenceScanModeCommand(JNIEnv* env, jobject clazz, jboolean setCoexScanMode) +{ + char cmdstr[256]; + + int numWritten = snprintf(cmdstr, sizeof(cmdstr), "DRIVER BTCOEXSCAN-%s", setCoexScanMode ? "START" : "STOP"); + int cmdTooLong = numWritten >= (int)sizeof(cmdstr); + + return (jboolean)!cmdTooLong && doBooleanCommand(cmdstr, "OK"); +} + static jboolean android_net_wifi_saveConfigCommand(JNIEnv* env, jobject clazz) { // Make sure we never write out a value for AP_SCAN other than 1 @@ -478,11 +506,15 @@ static JNINativeMethod gWifiMethods[] = { { "setScanModeCommand", "(Z)Z", (void*) android_net_wifi_setScanModeCommand }, { "startDriverCommand", "()Z", (void*) android_net_wifi_startDriverCommand }, { "stopDriverCommand", "()Z", (void*) android_net_wifi_stopDriverCommand }, + { "startPacketFiltering", "()Z", (void*) android_net_wifi_startPacketFiltering }, + { "stopPacketFiltering", "()Z", (void*) android_net_wifi_stopPacketFiltering }, { "setPowerModeCommand", "(I)Z", (void*) android_net_wifi_setPowerModeCommand }, { "setNumAllowedChannelsCommand", "(I)Z", (void*) android_net_wifi_setNumAllowedChannelsCommand }, { "getNumAllowedChannelsCommand", "()I", (void*) android_net_wifi_getNumAllowedChannelsCommand }, { "setBluetoothCoexistenceModeCommand", "(I)Z", (void*) android_net_wifi_setBluetoothCoexistenceModeCommand }, + { "setBluetoothCoexistenceScanModeCommand", "(Z)Z", + (void*) android_net_wifi_setBluetoothCoexistenceScanModeCommand }, { "getRssiCommand", "()I", (void*) android_net_wifi_getRssiCommand }, { "getLinkSpeedCommand", "()I", (void*) android_net_wifi_getLinkSpeedCommand }, { "getMacAddressCommand", "()Ljava/lang/String;", (void*) android_net_wifi_getMacAddressCommand }, diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp index 6ba949c421975217b4f41e53d0f135f5742e1749..a6b63d81f2b9aff27a4dcf689f9857bb3d4b7bf1 100644 --- a/core/jni/android_os_Debug.cpp +++ b/core/jni/android_os_Debug.cpp @@ -88,93 +88,101 @@ static jlong android_os_Debug_getNativeHeapFreeSize(JNIEnv *env, jobject clazz) #endif } -static int read_mapinfo(FILE *fp, stats_t* stats) +static void read_mapinfo(FILE *fp, stats_t* stats) { char line[1024]; int len; - int skip; + bool skip, done = false; unsigned start = 0, size = 0, resident = 0, pss = 0; unsigned shared_clean = 0, shared_dirty = 0; unsigned private_clean = 0, private_dirty = 0; unsigned referenced = 0; + unsigned temp; int isNativeHeap; int isDalvikHeap; int isSqliteHeap; -again: - isNativeHeap = 0; - isDalvikHeap = 0; - isSqliteHeap = 0; - skip = 0; - - if(fgets(line, 1024, fp) == 0) return 0; + if(fgets(line, 1024, fp) == 0) return; + + while (!done) { + isNativeHeap = 0; + isDalvikHeap = 0; + isSqliteHeap = 0; + skip = false; - len = strlen(line); - if (len < 1) return 0; - line[--len] = 0; + len = strlen(line); + if (len < 1) return; + line[--len] = 0; - /* ignore guard pages */ - if (line[18] == '-') skip = 1; + /* ignore guard pages */ + if (len > 18 && line[17] == '-') skip = true; - start = strtoul(line, 0, 16); + start = strtoul(line, 0, 16); - if (len >= 50) { - if (!strcmp(line + 49, "[heap]")) { + if (strstr(line, "[heap]")) { isNativeHeap = 1; - } else if (!strncmp(line + 49, "/dalvik-LinearAlloc", strlen("/dalvik-LinearAlloc"))) { + } else if (strstr(line, "/dalvik-LinearAlloc")) { isDalvikHeap = 1; - } else if (!strncmp(line + 49, "/mspace/dalvik-heap", strlen("/mspace/dalvik-heap"))) { + } else if (strstr(line, "/mspace/dalvik-heap")) { isDalvikHeap = 1; - } else if (!strncmp(line + 49, "/dalvik-heap-bitmap/", strlen("/dalvik-heap-bitmap/"))) { + } else if (strstr(line, "/dalvik-heap-bitmap/")) { isDalvikHeap = 1; - } else if (!strncmp(line + 49, "/tmp/sqlite-heap", strlen("/tmp/sqlite-heap"))) { + } else if (strstr(line, "/tmp/sqlite-heap")) { isSqliteHeap = 1; } - } - // TODO: This needs to be fixed to be less fragile. If the order of this file changes or a new - // line is add, this method will return without filling out any of the information. - - if (fgets(line, 1024, fp) == 0) return 0; - if (sscanf(line, "Size: %d kB", &size) != 1) return 0; - if (fgets(line, 1024, fp) == 0) return 0; - if (sscanf(line, "Rss: %d kB", &resident) != 1) return 0; - if (fgets(line, 1024, fp) == 0) return 0; - if (sscanf(line, "Pss: %d kB", &pss) != 1) return 0; - if (fgets(line, 1024, fp) == 0) return 0; - if (sscanf(line, "Shared_Clean: %d kB", &shared_clean) != 1) return 0; - if (fgets(line, 1024, fp) == 0) return 0; - if (sscanf(line, "Shared_Dirty: %d kB", &shared_dirty) != 1) return 0; - if (fgets(line, 1024, fp) == 0) return 0; - if (sscanf(line, "Private_Clean: %d kB", &private_clean) != 1) return 0; - if (fgets(line, 1024, fp) == 0) return 0; - if (sscanf(line, "Private_Dirty: %d kB", &private_dirty) != 1) return 0; - if (fgets(line, 1024, fp) == 0) return 0; - if (sscanf(line, "Referenced: %d kB", &referenced) != 1) return 0; - - if (skip) { - goto again; - } + //LOGI("native=%d dalvik=%d sqlite=%d: %s\n", isNativeHeap, isDalvikHeap, + // isSqliteHeap, line); + + while (true) { + if (fgets(line, 1024, fp) == 0) { + done = true; + break; + } + + if (sscanf(line, "Size: %d kB", &temp) == 1) { + size = temp; + } else if (sscanf(line, "Rss: %d kB", &temp) == 1) { + resident = temp; + } else if (sscanf(line, "Pss: %d kB", &temp) == 1) { + pss = temp; + } else if (sscanf(line, "Shared_Clean: %d kB", &temp) == 1) { + shared_clean = temp; + } else if (sscanf(line, "Shared_Dirty: %d kB", &temp) == 1) { + shared_dirty = temp; + } else if (sscanf(line, "Private_Clean: %d kB", &temp) == 1) { + private_clean = temp; + } else if (sscanf(line, "Private_Dirty: %d kB", &temp) == 1) { + private_dirty = temp; + } else if (sscanf(line, "Referenced: %d kB", &temp) == 1) { + referenced = temp; + } else if (strlen(line) > 40 && line[8] == '-' && line[17] == ' ') { + // looks like a new mapping + // example: "0000a000-00232000 rwxp 0000a000 00:00 0 [heap]" + break; + } + } - if (isNativeHeap) { - stats->nativePss += pss; - stats->nativePrivateDirty += private_dirty; - stats->nativeSharedDirty += shared_dirty; - } else if (isDalvikHeap) { - stats->dalvikPss += pss; - stats->dalvikPrivateDirty += private_dirty; - stats->dalvikSharedDirty += shared_dirty; - } else if (isSqliteHeap) { - // ignore - } else { - stats->otherPss += pss; - stats->otherPrivateDirty += shared_dirty; - stats->otherSharedDirty += private_dirty; + if (!skip) { + if (isNativeHeap) { + stats->nativePss += pss; + stats->nativePrivateDirty += private_dirty; + stats->nativeSharedDirty += shared_dirty; + } else if (isDalvikHeap) { + stats->dalvikPss += pss; + stats->dalvikPrivateDirty += private_dirty; + stats->dalvikSharedDirty += shared_dirty; + } else if ( isSqliteHeap) { + // ignore + } else { + stats->otherPss += pss; + stats->otherPrivateDirty += shared_dirty; + stats->otherSharedDirty += private_dirty; + } + } } - - return 1; } static void load_maps(int pid, stats_t* stats) @@ -185,10 +193,8 @@ static void load_maps(int pid, stats_t* stats) sprintf(tmp, "/proc/%d/smaps", pid); fp = fopen(tmp, "r"); if (fp == 0) return; - - while (read_mapinfo(fp, stats) != 0) { - // Do nothing - } + + read_mapinfo(fp, stats); fclose(fp); } diff --git a/core/jni/android_os_NetStat.cpp b/core/jni/android_os_NetStat.cpp deleted file mode 100644 index 983f719b0255a68dc6b837cbdd5fea5810a320d2..0000000000000000000000000000000000000000 --- a/core/jni/android_os_NetStat.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* //device/libs/android_runtime/android_os_Wifi.cpp -** -** Copyright 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. -*/ - -#define LOG_TAG "NetStat" - -#include "jni.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#if HAVE_ANDROID_OS -#include -#endif - -namespace android { - -static jint android_os_netStatGetTxPkts(JNIEnv* env, jobject clazz) -{ - int ret = 0; - int fd = -1; - char input[50]; - - fd = open("/sys/class/net/rmnet0/statistics/tx_packets", O_RDONLY); - if (fd <= 0) { - fd = open("/sys/class/net/ppp0/statistics/tx_packets", O_RDONLY); - } - - if (fd > 0) { - int size = read(fd, input, 50); - if (size > 0) { - ret = atoi(input); - } - close(fd); - } - - return (jint)ret; -} - -static jint android_os_netStatGetRxPkts(JNIEnv* env, jobject clazz) -{ - int ret = 0; - int fd = -1; - char input[50]; - - fd = open("/sys/class/net/rmnet0/statistics/rx_packets", O_RDONLY); - if (fd <= 0) { - fd = open("/sys/class/net/ppp0/statistics/rx_packets", O_RDONLY); - } - - if (fd > 0) { - int size = read(fd, input, 50); - if (size > 0) { - ret = atoi(input); - } - close(fd); - } - - return (jint)ret; -} - -static jint android_os_netStatGetRxBytes(JNIEnv* env, jobject clazz) -{ - int ret = 0; - int fd = -1; - char input[50]; - - fd = open("/sys/class/net/rmnet0/statistics/rx_bytes", O_RDONLY); - if (fd <= 0) { - fd = open("/sys/class/net/ppp0/statistics/rx_bytes", O_RDONLY); - } - - if (fd > 0) { - int size = read(fd, input, 50); - if (size > 0) { - ret = atoi(input); - } - close(fd); - } - - return (jint)ret; -} - - -static jint android_os_netStatGetTxBytes(JNIEnv* env, jobject clazz) -{ - int ret = 0; - int fd = -1; - char input[50]; - - fd = open("/sys/class/net/rmnet0/statistics/tx_bytes", O_RDONLY); - if (fd <= 0) { - fd = open("/sys/class/net/ppp0/statistics/tx_bytes", O_RDONLY); - } - - if (fd > 0) { - int size = read(fd, input, 50); - if (size > 0) { - ret = atoi(input); - } - close(fd); - } - - return (jint)ret; -} - -// ---------------------------------------------------------------------------- - -/* - * JNI registration. - */ -static JNINativeMethod gMethods[] = { - /* name, signature, funcPtr */ - - { "netStatGetTxPkts", "()I", - (void*) android_os_netStatGetTxPkts }, - - { "netStatGetRxPkts", "()I", - (void*) android_os_netStatGetRxPkts }, - - { "netStatGetTxBytes", "()I", - (void*) android_os_netStatGetTxBytes }, - - { "netStatGetRxBytes", "()I", - (void*) android_os_netStatGetRxBytes }, - -}; - -int register_android_os_NetStat(JNIEnv* env) -{ - jclass netStat = env->FindClass("android/os/NetStat"); - LOG_FATAL_IF(netStat == NULL, "Unable to find class android/os/NetStat"); - - return AndroidRuntime::registerNativeMethods(env, - "android/os/NetStat", gMethods, NELEM(gMethods)); -} - -}; // namespace android - diff --git a/core/jni/android_os_ParcelFileDescriptor.cpp b/core/jni/android_os_ParcelFileDescriptor.cpp index 465e233bb07205b925f8146bc11c16501714b781..971f87c2969cb0e64945261fe923d6ffcda4265e 100644 --- a/core/jni/android_os_ParcelFileDescriptor.cpp +++ b/core/jni/android_os_ParcelFileDescriptor.cpp @@ -15,6 +15,8 @@ ** limitations under the License. */ +//#define LOG_NDEBUG 0 + #include "JNIHelp.h" #include @@ -45,6 +47,11 @@ static struct socket_impl_offsets_t jfieldID mFileDescriptor; } gSocketImplOffsets; +static struct parcel_file_descriptor_offsets_t +{ + jclass mClass; + jfieldID mFileDescriptor; +} gParcelFileDescriptorOffsets; static jobject android_os_ParcelFileDescriptor_getFileDescriptorFromSocket(JNIEnv* env, jobject clazz, jobject object) @@ -60,9 +67,53 @@ static jobject android_os_ParcelFileDescriptor_getFileDescriptorFromSocket(JNIEn return fileDescriptorClone; } +static jint getFd(JNIEnv* env, jobject clazz) +{ + jobject descriptor = env->GetObjectField(clazz, gParcelFileDescriptorOffsets.mFileDescriptor); + if (descriptor == NULL) return -1; + return env->GetIntField(descriptor, gFileDescriptorOffsets.mDescriptor); +} + +static jlong android_os_ParcelFileDescriptor_getStatSize(JNIEnv* env, + jobject clazz) +{ + jint fd = getFd(env, clazz); + if (fd < 0) { + jniThrowException(env, "java/lang/IllegalArgumentException", "bad file descriptor"); + return -1; + } + + struct stat st; + if (fstat(fd, &st) != 0) { + return -1; + } + + if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) { + return st.st_size; + } + + return -1; +} + +static jlong android_os_ParcelFileDescriptor_seekTo(JNIEnv* env, + jobject clazz, jlong pos) +{ + jint fd = getFd(env, clazz); + if (fd < 0) { + jniThrowException(env, "java/lang/IllegalArgumentException", "bad file descriptor"); + return -1; + } + + return lseek(fd, pos, SEEK_SET); +} + static const JNINativeMethod gParcelFileDescriptorMethods[] = { {"getFileDescriptorFromSocket", "(Ljava/net/Socket;)Ljava/io/FileDescriptor;", - (void*)android_os_ParcelFileDescriptor_getFileDescriptorFromSocket} + (void*)android_os_ParcelFileDescriptor_getFileDescriptorFromSocket}, + {"getStatSize", "()J", + (void*)android_os_ParcelFileDescriptor_getStatSize}, + {"seekTo", "(J)J", + (void*)android_os_ParcelFileDescriptor_seekTo} }; const char* const kParcelFileDescriptorPathName = "android/os/ParcelFileDescriptor"; @@ -93,6 +144,10 @@ int register_android_os_ParcelFileDescriptor(JNIEnv* env) clazz = env->FindClass(kParcelFileDescriptorPathName); LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.ParcelFileDescriptor"); + gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz); + gParcelFileDescriptorOffsets.mFileDescriptor = env->GetFieldID(clazz, "mFileDescriptor", "Ljava/io/FileDescriptor;"); + LOG_FATAL_IF(gParcelFileDescriptorOffsets.mFileDescriptor == NULL, + "Unable to find mFileDescriptor field in android.os.ParcelFileDescriptor"); return AndroidRuntime::registerNativeMethods( env, kParcelFileDescriptorPathName, diff --git a/core/jni/android_server_BluetoothDeviceService.cpp b/core/jni/android_server_BluetoothDeviceService.cpp index 61a4a26aad0ec41b09db35a199c90ffda2d53063..796da1536b1c226e68ba0ddf284aeee0c5432dc7 100644 --- a/core/jni/android_server_BluetoothDeviceService.cpp +++ b/core/jni/android_server_BluetoothDeviceService.cpp @@ -428,36 +428,6 @@ static void disconnectRemoteDeviceNative(JNIEnv *env, jobject object, jstring ad #endif } -static jboolean isConnectableNative(JNIEnv *env, jobject object) { -#ifdef HAVE_BLUETOOTH - LOGV(__FUNCTION__); - native_data_t *nat = get_native_data(env, object); - if (nat) { - DBusMessage *reply = - dbus_func_args(env, nat->conn, nat->adapter, - DBUS_CLASS_NAME, "IsConnectable", - DBUS_TYPE_INVALID); - return reply ? dbus_returns_boolean(env, reply) : JNI_FALSE; - } -#endif - return JNI_FALSE; -} - -static jboolean isDiscoverableNative(JNIEnv *env, jobject object) { -#ifdef HAVE_BLUETOOTH - LOGV(__FUNCTION__); - native_data_t *nat = get_native_data(env, object); - if (nat) { - DBusMessage *reply = - dbus_func_args(env, nat->conn, nat->adapter, - DBUS_CLASS_NAME, "IsDiscoverable", - DBUS_TYPE_INVALID); - return reply ? dbus_returns_boolean(env, reply) : JNI_FALSE; - } -#endif - return JNI_FALSE; -} - static jstring getModeNative(JNIEnv *env, jobject object) { #ifdef HAVE_BLUETOOTH LOGV(__FUNCTION__); @@ -495,26 +465,6 @@ static jboolean setModeNative(JNIEnv *env, jobject object, jstring mode) { return JNI_FALSE; } -static void common_Bonding(JNIEnv *env, jobject object, int timeout_ms, - const char *func, jstring address) { -#ifdef HAVE_BLUETOOTH - native_data_t *nat = get_native_data(env, object); - if (nat) { - const char *c_address = env->GetStringUTFChars(address, NULL); - LOGV("... address = %s", c_address); - DBusMessage *reply = - dbus_func_args_timeout(env, nat->conn, timeout_ms, nat->adapter, - DBUS_CLASS_NAME, func, - DBUS_TYPE_STRING, &c_address, - DBUS_TYPE_INVALID); - env->ReleaseStringUTFChars(address, c_address); - if (reply) { - dbus_message_unref(reply); - } - } -#endif -} - static jboolean createBondingNative(JNIEnv *env, jobject object, jstring address, jint timeout_ms) { LOGV(__FUNCTION__); @@ -540,15 +490,64 @@ static jboolean createBondingNative(JNIEnv *env, jobject object, return JNI_FALSE; } -static void cancelBondingProcessNative(JNIEnv *env, jobject object, +static jboolean cancelBondingProcessNative(JNIEnv *env, jobject object, jstring address) { LOGV(__FUNCTION__); - common_Bonding(env, object, -1, "CancelBondingProcess", address); +#ifdef HAVE_BLUETOOTH + native_data_t *nat = get_native_data(env, object); + if (nat) { + const char *c_address = env->GetStringUTFChars(address, NULL); + LOGV("... address = %s", c_address); + DBusMessage *reply = + dbus_func_args_timeout(env, nat->conn, -1, nat->adapter, + DBUS_CLASS_NAME, "CancelBondingProcess", + DBUS_TYPE_STRING, &c_address, + DBUS_TYPE_INVALID); + env->ReleaseStringUTFChars(address, c_address); + if (reply) { + dbus_message_unref(reply); + } + return JNI_TRUE; + } +#endif + return JNI_FALSE; } -static void removeBondingNative(JNIEnv *env, jobject object, jstring address) { +static jboolean removeBondingNative(JNIEnv *env, jobject object, jstring address) { LOGV(__FUNCTION__); - common_Bonding(env, object, -1, "RemoveBonding", address); + jboolean result = JNI_FALSE; +#ifdef HAVE_BLUETOOTH + native_data_t *nat = get_native_data(env, object); + if (nat) { + const char *c_address = env->GetStringUTFChars(address, NULL); + LOGV("... address = %s", c_address); + DBusError err; + dbus_error_init(&err); + DBusMessage *reply = + dbus_func_args_error(env, nat->conn, &err, nat->adapter, + DBUS_CLASS_NAME, "RemoveBonding", + DBUS_TYPE_STRING, &c_address, + DBUS_TYPE_INVALID); + if (dbus_error_is_set(&err)) { + if (dbus_error_has_name(&err, + BLUEZ_DBUS_BASE_IFC ".Error.DoesNotExist")) { + LOGW("%s: Warning: %s (%s)", __FUNCTION__, err.message, + c_address); + result = JNI_TRUE; + } else { + LOGE("%s: D-Bus error %s (%s)", __FUNCTION__, err.name, + err.message); + } + } else { + result = JNI_TRUE; + } + + env->ReleaseStringUTFChars(address, c_address); + dbus_error_free(&err); + if (reply) dbus_message_unref(reply); + } +#endif + return result; } static jobjectArray listBondingsNative(JNIEnv *env, jobject object) { @@ -660,14 +659,6 @@ static jboolean setNameNative(JNIEnv *env, jobject obj, jstring name) { return JNI_FALSE; } -static jstring getMajorClassNative(JNIEnv *env, jobject obj) { - return common_Get(env, obj, "GetMajorClass"); -} - -static jstring getMinorClassNative(JNIEnv *env, jobject obj) { - return common_Get(env, obj, "GetMinorClass"); -} - static jstring common_getRemote(JNIEnv *env, jobject object, const char *func, jstring address) { LOGV("%s:%s", __FUNCTION__, func); @@ -704,66 +695,6 @@ static jstring common_getRemote(JNIEnv *env, jobject object, const char *func, return NULL; } -static jstring getRemoteAliasNative(JNIEnv *env, jobject obj, jstring address) { - return common_getRemote(env, obj, "GetRemoteAlias", address); -} - -static jboolean setRemoteAliasNative(JNIEnv *env, jobject obj, - jstring address, jstring alias) { -#ifdef HAVE_BLUETOOTH - LOGV(__FUNCTION__); - native_data_t *nat = get_native_data(env, obj); - if (nat) { - const char *c_address = env->GetStringUTFChars(address, NULL); - const char *c_alias = env->GetStringUTFChars(alias, NULL); - - LOGV("... address = %s alias = %s", c_address, c_alias); - - DBusMessage *reply = dbus_func_args(env, nat->conn, nat->adapter, - DBUS_CLASS_NAME, "SetRemoteAlias", - DBUS_TYPE_STRING, &c_address, - DBUS_TYPE_STRING, &c_alias, - DBUS_TYPE_INVALID); - - env->ReleaseStringUTFChars(address, c_address); - env->ReleaseStringUTFChars(alias, c_alias); - if (reply) - { - dbus_message_unref(reply); - return JNI_TRUE; - } - return JNI_FALSE; - } -#endif - return JNI_FALSE; -} - -static jboolean clearRemoteAliasNative(JNIEnv *env, jobject obj, jstring address) { -#ifdef HAVE_BLUETOOTH - LOGV(__FUNCTION__); - native_data_t *nat = get_native_data(env, obj); - if (nat) { - const char *c_address = env->GetStringUTFChars(address, NULL); - - LOGV("... address = %s", c_address); - - DBusMessage *reply = dbus_func_args(env, nat->conn, nat->adapter, - DBUS_CLASS_NAME, "ClearRemoteAlias", - DBUS_TYPE_STRING, &c_address, - DBUS_TYPE_INVALID); - - env->ReleaseStringUTFChars(address, c_address); - if (reply) - { - dbus_message_unref(reply); - return JNI_TRUE; - } - return JNI_FALSE; - } -#endif - return JNI_FALSE; -} - static jstring getRemoteVersionNative(JNIEnv *env, jobject obj, jstring address) { return common_getRemote(env, obj, "GetRemoteVersion", address); } @@ -780,14 +711,6 @@ static jstring getRemoteCompanyNative(JNIEnv *env, jobject obj, jstring address) return common_getRemote(env, obj, "GetRemoteCompany", address); } -static jstring getRemoteMajorClassNative(JNIEnv *env, jobject obj, jstring address) { - return common_getRemote(env, obj, "GetRemoteMajorClass", address); -} - -static jstring getRemoteMinorClassNative(JNIEnv *env, jobject obj, jstring address) { - return common_getRemote(env, obj, "GetRemoteMinorClass", address); -} - static jstring getRemoteNameNative(JNIEnv *env, jobject obj, jstring address) { return common_getRemote(env, obj, "GetRemoteName", address); } @@ -800,28 +723,6 @@ static jstring lastUsedNative(JNIEnv *env, jobject obj, jstring address) { return common_getRemote(env, obj, "LastUsed", address); } -static jobjectArray getRemoteServiceClassesNative(JNIEnv *env, jobject object, - jstring address) { -#ifdef HAVE_BLUETOOTH - LOGV(__FUNCTION__); - native_data_t *nat = get_native_data(env, object); - if (nat) { - const char *c_address = env->GetStringUTFChars(address, NULL); - - LOGV("... address = %s", c_address); - - DBusMessage *reply = - dbus_func_args(env, nat->conn, nat->adapter, - DBUS_CLASS_NAME, "GetRemoteServiceClasses", - DBUS_TYPE_STRING, &c_address, - DBUS_TYPE_INVALID); - env->ReleaseStringUTFChars(address, c_address); - return reply ? dbus_returns_array_of_strings(env, reply) : NULL; - } -#endif - return NULL; -} - static jint getRemoteClassNative(JNIEnv *env, jobject object, jstring address) { #ifdef HAVE_BLUETOOTH LOGV(__FUNCTION__); @@ -1070,8 +971,6 @@ static JNINativeMethod sMethods[] = { {"getAddressNative", "()Ljava/lang/String;", (void *)getAddressNative}, {"getNameNative", "()Ljava/lang/String;", (void*)getNameNative}, {"setNameNative", "(Ljava/lang/String;)Z", (void *)setNameNative}, - {"getMajorClassNative", "()Ljava/lang/String;", (void *)getMajorClassNative}, - {"getMinorClassNative", "()Ljava/lang/String;", (void *)getMinorClassNative}, {"getVersionNative", "()Ljava/lang/String;", (void *)getVersionNative}, {"getRevisionNative", "()Ljava/lang/String;", (void *)getRevisionNative}, {"getManufacturerNative", "()Ljava/lang/String;", (void *)getManufacturerNative}, @@ -1100,17 +999,11 @@ static JNINativeMethod sMethods[] = { {"removeBondingNative", "(Ljava/lang/String;)Z", (void *)removeBondingNative}, {"getRemoteNameNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteNameNative}, - {"getRemoteAliasNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteAliasNative}, - {"setRemoteAliasNative", "(Ljava/lang/String;Ljava/lang/String;)Z", (void *)setRemoteAliasNative}, - {"clearRemoteAliasNative", "(Ljava/lang/String;)Z", (void *)clearRemoteAliasNative}, {"getRemoteVersionNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteVersionNative}, {"getRemoteRevisionNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteRevisionNative}, {"getRemoteClassNative", "(Ljava/lang/String;)I", (void *)getRemoteClassNative}, {"getRemoteManufacturerNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteManufacturerNative}, {"getRemoteCompanyNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteCompanyNative}, - {"getRemoteMajorClassNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteMajorClassNative}, - {"getRemoteMinorClassNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)getRemoteMinorClassNative}, - {"getRemoteServiceClassesNative", "(Ljava/lang/String;)[Ljava/lang/String;", (void *)getRemoteServiceClassesNative}, {"getRemoteServiceChannelNative", "(Ljava/lang/String;S)Z", (void *)getRemoteServiceChannelNative}, {"getRemoteFeaturesNative", "(Ljava/lang/String;)[B", (void *)getRemoteFeaturesNative}, {"lastSeenNative", "(Ljava/lang/String;)Ljava/lang/String;", (void *)lastSeenNative}, diff --git a/core/jni/android_server_BluetoothEventLoop.cpp b/core/jni/android_server_BluetoothEventLoop.cpp index 3468265bd8bf6f8098df8be190efdea729fd9da1..c03bab6c2f192627b18d8ada7a1b822a0ffdc5be 100644 --- a/core/jni/android_server_BluetoothEventLoop.cpp +++ b/core/jni/android_server_BluetoothEventLoop.cpp @@ -47,8 +47,6 @@ static jmethodID method_onRemoteDeviceDisappeared; static jmethodID method_onRemoteClassUpdated; static jmethodID method_onRemoteNameUpdated; static jmethodID method_onRemoteNameFailed; -static jmethodID method_onRemoteAliasChanged; -static jmethodID method_onRemoteAliasCleared; static jmethodID method_onRemoteDeviceConnected; static jmethodID method_onRemoteDeviceDisconnectRequested; static jmethodID method_onRemoteDeviceDisconnected; @@ -60,6 +58,10 @@ static jmethodID method_onGetRemoteServiceChannelResult; static jmethodID method_onPasskeyAgentRequest; static jmethodID method_onPasskeyAgentCancel; +static jmethodID method_onAuthAgentAuthorize; +static jmethodID method_onAuthAgentCancel; + +static jmethodID method_onRestartRequired; typedef event_loop_native_data_t native_data_t; @@ -85,7 +87,6 @@ static void classInitNative(JNIEnv* env, jclass clazz) { method_onRemoteClassUpdated = env->GetMethodID(clazz, "onRemoteClassUpdated", "(Ljava/lang/String;I)V"); method_onRemoteNameUpdated = env->GetMethodID(clazz, "onRemoteNameUpdated", "(Ljava/lang/String;Ljava/lang/String;)V"); method_onRemoteNameFailed = env->GetMethodID(clazz, "onRemoteNameFailed", "(Ljava/lang/String;)V"); - method_onRemoteAliasChanged = env->GetMethodID(clazz, "onRemoteAliasChanged", "(Ljava/lang/String;Ljava/lang/String;)V"); method_onRemoteDeviceConnected = env->GetMethodID(clazz, "onRemoteDeviceConnected", "(Ljava/lang/String;)V"); method_onRemoteDeviceDisconnectRequested = env->GetMethodID(clazz, "onRemoteDeviceDisconnectRequested", "(Ljava/lang/String;)V"); method_onRemoteDeviceDisconnected = env->GetMethodID(clazz, "onRemoteDeviceDisconnected", "(Ljava/lang/String;)V"); @@ -96,8 +97,12 @@ static void classInitNative(JNIEnv* env, jclass clazz) { method_onPasskeyAgentRequest = env->GetMethodID(clazz, "onPasskeyAgentRequest", "(Ljava/lang/String;I)V"); method_onPasskeyAgentCancel = env->GetMethodID(clazz, "onPasskeyAgentCancel", "(Ljava/lang/String;)V"); + method_onAuthAgentAuthorize = env->GetMethodID(clazz, "onAuthAgentAuthorize", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z"); + method_onAuthAgentCancel = env->GetMethodID(clazz, "onAuthAgentCancel", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); method_onGetRemoteServiceChannelResult = env->GetMethodID(clazz, "onGetRemoteServiceChannelResult", "(Ljava/lang/String;I)V"); + method_onRestartRequired = env->GetMethodID(clazz, "onRestartRequired", "()V"); + field_mNativeData = env->GetFieldID(clazz, "mNativeData", "I"); #endif } @@ -139,12 +144,12 @@ static void cleanupNativeDataNative(JNIEnv* env, jobject object) { #ifdef HAVE_BLUETOOTH static DBusHandlerResult event_filter(DBusConnection *conn, DBusMessage *msg, void *data); -static DBusHandlerResult passkey_agent_event_filter(DBusConnection *conn, - DBusMessage *msg, - void *data); +static DBusHandlerResult agent_event_filter(DBusConnection *conn, + DBusMessage *msg, + void *data); -static const DBusObjectPathVTable passkey_agent_vtable = { - NULL, passkey_agent_event_filter, NULL, NULL, NULL, NULL +static const DBusObjectPathVTable agent_vtable = { + NULL, agent_event_filter, NULL, NULL, NULL, NULL }; #endif @@ -163,6 +168,13 @@ static jboolean setUpEventLoopNative(JNIEnv *env, jobject object) { } // Set which messages will be processed by this dbus connection + dbus_bus_add_match(nat->conn, + "type='signal',interface='org.freedesktop.DBus'", + &err); + if (dbus_error_is_set(&err)) { + LOG_AND_FREE_DBUS_ERROR(&err); + return JNI_FALSE; + } dbus_bus_add_match(nat->conn, "type='signal',interface='"BLUEZ_DBUS_BASE_IFC".Adapter'", &err); @@ -193,9 +205,9 @@ static jboolean setUpEventLoopNative(JNIEnv *env, jobject object) { } // Add an object handler for passkey agent method calls - const char *path = "/android/bluetooth/PasskeyAgent"; + const char *path = "/android/bluetooth/Agent"; if (!dbus_connection_register_object_path(nat->conn, path, - &passkey_agent_vtable, NULL)) { + &agent_vtable, NULL)) { LOGE("%s: Can't register object path %s for agent!", __FUNCTION__, path); return JNI_FALSE; @@ -204,7 +216,7 @@ static jboolean setUpEventLoopNative(JNIEnv *env, jobject object) { // RegisterDefaultPasskeyAgent() will fail until hcid is up, so keep // trying for 10 seconds. int attempt; - for (attempt = 1000; attempt > 0; attempt--) { + for (attempt = 0; attempt < 1000; attempt++) { DBusMessage *reply = dbus_func_args_error(env, nat->conn, &err, BLUEZ_DBUS_BASE_PATH, "org.bluez.Security", "RegisterDefaultPasskeyAgent", @@ -213,7 +225,8 @@ static jboolean setUpEventLoopNative(JNIEnv *env, jobject object) { if (reply) { // Success dbus_message_unref(reply); - return JNI_TRUE; + LOGV("Registered agent on attempt %d of 1000\n", attempt); + break; } else if (dbus_error_has_name(&err, "org.freedesktop.DBus.Error.ServiceUnknown")) { // hcid is still down, retry @@ -225,9 +238,25 @@ static jboolean setUpEventLoopNative(JNIEnv *env, jobject object) { return JNI_FALSE; } } - LOGE("Time-out trying to call RegisterDefaultPasskeyAgent(), " - "is hcid running?"); - return JNI_FALSE; + if (attempt == 1000) { + LOGE("Time-out trying to call RegisterDefaultPasskeyAgent(), " + "is hcid running?"); + return JNI_FALSE; + } + + // Now register the Auth agent + DBusMessage *reply = dbus_func_args_error(env, nat->conn, &err, + BLUEZ_DBUS_BASE_PATH, + "org.bluez.Security", "RegisterDefaultAuthorizationAgent", + DBUS_TYPE_STRING, &path, + DBUS_TYPE_INVALID); + if (!reply) { + LOG_AND_FREE_DBUS_ERROR(&err); + return JNI_FALSE; + } + + dbus_message_unref(reply); + return JNI_TRUE; } #endif @@ -243,12 +272,19 @@ static void tearDownEventLoopNative(JNIEnv *env, jobject object) { DBusError err; dbus_error_init(&err); - const char *path = "/android/bluetooth/PasskeyAgent"; + const char *path = "/android/bluetooth/Agent"; DBusMessage *reply = dbus_func_args(env, nat->conn, BLUEZ_DBUS_BASE_PATH, - "org.bluez.Security", "UnregisterDefaultPasskeyAgent", - DBUS_TYPE_STRING, &path, - DBUS_TYPE_INVALID); + "org.bluez.Security", "UnregisterDefaultPasskeyAgent", + DBUS_TYPE_STRING, &path, + DBUS_TYPE_INVALID); + if (reply) dbus_message_unref(reply); + + reply = + dbus_func_args(env, nat->conn, BLUEZ_DBUS_BASE_PATH, + "org.bluez.Security", "UnregisterDefaultAuthorizationAgent", + DBUS_TYPE_STRING, &path, + DBUS_TYPE_INVALID); if (reply) dbus_message_unref(reply); dbus_connection_unregister_object_path(nat->conn, path); @@ -277,6 +313,12 @@ static void tearDownEventLoopNative(JNIEnv *env, jobject object) { if (dbus_error_is_set(&err)) { LOG_AND_FREE_DBUS_ERROR(&err); } + dbus_bus_remove_match(nat->conn, + "type='signal',interface='org.freedesktop.DBus'", + &err); + if (dbus_error_is_set(&err)) { + LOG_AND_FREE_DBUS_ERROR(&err); + } dbus_connection_remove_filter(nat->conn, event_filter, nat); } @@ -393,34 +435,6 @@ static DBusHandlerResult event_filter(DBusConnection *conn, DBusMessage *msg, env->NewStringUTF(c_address)); } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg); return DBUS_HANDLER_RESULT_HANDLED; - } else if (dbus_message_is_signal(msg, - "org.bluez.Adapter", - "RemoteAliasChanged")) { - char *c_address, *c_alias; - if (dbus_message_get_args(msg, &err, - DBUS_TYPE_STRING, &c_address, - DBUS_TYPE_STRING, &c_alias, - DBUS_TYPE_INVALID)) { - LOGV("... address = %s, alias = %s", c_address, c_alias); - env->CallVoidMethod(nat->me, - method_onRemoteAliasChanged, - env->NewStringUTF(c_address), - env->NewStringUTF(c_alias)); - } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg); - return DBUS_HANDLER_RESULT_HANDLED; - } else if (dbus_message_is_signal(msg, - "org.bluez.Adapter", - "RemoteAliasCleared")) { - char *c_address; - if (dbus_message_get_args(msg, &err, - DBUS_TYPE_STRING, &c_address, - DBUS_TYPE_INVALID)) { - LOGV("... address = %s", c_address); - env->CallVoidMethod(nat->me, - method_onRemoteAliasCleared, - env->NewStringUTF(c_address)); - } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg); - return DBUS_HANDLER_RESULT_HANDLED; } else if (dbus_message_is_signal(msg, "org.bluez.Adapter", "RemoteDeviceConnected")) { @@ -512,15 +526,36 @@ static DBusHandlerResult event_filter(DBusConnection *conn, DBusMessage *msg, env->NewStringUTF(c_name)); } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg); return DBUS_HANDLER_RESULT_HANDLED; + } else if (dbus_message_is_signal(msg, + "org.freedesktop.DBus", + "NameOwnerChanged")) { + char *c_name; + char *c_old_owner; + char *c_new_owner; + if (dbus_message_get_args(msg, &err, + DBUS_TYPE_STRING, &c_name, + DBUS_TYPE_STRING, &c_old_owner, + DBUS_TYPE_STRING, &c_new_owner, + DBUS_TYPE_INVALID)) { + LOGV("... name = %s", c_name); + LOGV("... old_owner = %s", c_old_owner); + LOGV("... new_owner = %s", c_new_owner); + if (!strcmp(c_name, "org.bluez") && c_new_owner[0] != '\0') { + // New owner of org.bluez. This can only happen when hcid + // restarts. Need to restart framework BT services to recover. + LOGE("Looks like hcid restarted"); + env->CallVoidMethod(nat->me, method_onRestartRequired); + } + } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg); + return DBUS_HANDLER_RESULT_HANDLED; } return a2dp_event_filter(msg, env); } // Called by dbus during WaitForAndDispatchEventNative() -static DBusHandlerResult passkey_agent_event_filter(DBusConnection *conn, - DBusMessage *msg, - void *data) { +static DBusHandlerResult agent_event_filter(DBusConnection *conn, + DBusMessage *msg, void *data) { native_data_t *nat = event_loop_nat; JNIEnv *env; @@ -573,11 +608,120 @@ static DBusHandlerResult passkey_agent_event_filter(DBusConnection *conn, env->CallVoidMethod(nat->me, method_onPasskeyAgentCancel, env->NewStringUTF(address)); + // reply + DBusMessage *reply = dbus_message_new_method_return(msg); + if (!reply) { + LOGE("%s: Cannot create message reply\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + dbus_connection_send(nat->conn, reply, NULL); + dbus_message_unref(reply); return DBUS_HANDLER_RESULT_HANDLED; } else if (dbus_message_is_method_call(msg, "org.bluez.PasskeyAgent", "Release")) { - LOGE("We are no longer the passkey agent!"); + LOGW("We are no longer the passkey agent!"); + + // reply + DBusMessage *reply = dbus_message_new_method_return(msg); + if (!reply) { + LOGE("%s: Cannot create message reply\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + dbus_connection_send(nat->conn, reply, NULL); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_HANDLED; + } else if (dbus_message_is_method_call(msg, + "org.bluez.AuthorizationAgent", "Authorize")) { + const char *adapter; + const char *address; + const char *service; + const char *uuid; + if (!dbus_message_get_args(msg, NULL, + DBUS_TYPE_STRING, &adapter, + DBUS_TYPE_STRING, &address, + DBUS_TYPE_STRING, &service, + DBUS_TYPE_STRING, &uuid, + DBUS_TYPE_INVALID)) { + LOGE("%s: Invalid arguments for Authorize() method", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + + LOGV("... address = %s", address); + LOGV("... service = %s", service); + LOGV("... uuid = %s", uuid); + + bool auth_granted = env->CallBooleanMethod(nat->me, + method_onAuthAgentAuthorize, env->NewStringUTF(address), + env->NewStringUTF(service), env->NewStringUTF(uuid)); + + // reply + if (auth_granted) { + DBusMessage *reply = dbus_message_new_method_return(msg); + if (!reply) { + LOGE("%s: Cannot create message reply\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + dbus_connection_send(nat->conn, reply, NULL); + dbus_message_unref(reply); + } else { + DBusMessage *reply = dbus_message_new_error(msg, + "org.bluez.Error.Rejected", "Authorization rejected"); + if (!reply) { + LOGE("%s: Cannot create message reply\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + dbus_connection_send(nat->conn, reply, NULL); + dbus_message_unref(reply); + } + return DBUS_HANDLER_RESULT_HANDLED; + } else if (dbus_message_is_method_call(msg, + "org.bluez.AuthorizationAgent", "Cancel")) { + const char *adapter; + const char *address; + const char *service; + const char *uuid; + if (!dbus_message_get_args(msg, NULL, + DBUS_TYPE_STRING, &adapter, + DBUS_TYPE_STRING, &address, + DBUS_TYPE_STRING, &service, + DBUS_TYPE_STRING, &uuid, + DBUS_TYPE_INVALID)) { + LOGE("%s: Invalid arguments for Cancel() method", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + + LOGV("... address = %s", address); + LOGV("... service = %s", service); + LOGV("... uuid = %s", uuid); + + env->CallVoidMethod(nat->me, + method_onAuthAgentCancel, env->NewStringUTF(address), + env->NewStringUTF(service), env->NewStringUTF(uuid)); + + // reply + DBusMessage *reply = dbus_message_new_method_return(msg); + if (!reply) { + LOGE("%s: Cannot create message reply\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + dbus_connection_send(nat->conn, reply, NULL); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_HANDLED; + + } else if (dbus_message_is_method_call(msg, + "org.bluez.AuthorizationAgent", "Release")) { + LOGW("We are no longer the auth agent!"); + + // reply + DBusMessage *reply = dbus_message_new_method_return(msg); + if (!reply) { + LOGE("%s: Cannot create message reply\n", __FUNCTION__); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + dbus_connection_send(nat->conn, reply, NULL); + dbus_message_unref(reply); + return DBUS_HANDLER_RESULT_HANDLED; } else { LOGV("... ignored"); } @@ -614,7 +758,9 @@ static jboolean waitForAndDispatchEventNative(JNIEnv *env, jobject object, #define BOND_RESULT_SUCCESS 0 #define BOND_RESULT_AUTH_FAILED 1 #define BOND_RESULT_AUTH_REJECTED 2 -#define BOND_RESULT_REMOTE_DEVICE_DOWN 3 +#define BOND_RESULT_AUTH_CANCELED 3 +#define BOND_RESULT_REMOTE_DEVICE_DOWN 4 +#define BOND_RESULT_DISCOVERY_IN_PROGRESS 5 void onCreateBondingResult(DBusMessage *msg, void *user) { LOGV(__FUNCTION__); @@ -637,21 +783,38 @@ void onCreateBondingResult(DBusMessage *msg, void *user) { // happens if either side presses 'cancel' at the pairing dialog. LOGV("... error = %s (%s)\n", err.name, err.message); result = BOND_RESULT_AUTH_REJECTED; - } else if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".ConnectionAttemptFailed")) { + } else if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.AuthenticationCanceled")) { + // Not sure if this happens + LOGV("... error = %s (%s)\n", err.name, err.message); + result = BOND_RESULT_AUTH_CANCELED; + } else if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.ConnectionAttemptFailed")) { // Other device is not responding at all LOGV("... error = %s (%s)\n", err.name, err.message); result = BOND_RESULT_REMOTE_DEVICE_DOWN; + } else if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.AlreadyExists")) { + // already bonded + LOGV("... error = %s (%s)\n", err.name, err.message); + result = BOND_RESULT_SUCCESS; + } else if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.InProgress") && + !strcmp(err.message, "Bonding in progress")) { + LOGV("... error = %s (%s)\n", err.name, err.message); + goto done; + } else if (!strcmp(err.name, BLUEZ_DBUS_BASE_IFC ".Error.InProgress") && + !strcmp(err.message, "Discover in progress")) { + LOGV("... error = %s (%s)\n", err.name, err.message); + result = BOND_RESULT_DISCOVERY_IN_PROGRESS; } else { LOGE("%s: D-Bus error: %s (%s)\n", __FUNCTION__, err.name, err.message); result = BOND_RESULT_ERROR; } - dbus_error_free(&err); } env->CallVoidMethod(event_loop_nat->me, method_onCreateBondingResult, env->NewStringUTF(address), result); +done: + dbus_error_free(&err); free(user); } diff --git a/core/jni/android_text_format_Time.cpp b/core/jni/android_text_format_Time.cpp index 8e41ec76a80144b8b8ba88f654cea0e47b4290ff..923e1aa05cc83df44d3278abb65302a1bc79206f 100644 --- a/core/jni/android_text_format_Time.cpp +++ b/core/jni/android_text_format_Time.cpp @@ -52,6 +52,9 @@ static jfieldID g_dateTimeFormatField = 0; static jfieldID g_amField = 0; static jfieldID g_pmField = 0; static jfieldID g_dateCommandField = 0; +static jfieldID g_localeField = 0; + +static jclass g_timeClass = NULL; static inline bool java2time(JNIEnv* env, Time* t, jobject o) { @@ -183,56 +186,101 @@ static jstring android_text_format_Time_format2445(JNIEnv* env, jobject This) static jstring android_text_format_Time_format(JNIEnv* env, jobject This, jstring formatObject) { - Time t; - struct strftime_locale locale; - jclass timeClass = env->FindClass("android/text/format/Time"); - jstring js_mon[12], js_month[12], js_wday[7], js_weekday[7]; - jstring js_X_fmt, js_x_fmt, js_c_fmt, js_am, js_pm, js_date_fmt; - jobjectArray ja; + // We only teardown and setup our 'locale' struct and other state + // when the Java-side locale changed. This is safe to do here + // without locking because we're always called from Java code + // synchronized on the class instance. + static jobject js_locale_previous = NULL; + static struct strftime_locale locale; + static jstring js_mon[12], js_month[12], js_wday[7], js_weekday[7]; + static jstring js_X_fmt, js_x_fmt, js_c_fmt, js_am, js_pm, js_date_fmt; + Time t; if (!java2time(env, &t, This)) return env->NewStringUTF(""); - ja = (jobjectArray) env->GetStaticObjectField(timeClass, g_shortMonthsField); - for (int i = 0; i < 12; i++) { - js_mon[i] = (jstring) env->GetObjectArrayElement(ja, i); - locale.mon[i] = env->GetStringUTFChars(js_mon[i], NULL); - } + jclass timeClass = g_timeClass; + jobject js_locale = (jobject) env->GetStaticObjectField(timeClass, g_localeField); + if (js_locale_previous != js_locale) { + if (js_locale_previous != NULL) { + // Free the old one. + for (int i = 0; i < 12; i++) { + env->ReleaseStringUTFChars(js_mon[i], locale.mon[i]); + env->ReleaseStringUTFChars(js_month[i], locale.month[i]); + env->DeleteGlobalRef(js_mon[i]); + env->DeleteGlobalRef(js_month[i]); + } + + for (int i = 0; i < 7; i++) { + env->ReleaseStringUTFChars(js_wday[i], locale.wday[i]); + env->ReleaseStringUTFChars(js_weekday[i], locale.weekday[i]); + env->DeleteGlobalRef(js_wday[i]); + env->DeleteGlobalRef(js_weekday[i]); + } + + env->ReleaseStringUTFChars(js_X_fmt, locale.X_fmt); + env->ReleaseStringUTFChars(js_x_fmt, locale.x_fmt); + env->ReleaseStringUTFChars(js_c_fmt, locale.c_fmt); + env->ReleaseStringUTFChars(js_am, locale.am); + env->ReleaseStringUTFChars(js_pm, locale.pm); + env->ReleaseStringUTFChars(js_date_fmt, locale.date_fmt); + env->DeleteGlobalRef(js_X_fmt); + env->DeleteGlobalRef(js_x_fmt); + env->DeleteGlobalRef(js_c_fmt); + env->DeleteGlobalRef(js_am); + env->DeleteGlobalRef(js_pm); + env->DeleteGlobalRef(js_date_fmt); + } + js_locale_previous = js_locale; - ja = (jobjectArray) env->GetStaticObjectField(timeClass, g_longMonthsField); - for (int i = 0; i < 12; i++) { - js_month[i] = (jstring) env->GetObjectArrayElement(ja, i); - locale.month[i] = env->GetStringUTFChars(js_month[i], NULL); - } + jobjectArray ja; + ja = (jobjectArray) env->GetStaticObjectField(timeClass, g_shortMonthsField); + for (int i = 0; i < 12; i++) { + js_mon[i] = (jstring) env->NewGlobalRef(env->GetObjectArrayElement(ja, i)); + locale.mon[i] = env->GetStringUTFChars(js_mon[i], NULL); + } - ja = (jobjectArray) env->GetStaticObjectField(timeClass, g_shortWeekdaysField); - for (int i = 0; i < 7; i++) { - js_wday[i] = (jstring) env->GetObjectArrayElement(ja, i); - locale.wday[i] = env->GetStringUTFChars(js_wday[i], NULL); - } + ja = (jobjectArray) env->GetStaticObjectField(timeClass, g_longMonthsField); + for (int i = 0; i < 12; i++) { + js_month[i] = (jstring) env->NewGlobalRef(env->GetObjectArrayElement(ja, i)); + locale.month[i] = env->GetStringUTFChars(js_month[i], NULL); + } - ja = (jobjectArray) env->GetStaticObjectField(timeClass, g_longWeekdaysField); - for (int i = 0; i < 7; i++) { - js_weekday[i] = (jstring) env->GetObjectArrayElement(ja, i); - locale.weekday[i] = env->GetStringUTFChars(js_weekday[i], NULL); - } + ja = (jobjectArray) env->GetStaticObjectField(timeClass, g_shortWeekdaysField); + for (int i = 0; i < 7; i++) { + js_wday[i] = (jstring) env->NewGlobalRef(env->GetObjectArrayElement(ja, i)); + locale.wday[i] = env->GetStringUTFChars(js_wday[i], NULL); + } - js_X_fmt = (jstring) env->GetStaticObjectField(timeClass, g_timeOnlyFormatField); - locale.X_fmt = env->GetStringUTFChars(js_X_fmt, NULL); + ja = (jobjectArray) env->GetStaticObjectField(timeClass, g_longWeekdaysField); + for (int i = 0; i < 7; i++) { + js_weekday[i] = (jstring) env->NewGlobalRef(env->GetObjectArrayElement(ja, i)); + locale.weekday[i] = env->GetStringUTFChars(js_weekday[i], NULL); + } + + js_X_fmt = (jstring) env->NewGlobalRef(env->GetStaticObjectField( + timeClass, g_timeOnlyFormatField)); + locale.X_fmt = env->GetStringUTFChars(js_X_fmt, NULL); - js_x_fmt = (jstring) env->GetStaticObjectField(timeClass, g_dateOnlyFormatField); - locale.x_fmt = env->GetStringUTFChars(js_x_fmt, NULL); + js_x_fmt = (jstring) env->NewGlobalRef(env->GetStaticObjectField( + timeClass, g_dateOnlyFormatField)); + locale.x_fmt = env->GetStringUTFChars(js_x_fmt, NULL); - js_c_fmt = (jstring) env->GetStaticObjectField(timeClass, g_dateTimeFormatField); - locale.c_fmt = env->GetStringUTFChars(js_c_fmt, NULL); + js_c_fmt = (jstring) env->NewGlobalRef(env->GetStaticObjectField( + timeClass, g_dateTimeFormatField)); + locale.c_fmt = env->GetStringUTFChars(js_c_fmt, NULL); - js_am = (jstring) env->GetStaticObjectField(timeClass, g_amField); - locale.am = env->GetStringUTFChars(js_am, NULL); + js_am = (jstring) env->NewGlobalRef(env->GetStaticObjectField( + timeClass, g_amField)); + locale.am = env->GetStringUTFChars(js_am, NULL); - js_pm = (jstring) env->GetStaticObjectField(timeClass, g_pmField); - locale.pm = env->GetStringUTFChars(js_pm, NULL); + js_pm = (jstring) env->NewGlobalRef(env->GetStaticObjectField( + timeClass, g_pmField)); + locale.pm = env->GetStringUTFChars(js_pm, NULL); - js_date_fmt = (jstring) env->GetStaticObjectField(timeClass, g_dateCommandField); - locale.date_fmt = env->GetStringUTFChars(js_date_fmt, NULL); + js_date_fmt = (jstring) env->NewGlobalRef(env->GetStaticObjectField( + timeClass, g_dateCommandField)); + locale.date_fmt = env->GetStringUTFChars(js_date_fmt, NULL); + } ACQUIRE_TIMEZONE(This, t) @@ -243,23 +291,6 @@ static jstring android_text_format_Time_format(JNIEnv* env, jobject This, env->ReleaseStringUTFChars(formatObject, format); RELEASE_TIMEZONE(This, t) - for (int i = 0; i < 12; i++) { - env->ReleaseStringUTFChars(js_mon[i], locale.mon[i]); - env->ReleaseStringUTFChars(js_month[i], locale.month[i]); - } - - for (int i = 0; i < 7; i++) { - env->ReleaseStringUTFChars(js_wday[i], locale.wday[i]); - env->ReleaseStringUTFChars(js_weekday[i], locale.weekday[i]); - } - - env->ReleaseStringUTFChars(js_X_fmt, locale.X_fmt); - env->ReleaseStringUTFChars(js_x_fmt, locale.x_fmt); - env->ReleaseStringUTFChars(js_c_fmt, locale.c_fmt); - env->ReleaseStringUTFChars(js_am, locale.am); - env->ReleaseStringUTFChars(js_pm, locale.pm); - env->ReleaseStringUTFChars(js_date_fmt, locale.date_fmt); - return env->NewStringUTF(r.string()); } @@ -307,7 +338,6 @@ static void android_text_format_Time_set(JNIEnv* env, jobject This, jlong millis { env->SetBooleanField(This, g_allDayField, JNI_FALSE); Time t; - if (!java2time(env, &t, This)) return; ACQUIRE_TIMEZONE(This, t) t.set(millis); @@ -592,6 +622,8 @@ int register_android_text_format_Time(JNIEnv* env) { jclass timeClass = env->FindClass("android/text/format/Time"); + g_timeClass = (jclass) env->NewGlobalRef(timeClass); + g_allDayField = env->GetFieldID(timeClass, "allDay", "Z"); g_secField = env->GetFieldID(timeClass, "second", "I"); g_minField = env->GetFieldID(timeClass, "minute", "I"); @@ -615,9 +647,9 @@ int register_android_text_format_Time(JNIEnv* env) g_amField = env->GetStaticFieldID(timeClass, "sAm", "Ljava/lang/String;"); g_pmField = env->GetStaticFieldID(timeClass, "sPm", "Ljava/lang/String;"); g_dateCommandField = env->GetStaticFieldID(timeClass, "sDateCommand", "Ljava/lang/String;"); + g_localeField = env->GetStaticFieldID(timeClass, "sLocale", "Ljava/util/Locale;"); return AndroidRuntime::registerNativeMethods(env, "android/text/format/Time", gMethods, NELEM(gMethods)); } }; // namespace android - diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp index add108053f87b24eb309318e21b01fec9f442a0d..d147bcc883c281240d3f7a2bdec21c64a4e860c9 100644 --- a/core/jni/android_util_AssetManager.cpp +++ b/core/jni/android_util_AssetManager.cpp @@ -44,6 +44,7 @@ static struct typedvalue_offsets_t jfieldID mAssetCookie; jfieldID mResourceId; jfieldID mChangingConfigurations; + jfieldID mDensity; } gTypedValueOffsets; static struct assetfiledescriptor_offsets_t @@ -83,7 +84,11 @@ enum { static jint copyValue(JNIEnv* env, jobject outValue, const ResTable* table, const Res_value& value, uint32_t ref, ssize_t block, - uint32_t typeSpecFlags) + uint32_t typeSpecFlags, ResTable_config* config = NULL); + +jint copyValue(JNIEnv* env, jobject outValue, const ResTable* table, + const Res_value& value, uint32_t ref, ssize_t block, + uint32_t typeSpecFlags, ResTable_config* config) { env->SetIntField(outValue, gTypedValueOffsets.mType, value.dataType); env->SetIntField(outValue, gTypedValueOffsets.mAssetCookie, @@ -93,6 +98,9 @@ static jint copyValue(JNIEnv* env, jobject outValue, const ResTable* table, env->SetIntField(outValue, gTypedValueOffsets.mResourceId, ref); env->SetIntField(outValue, gTypedValueOffsets.mChangingConfigurations, typeSpecFlags); + if (config != NULL) { + env->SetIntField(outValue, gTypedValueOffsets.mDensity, config->density); + } return block; } @@ -703,13 +711,14 @@ static jint android_content_AssetManager_loadResourceValue(JNIEnv* env, jobject const ResTable& res(am->getResources()); Res_value value; + ResTable_config config; uint32_t typeSpecFlags; - ssize_t block = res.getResource(ident, &value, false, &typeSpecFlags); + ssize_t block = res.getResource(ident, &value, false, &typeSpecFlags, &config); uint32_t ref = ident; if (resolve) { block = res.resolveReference(&value, block, &ref); } - return block >= 0 ? copyValue(env, outValue, &res, value, ref, block, typeSpecFlags) : block; + return block >= 0 ? copyValue(env, outValue, &res, value, ref, block, typeSpecFlags, &config) : block; } static jint android_content_AssetManager_loadResourceBagValue(JNIEnv* env, jobject clazz, @@ -1648,6 +1657,8 @@ int register_android_content_AssetManager(JNIEnv* env) gTypedValueOffsets.mChangingConfigurations = env->GetFieldID(typedValue, "changingConfigurations", "I"); LOG_FATAL_IF(gTypedValueOffsets.mChangingConfigurations == NULL, "Unable to find TypedValue.changingConfigurations"); + gTypedValueOffsets.mDensity = env->GetFieldID(typedValue, "density", "I"); + LOG_FATAL_IF(gTypedValueOffsets.mDensity == NULL, "Unable to find TypedValue.density"); jclass assetFd = env->FindClass("android/content/res/AssetFileDescriptor"); LOG_FATAL_IF(assetFd == NULL, "Unable to find class android/content/res/AssetFileDescriptor"); diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp index 24404a87e821a15f07b82d1fc996bd8504ec91a4..73254320bdf4b83cef2b07107252cfa34d4dc883 100644 --- a/core/jni/android_util_Binder.cpp +++ b/core/jni/android_util_Binder.cpp @@ -1223,6 +1223,7 @@ static jobject android_os_Parcel_openFileDescriptor(JNIEnv* env, jobject clazz, if (mode&0x08000000) flags |= O_CREAT; if (mode&0x04000000) flags |= O_TRUNC; + if (mode&0x02000000) flags |= O_APPEND; int realMode = S_IRWXU|S_IRWXG; if (mode&0x00000001) realMode |= S_IROTH; diff --git a/core/jni/android_util_EventLog.cpp b/core/jni/android_util_EventLog.cpp index d0cac183ab67805b4db1552a16351e563e89ab5d..5e5103a2fabea521fa82cdd8867486b50d2b6df2 100644 --- a/core/jni/android_util_EventLog.cpp +++ b/core/jni/android_util_EventLog.cpp @@ -19,7 +19,7 @@ #include "JNIHelp.h" #include "android_runtime/AndroidRuntime.h" #include "jni.h" -#include "utils/logger.h" +#include "cutils/logger.h" #define END_DELIMITER '\n' #define INT_BUFFER_SIZE (sizeof(jbyte)+sizeof(jint)+sizeof(END_DELIMITER)) diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp index f09bd4c7be98284b4b3411b00b6d41c1883de986..8baaa84e6820cecd22a066c40e4f879c9978d963 100644 --- a/core/jni/android_view_Surface.cpp +++ b/core/jni/android_view_Surface.cpp @@ -212,7 +212,9 @@ static jobject Surface_lockCanvas(JNIEnv* env, jobject clazz, jobject dirtyRect) dirty.top = env->GetIntField(dirtyRect, ro.t); dirty.right = env->GetIntField(dirtyRect, ro.r); dirty.bottom= env->GetIntField(dirtyRect, ro.b); - dirtyRegion.set(dirty); + if (dirty.left < dirty.right && dirty.top < dirty.bottom) { + dirtyRegion.set(dirty); + } } else { dirtyRegion.set(Rect(0x3FFF,0x3FFF)); } @@ -246,6 +248,14 @@ static jobject Surface_lockCanvas(JNIEnv* env, jobject clazz, jobject dirtyRect) int saveCount = nativeCanvas->save(); env->SetIntField(clazz, so.saveCount, saveCount); + if (dirtyRect) { + Rect bounds(dirtyRegion.bounds()); + env->SetIntField(dirtyRect, ro.l, bounds.left); + env->SetIntField(dirtyRect, ro.t, bounds.top); + env->SetIntField(dirtyRect, ro.r, bounds.right); + env->SetIntField(dirtyRect, ro.b, bounds.bottom); + } + return canvas; } diff --git a/core/jni/com_google_android_gles_jni_EGLImpl.cpp b/core/jni/com_google_android_gles_jni_EGLImpl.cpp index 8bacc74dc645bfab545f45a74fe36c7a4954d0b7..fbbd85216608acf84ad1c0131511c9a05c839e36 100644 --- a/core/jni/com_google_android_gles_jni_EGLImpl.cpp +++ b/core/jni/com_google_android_gles_jni_EGLImpl.cpp @@ -18,7 +18,7 @@ #include #include -#include +#include #include #include diff --git a/core/res/Android.mk b/core/res/Android.mk index 5fca5d011fc1b949a8a4a18c6dd14ca73432135e..cb5524a6dc30b6dbfcd250b7970a3ce9f485c34f 100644 --- a/core/res/Android.mk +++ b/core/res/Android.mk @@ -24,7 +24,7 @@ LOCAL_CERTIFICATE := platform # since these resources will be used by many apps. LOCAL_AAPT_FLAGS := -x -LOCAL_MODULE_TAGS := user development +LOCAL_MODULE_TAGS := user # Install this alongside the libraries. LOCAL_MODULE_PATH := $(TARGET_OUT_JAVA_LIBRARIES) diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml index ded909f0c3ca69aef3e1960573ce7347995ed7d3..1b145af033f3b5ee9a568bf4465054d9b0786b3b 100644 --- a/core/res/AndroidManifest.xml +++ b/core/res/AndroidManifest.xml @@ -18,7 +18,8 @@ */ --> + package="android" android:sharedUserId="android.uid.system" + android:sharedUserLabel="@string/android_system_label"> @@ -549,6 +550,13 @@ android:label="@string/permlab_mount_unmount_filesystems" android:description="@string/permdesc_mount_unmount_filesystems" /> + + + + android:protectionLevel="signatureOrSystem" /> @@ -725,8 +733,9 @@ android:description="@string/permdesc_fotaUpdate" android:protectionLevel="signature" /> - - + @@ -902,10 +911,43 @@ android:description="@string/permdesc_checkinProperties" android:protectionLevel="signature" /> + + + + + + + + + + + + - + + + + + - - - - - - - - - - - - - - - - + diff --git a/core/res/assets/webkit/nullplugin.png b/core/res/assets/webkit/nullPlugin.png similarity index 100% rename from core/res/assets/webkit/nullplugin.png rename to core/res/assets/webkit/nullPlugin.png diff --git a/core/res/res/anim/app_starting_exit.xml b/core/res/res/anim/app_starting_exit.xml index c6f94b06bb0489d34e6925a9144af89bf8efd62a..06755754c092019ea1c70e9324814c820a451ea0 100644 --- a/core/res/res/anim/app_starting_exit.xml +++ b/core/res/res/anim/app_starting_exit.xml @@ -19,6 +19,6 @@ --> - + diff --git a/core/res/res/anim/dialog_enter.xml b/core/res/res/anim/dialog_enter.xml index fd08cd03eae383e012429add18d71c51ba68e042..cc409e8f5a05b8dbd1d18888bf0ac54ebfc99eb0 100644 --- a/core/res/res/anim/dialog_enter.xml +++ b/core/res/res/anim/dialog_enter.xml @@ -20,10 +20,10 @@ - + android:duration="@android:integer/config_shortAnimTime" /> + android:duration="@android:integer/config_shortAnimTime" /> diff --git a/core/res/res/anim/dialog_exit.xml b/core/res/res/anim/dialog_exit.xml index e1b7a775978fa08481c7f5e9ebd17456bcda1018..8bf808247b6ae3deba2ae01245c59ff4dd94edd9 100644 --- a/core/res/res/anim/dialog_exit.xml +++ b/core/res/res/anim/dialog_exit.xml @@ -19,10 +19,10 @@ --> - + android:duration="@android:integer/config_shortAnimTime" /> + android:duration="@android:integer/config_shortAnimTime"/> diff --git a/core/res/res/anim/fade_in.xml b/core/res/res/anim/fade_in.xml index 32eea014ecc21e7c9663b0f6fa21c37f9f64a0f2..57310d9dd72213c689f87ed49b111cc223594edf 100644 --- a/core/res/res/anim/fade_in.xml +++ b/core/res/res/anim/fade_in.xml @@ -18,4 +18,7 @@ */ --> - + diff --git a/core/res/res/anim/fade_out.xml b/core/res/res/anim/fade_out.xml index e8ae9c10814552cfb52763fe5c9b0432a5979650..dc7627607bebf9017779354ab037a872f3c015b3 100644 --- a/core/res/res/anim/fade_out.xml +++ b/core/res/res/anim/fade_out.xml @@ -21,5 +21,5 @@ diff --git a/core/res/res/anim/grow_fade_in.xml b/core/res/res/anim/grow_fade_in.xml index 09698575572079f209f1f8b5f49043621349af54..5dc41cb002182b3523cf4685afa1ac2211a32e57 100644 --- a/core/res/res/anim/grow_fade_in.xml +++ b/core/res/res/anim/grow_fade_in.xml @@ -21,6 +21,9 @@ - + android:pivotX="0%" android:pivotY="0%" + android:duration="@android:integer/config_shortAnimTime" /> + diff --git a/core/res/res/anim/grow_fade_in_center.xml b/core/res/res/anim/grow_fade_in_center.xml index 01d7a7771ba10d17e70064747f66f62a577f89e0..c07a82e0556f5ac14f291169da9eed609089b3b6 100644 --- a/core/res/res/anim/grow_fade_in_center.xml +++ b/core/res/res/anim/grow_fade_in_center.xml @@ -21,6 +21,9 @@ - + android:pivotX="50%" android:pivotY="50%" + android:duration="@android:integer/config_shortAnimTime" /> + diff --git a/core/res/res/anim/grow_fade_in_from_bottom.xml b/core/res/res/anim/grow_fade_in_from_bottom.xml index d3e468db3d2d0884e4d25caf97041211e5ca4108..848c6773a67dc8e71ec00b538ed123aa232a55e7 100644 --- a/core/res/res/anim/grow_fade_in_from_bottom.xml +++ b/core/res/res/anim/grow_fade_in_from_bottom.xml @@ -21,6 +21,9 @@ - + android:pivotX="0%" android:pivotY="100%" + android:duration="@android:integer/config_shortAnimTime" /> + diff --git a/core/res/res/anim/input_method_enter.xml b/core/res/res/anim/input_method_enter.xml index 572a266f53fd3e7bf9e05b877df89149862107e4..3858651f2d374bdc8b83e83e6a8b126ca38d56ea 100644 --- a/core/res/res/anim/input_method_enter.xml +++ b/core/res/res/anim/input_method_enter.xml @@ -20,13 +20,8 @@ - - + + android:duration="@android:integer/config_shortAnimTime" /> diff --git a/core/res/res/anim/input_method_exit.xml b/core/res/res/anim/input_method_exit.xml index d28313af0bd4d1cba5d0b180678d00d73b6678c1..25369abb889dc03ff81ca06c6ac7766a354026b0 100644 --- a/core/res/res/anim/input_method_exit.xml +++ b/core/res/res/anim/input_method_exit.xml @@ -19,13 +19,8 @@ --> - - + + android:duration="@android:integer/config_shortAnimTime"/> diff --git a/core/res/res/drawable/checkbox.xml b/core/res/res/anim/input_method_fancy_enter.xml similarity index 52% rename from core/res/res/drawable/checkbox.xml rename to core/res/res/anim/input_method_fancy_enter.xml index 7a221856226bfc1a2dbbb3a57ad5b7ad18bb747d..c6949b35c1505d20bbdb0476f16ea35fb4ad3bdf 100644 --- a/core/res/res/drawable/checkbox.xml +++ b/core/res/res/anim/input_method_fancy_enter.xml @@ -1,6 +1,6 @@ - - - - - - - + + + + diff --git a/core/res/res/anim/input_method_fancy_exit.xml b/core/res/res/anim/input_method_fancy_exit.xml new file mode 100644 index 0000000000000000000000000000000000000000..7333cca12f145488d068529d32c17d1dc03d43d9 --- /dev/null +++ b/core/res/res/anim/input_method_fancy_exit.xml @@ -0,0 +1,28 @@ + + + + + + diff --git a/core/res/res/drawable/radiobutton.xml b/core/res/res/anim/lock_screen_exit.xml similarity index 51% rename from core/res/res/drawable/radiobutton.xml rename to core/res/res/anim/lock_screen_exit.xml index a72c82598ac29ec801c75ebed115ed333b138f44..55c5ec950ef0111abce27383e51116c404708681 100644 --- a/core/res/res/drawable/radiobutton.xml +++ b/core/res/res/anim/lock_screen_exit.xml @@ -1,6 +1,6 @@ - - - - - - + + + diff --git a/core/res/res/anim/options_panel_enter.xml b/core/res/res/anim/options_panel_enter.xml index 9614014a72f8df254e837552fbeda2a8d053dff6..d81866b6e2b91add7f1fc54de19d020daa32c6e7 100644 --- a/core/res/res/anim/options_panel_enter.xml +++ b/core/res/res/anim/options_panel_enter.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/options_panel_exit.xml b/core/res/res/anim/options_panel_exit.xml index c9bee1d0b14443a7c1e84a8d7b40f90e6c7003a5..4e7af7a4563cd056dea806c18c40399eef71700f 100644 --- a/core/res/res/anim/options_panel_exit.xml +++ b/core/res/res/anim/options_panel_exit.xml @@ -19,7 +19,9 @@ --> - - + + diff --git a/core/res/res/anim/push_down_in.xml b/core/res/res/anim/push_down_in.xml index 1cb15970c75b532fa0029b08666670cfbb54d76c..6ab9a047c02fe7eca4884d2cb3db2abfafbb2e2a 100644 --- a/core/res/res/anim/push_down_in.xml +++ b/core/res/res/anim/push_down_in.xml @@ -15,6 +15,8 @@ --> - - + + diff --git a/core/res/res/anim/push_down_out.xml b/core/res/res/anim/push_down_out.xml index 1ad49b06c476cb208fdf0e6642839000269698aa..ce36458aa5beecfd86ff1edf1eeeac91165a19e0 100644 --- a/core/res/res/anim/push_down_out.xml +++ b/core/res/res/anim/push_down_out.xml @@ -15,6 +15,8 @@ --> - - + + diff --git a/core/res/res/anim/push_up_in.xml b/core/res/res/anim/push_up_in.xml index a2f47e953c0aedb62c6d984f0a1cbe718b7f6f2f..6ef582c4e446aa9eeec6dc4095a951deb1083582 100644 --- a/core/res/res/anim/push_up_in.xml +++ b/core/res/res/anim/push_up_in.xml @@ -15,6 +15,8 @@ --> - - + + diff --git a/core/res/res/anim/push_up_out.xml b/core/res/res/anim/push_up_out.xml index 280343530fbcdb259d94a6ba47f07fcb95573787..2b267d598c4c3479dfb22921578d9878afa1d93c 100644 --- a/core/res/res/anim/push_up_out.xml +++ b/core/res/res/anim/push_up_out.xml @@ -15,6 +15,8 @@ --> - - + + diff --git a/core/res/res/anim/search_bar_enter.xml b/core/res/res/anim/search_bar_enter.xml index ecb86c152f4529bc957e817146549cd43a245aaa..c85caaa081abbd9248f89937b6479a6d1844d49b 100644 --- a/core/res/res/anim/search_bar_enter.xml +++ b/core/res/res/anim/search_bar_enter.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/search_bar_exit.xml b/core/res/res/anim/search_bar_exit.xml index db7142eb33ba1512279edce0b330dbd6ebf1340b..1609a129a1917ab11a57cc5065b06209186d6617 100644 --- a/core/res/res/anim/search_bar_exit.xml +++ b/core/res/res/anim/search_bar_exit.xml @@ -19,7 +19,9 @@ --> - - + + diff --git a/core/res/res/anim/shrink_fade_out.xml b/core/res/res/anim/shrink_fade_out.xml index ae15ff9fed20d240c29e8185620c235e3750eced..4000c2301e5201adf6f2bcb8be4a9efe490dbe5a 100644 --- a/core/res/res/anim/shrink_fade_out.xml +++ b/core/res/res/anim/shrink_fade_out.xml @@ -20,6 +20,9 @@ - + android:pivotX="0%" android:pivotY="0%" + android:duration="@android:integer/config_shortAnimTime" /> + diff --git a/core/res/res/anim/shrink_fade_out_center.xml b/core/res/res/anim/shrink_fade_out_center.xml index 7b0be34d480f59d6f313d0c97a5e0db076054dd1..a41731eb2fc15aaf6fe9949261ea94ffdc493b04 100644 --- a/core/res/res/anim/shrink_fade_out_center.xml +++ b/core/res/res/anim/shrink_fade_out_center.xml @@ -20,6 +20,9 @@ - + android:pivotX="50%" android:pivotY="50%" + android:duration="@android:integer/config_shortAnimTime" /> + diff --git a/core/res/res/anim/shrink_fade_out_from_bottom.xml b/core/res/res/anim/shrink_fade_out_from_bottom.xml index 61f29d5d8b676073d8d97885f7cd027122dbc862..345a2e061a06a57ba2593d5935102f4308d14cbb 100644 --- a/core/res/res/anim/shrink_fade_out_from_bottom.xml +++ b/core/res/res/anim/shrink_fade_out_from_bottom.xml @@ -20,6 +20,9 @@ - + android:pivotX="0%" android:pivotY="100%" + android:duration="@android:integer/config_shortAnimTime" /> + diff --git a/core/res/res/anim/slide_in_bottom.xml b/core/res/res/anim/slide_in_bottom.xml index 569d9741a3ed0bb491ec03ba6897861722898c97..d11185466cad9949504edfa54141e4df0da9816c 100644 --- a/core/res/res/anim/slide_in_bottom.xml +++ b/core/res/res/anim/slide_in_bottom.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/slide_in_child_bottom.xml b/core/res/res/anim/slide_in_child_bottom.xml index ce51c36e6de45ad0900bdf0c12c7e8acca907a4b..2ab0f66b594a5b9d320ad893551e046332508e27 100644 --- a/core/res/res/anim/slide_in_child_bottom.xml +++ b/core/res/res/anim/slide_in_child_bottom.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/slide_in_left.xml b/core/res/res/anim/slide_in_left.xml index 033bfe26eb7d76783590d2f96e7d84bf881b118d..9a585f5b736603b388e1e00bc9e16fd242119d21 100644 --- a/core/res/res/anim/slide_in_left.xml +++ b/core/res/res/anim/slide_in_left.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/slide_in_right.xml b/core/res/res/anim/slide_in_right.xml index 76b336c15ea09ecb1dfe1750c977b6407f8df3a5..125060e43a66c80086ab92ec2c0f2b633e0b2536 100644 --- a/core/res/res/anim/slide_in_right.xml +++ b/core/res/res/anim/slide_in_right.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/slide_in_top.xml b/core/res/res/anim/slide_in_top.xml index 15df9131ff37dbdc5cec86a2437db489ff0ee027..f4810abae39b4bc0fdf1f67b68b7e3ec7bc4efed 100644 --- a/core/res/res/anim/slide_in_top.xml +++ b/core/res/res/anim/slide_in_top.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/slide_out_bottom.xml b/core/res/res/anim/slide_out_bottom.xml index 8f6e8b06b297413b3b8ccf08694b8ee2db676136..8ddcd59b784533e3d1a632c6e420093fd38c1d56 100644 --- a/core/res/res/anim/slide_out_bottom.xml +++ b/core/res/res/anim/slide_out_bottom.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/slide_out_left.xml b/core/res/res/anim/slide_out_left.xml index 979d10ae14ea373339d4b5519f9ebcbe01d995f8..73337d4f92f3c62342ac56f74b3edac9d1b3b919 100644 --- a/core/res/res/anim/slide_out_left.xml +++ b/core/res/res/anim/slide_out_left.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/slide_out_right.xml b/core/res/res/anim/slide_out_right.xml index b5f9bb9f97f0aed12634371d1bd34bc65c39c329..de8c512c52f8d5878fd3dad2f9a2699d1dbd71cf 100644 --- a/core/res/res/anim/slide_out_right.xml +++ b/core/res/res/anim/slide_out_right.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/slide_out_top.xml b/core/res/res/anim/slide_out_top.xml index b15323e342eedc189af0ba72660a863f07edacce..3134a5723d2ad3cfb94627d1cdb4c90239266b45 100644 --- a/core/res/res/anim/slide_out_top.xml +++ b/core/res/res/anim/slide_out_top.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/status_bar_enter.xml b/core/res/res/anim/status_bar_enter.xml index 2df1af4ccbcfa952bf7e2f3071e8697d009a7cd5..d308ad541cc051fbf9836db374f1108b9933775c 100644 --- a/core/res/res/anim/status_bar_enter.xml +++ b/core/res/res/anim/status_bar_enter.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/status_bar_exit.xml b/core/res/res/anim/status_bar_exit.xml index c72d014421c57c5f5ad5738249c4c45512738826..43a1b9a0b95b7ee44f4fb9eae0c1b6f5bcd652f4 100644 --- a/core/res/res/anim/status_bar_exit.xml +++ b/core/res/res/anim/status_bar_exit.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/submenu_enter.xml b/core/res/res/anim/submenu_enter.xml index 32a8054406b422ff52bce8f2790393576c454969..5a94971b724c55daf320d6826a832bf4fdb9eae1 100644 --- a/core/res/res/anim/submenu_enter.xml +++ b/core/res/res/anim/submenu_enter.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/submenu_exit.xml b/core/res/res/anim/submenu_exit.xml index 92837515b24f1e8a968c5eeaf9cba9528575ca98..20fbefc06b761c17afcc9cac4b985b06c6cc5af7 100644 --- a/core/res/res/anim/submenu_exit.xml +++ b/core/res/res/anim/submenu_exit.xml @@ -19,6 +19,8 @@ --> - - + + diff --git a/core/res/res/anim/task_close_enter.xml b/core/res/res/anim/task_close_enter.xml index 6bef7a4aef8df1d78b5b10ca0afcb044d6d783a1..c289869cafcb78edf56aa11445075440e62718ea 100644 --- a/core/res/res/anim/task_close_enter.xml +++ b/core/res/res/anim/task_close_enter.xml @@ -21,5 +21,6 @@ - + diff --git a/core/res/res/anim/task_close_exit.xml b/core/res/res/anim/task_close_exit.xml index 48dc31aa81213d0fec7c7e8a8081b515ccb97f99..96fff94a27b10c4492eb471b8fe0740407c4883d 100644 --- a/core/res/res/anim/task_close_exit.xml +++ b/core/res/res/anim/task_close_exit.xml @@ -20,5 +20,6 @@ - + diff --git a/core/res/res/anim/task_open_enter.xml b/core/res/res/anim/task_open_enter.xml index e498c9da0c210b5250e410c571ff8a7c220c5799..8e7d049ce8537a0aebf9fb2f57ccccb6f77b5f3a 100644 --- a/core/res/res/anim/task_open_enter.xml +++ b/core/res/res/anim/task_open_enter.xml @@ -20,5 +20,6 @@ - + diff --git a/core/res/res/anim/task_open_exit.xml b/core/res/res/anim/task_open_exit.xml index 8ef4006fbeab15ac570443a58a67fed7b50c25d1..5e5c66d0edf50711a924d435b91206eee4ee8749 100644 --- a/core/res/res/anim/task_open_exit.xml +++ b/core/res/res/anim/task_open_exit.xml @@ -21,5 +21,6 @@ - + diff --git a/core/res/res/anim/toast_enter.xml b/core/res/res/anim/toast_enter.xml index 83cb1fe006216770ff6c09d72a56a8e6f4b742ab..57310d9dd72213c689f87ed49b111cc223594edf 100644 --- a/core/res/res/anim/toast_enter.xml +++ b/core/res/res/anim/toast_enter.xml @@ -20,4 +20,5 @@ + android:fromAlpha="0.0" android:toAlpha="1.0" + android:duration="@android:integer/config_longAnimTime" /> diff --git a/core/res/res/anim/toast_exit.xml b/core/res/res/anim/toast_exit.xml index f922085dac09821ec9a9b5bdcc336842f6cc57e5..b7c5fa004ad809cb8fbe48a8eae69d6ae371985a 100644 --- a/core/res/res/anim/toast_exit.xml +++ b/core/res/res/anim/toast_exit.xml @@ -20,5 +20,6 @@ diff --git a/core/res/res/color/tertiary_text_dark.xml b/core/res/res/color/tertiary_text_dark.xml index 7e61fc89d8a51d891c7489c655bf8a35c87134e2..7ce3580f36c9f7adbc9c93302da50fe0ab12ea8b 100644 --- a/core/res/res/color/tertiary_text_dark.xml +++ b/core/res/res/color/tertiary_text_dark.xml @@ -18,7 +18,7 @@  - + diff --git a/core/res/res/drawable-land/statusbar_background.png b/core/res/res/drawable-land/statusbar_background.png index 9e82f752dd25aef0e24ee5117d0190ab2fd351b2..2a351a5f96e6b54457adb6c9e4f6ea2a6f459ae8 100644 Binary files a/core/res/res/drawable-land/statusbar_background.png and b/core/res/res/drawable-land/statusbar_background.png differ diff --git a/core/res/res/drawable-land/title_bar_tall.png b/core/res/res/drawable-land/title_bar_tall.png new file mode 100644 index 0000000000000000000000000000000000000000..16290fb3a800ff71027274eb308af3b4582b5ff0 Binary files /dev/null and b/core/res/res/drawable-land/title_bar_tall.png differ diff --git a/core/res/res/drawable/activity_title_bar.9.png b/core/res/res/drawable/activity_title_bar.9.png new file mode 100644 index 0000000000000000000000000000000000000000..bd0680d50616556672054791dccfcffa008d04b8 Binary files /dev/null and b/core/res/res/drawable/activity_title_bar.9.png differ diff --git a/core/res/res/drawable/btn_browser_zoom_fit_page.xml b/core/res/res/drawable/btn_browser_zoom_fit_page.xml new file mode 100644 index 0000000000000000000000000000000000000000..2f4761a155e28e4f5782e0360edf33cb501092f9 --- /dev/null +++ b/core/res/res/drawable/btn_browser_zoom_fit_page.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/core/res/res/drawable/btn_browser_zoom_page_overview.xml b/core/res/res/drawable/btn_browser_zoom_page_overview.xml new file mode 100644 index 0000000000000000000000000000000000000000..16fb1e60210beae1ee4ce539edf80fdd1494a557 --- /dev/null +++ b/core/res/res/drawable/btn_browser_zoom_page_overview.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/core/res/res/drawable/btn_check_off_disable.png b/core/res/res/drawable/btn_check_off_disable.png index 6c065bde1cf882359303ebfcae12a4f446d6494b..e012afd28ddd52f9f05231f7eafd702775be9b3c 100644 Binary files a/core/res/res/drawable/btn_check_off_disable.png and b/core/res/res/drawable/btn_check_off_disable.png differ diff --git a/core/res/res/drawable/btn_check_off_disable_focused.png b/core/res/res/drawable/btn_check_off_disable_focused.png index cf23690371b733eec0f813b6d60d32cbfc926a15..0837bbdb89f71b0ef943e07d66302575efb328a8 100644 Binary files a/core/res/res/drawable/btn_check_off_disable_focused.png and b/core/res/res/drawable/btn_check_off_disable_focused.png differ diff --git a/core/res/res/drawable/btn_check_off_pressed.png b/core/res/res/drawable/btn_check_off_pressed.png index 47c1a460f110f500a9de3d832594dc794e3ae90c..984dfd750d306252e304a01ebec9f7ec2850d42d 100644 Binary files a/core/res/res/drawable/btn_check_off_pressed.png and b/core/res/res/drawable/btn_check_off_pressed.png differ diff --git a/core/res/res/drawable/btn_check_off_selected.png b/core/res/res/drawable/btn_check_off_selected.png index cf53075c0aad86c68d34ef221d1877db850d54b8..20842d41c8f18a8e9d60b543e14448c6c6840203 100644 Binary files a/core/res/res/drawable/btn_check_off_selected.png and b/core/res/res/drawable/btn_check_off_selected.png differ diff --git a/core/res/res/drawable/btn_check_on_disable.png b/core/res/res/drawable/btn_check_on_disable.png index 8e9f633e13ac023c5a2433f06877bc7f7da6ae30..6cb02f3e4674b7cb2557394d0f6bb40b15a52294 100644 Binary files a/core/res/res/drawable/btn_check_on_disable.png and b/core/res/res/drawable/btn_check_on_disable.png differ diff --git a/core/res/res/drawable/btn_check_on_disable_focused.png b/core/res/res/drawable/btn_check_on_disable_focused.png index 0abb0519f7a1d96b5c892af2c6a56f63a09dfc2b..8a73b33f0df551d797f546b506f323d76c570a8a 100644 Binary files a/core/res/res/drawable/btn_check_on_disable_focused.png and b/core/res/res/drawable/btn_check_on_disable_focused.png differ diff --git a/core/res/res/drawable/btn_check_on_pressed.png b/core/res/res/drawable/btn_check_on_pressed.png index ee2175d04711605373602c5b92fa4507e3958be8..300d64afecb925b757895df7b65bfde1e06a3fdb 100644 Binary files a/core/res/res/drawable/btn_check_on_pressed.png and b/core/res/res/drawable/btn_check_on_pressed.png differ diff --git a/core/res/res/drawable/btn_check_on_selected.png b/core/res/res/drawable/btn_check_on_selected.png index 9356456577b43d874e8c2c05b4a556628dfc177e..0b36adbe27125188f1f68ba9940d446659fc456a 100644 Binary files a/core/res/res/drawable/btn_check_on_selected.png and b/core/res/res/drawable/btn_check_on_selected.png differ diff --git a/core/res/res/drawable/btn_circle.xml b/core/res/res/drawable/btn_circle.xml new file mode 100644 index 0000000000000000000000000000000000000000..920801033c1fc8f04c309a2afdea521a70d9def7 --- /dev/null +++ b/core/res/res/drawable/btn_circle.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + diff --git a/core/res/res/drawable/btn_circle_disable.png b/core/res/res/drawable/btn_circle_disable.png new file mode 100644 index 0000000000000000000000000000000000000000..33b74a66c07f360cd4590aff32f83aaf3e1db888 Binary files /dev/null and b/core/res/res/drawable/btn_circle_disable.png differ diff --git a/core/res/res/drawable/btn_circle_disable_focused.png b/core/res/res/drawable/btn_circle_disable_focused.png new file mode 100644 index 0000000000000000000000000000000000000000..005ad8dcaeaeb6f245fe6090282ac10fbdc1c78d Binary files /dev/null and b/core/res/res/drawable/btn_circle_disable_focused.png differ diff --git a/core/res/res/drawable/btn_circle_longpress.png b/core/res/res/drawable/btn_circle_longpress.png new file mode 100644 index 0000000000000000000000000000000000000000..f27d4119b42fd3f879afb7e05f75762d0aaea9d0 Binary files /dev/null and b/core/res/res/drawable/btn_circle_longpress.png differ diff --git a/core/res/res/drawable/btn_circle_normal.png b/core/res/res/drawable/btn_circle_normal.png new file mode 100644 index 0000000000000000000000000000000000000000..fc5af1c9fc508aa63af280b7c68926db9c0f07be Binary files /dev/null and b/core/res/res/drawable/btn_circle_normal.png differ diff --git a/core/res/res/drawable/btn_circle_pressed.png b/core/res/res/drawable/btn_circle_pressed.png new file mode 100644 index 0000000000000000000000000000000000000000..8f40afdfcb30cf7e2f014bba7c03ff2372d539e2 Binary files /dev/null and b/core/res/res/drawable/btn_circle_pressed.png differ diff --git a/core/res/res/drawable/btn_circle_selected.png b/core/res/res/drawable/btn_circle_selected.png new file mode 100644 index 0000000000000000000000000000000000000000..c74fac227a2381ea347e0ee4930b0f60cd00645e Binary files /dev/null and b/core/res/res/drawable/btn_circle_selected.png differ diff --git a/core/res/res/drawable/btn_default_normal.9.png b/core/res/res/drawable/btn_default_normal.9.png index ad1634ad273e0fec4e10cf97aca1b757ac49a97a..a2d5ccd20c59189a67fb7c1990aff851bdb3b68b 100644 Binary files a/core/res/res/drawable/btn_default_normal.9.png and b/core/res/res/drawable/btn_default_normal.9.png differ diff --git a/core/res/res/drawable/btn_default_normal_disable.9.png b/core/res/res/drawable/btn_default_normal_disable.9.png index a89f37d82d9a2fd1592844ef4e644c02db5a4422..edd3a3eb22cc387b27d75ba6ae8d856859805a0a 100644 Binary files a/core/res/res/drawable/btn_default_normal_disable.9.png and b/core/res/res/drawable/btn_default_normal_disable.9.png differ diff --git a/core/res/res/drawable/btn_default_normal_disable_focused.9.png b/core/res/res/drawable/btn_default_normal_disable_focused.9.png index b71dae9250fbea7e24bd00577859815d4add64a7..f506179795bf55e27cc8b012537123b803e3267f 100644 Binary files a/core/res/res/drawable/btn_default_normal_disable_focused.9.png and b/core/res/res/drawable/btn_default_normal_disable_focused.9.png differ diff --git a/core/res/res/drawable/btn_default_pressed.9.png b/core/res/res/drawable/btn_default_pressed.9.png index f496a86b8655899d50722f642c8be51016e4cfb8..033bf89cb8f9da8d5ce83a7e082e211331b6bdbf 100644 Binary files a/core/res/res/drawable/btn_default_pressed.9.png and b/core/res/res/drawable/btn_default_pressed.9.png differ diff --git a/core/res/res/drawable/btn_default_selected.9.png b/core/res/res/drawable/btn_default_selected.9.png index c9e7e647a3e4f8ac3f8a2e788901fb64b17e505a..1e900bf1a03ed285a80104951ee9cb2e2f8aec59 100644 Binary files a/core/res/res/drawable/btn_default_selected.9.png and b/core/res/res/drawable/btn_default_selected.9.png differ diff --git a/core/res/res/drawable/btn_default_small_normal.9.png b/core/res/res/drawable/btn_default_small_normal.9.png index faac205a9966fd4144a0f022a0e4ffc5d5356826..bcedd5f0ff38f9693b699b7f1e9e88389be99d81 100644 Binary files a/core/res/res/drawable/btn_default_small_normal.9.png and b/core/res/res/drawable/btn_default_small_normal.9.png differ diff --git a/core/res/res/drawable/btn_default_small_normal_disable.9.png b/core/res/res/drawable/btn_default_small_normal_disable.9.png index ce4fd287e680acb005557d081e73c12a7f561e72..ac6260f906c80bb489483252ba03857002875e67 100644 Binary files a/core/res/res/drawable/btn_default_small_normal_disable.9.png and b/core/res/res/drawable/btn_default_small_normal_disable.9.png differ diff --git a/core/res/res/drawable/btn_default_small_normal_disable_focused.9.png b/core/res/res/drawable/btn_default_small_normal_disable_focused.9.png index 1f04c18bd5431783301ed2d0e5c14a00c1854528..4ee1b3fb17a7eed1c881d277721bb05271bd7780 100644 Binary files a/core/res/res/drawable/btn_default_small_normal_disable_focused.9.png and b/core/res/res/drawable/btn_default_small_normal_disable_focused.9.png differ diff --git a/core/res/res/drawable/btn_default_small_pressed.9.png b/core/res/res/drawable/btn_default_small_pressed.9.png index dab005bb452ff60a344cfb0cf99d9003986ea925..25e38f4e7635449fe7f3bc107e95875052e8ece9 100644 Binary files a/core/res/res/drawable/btn_default_small_pressed.9.png and b/core/res/res/drawable/btn_default_small_pressed.9.png differ diff --git a/core/res/res/drawable/btn_default_small_selected.9.png b/core/res/res/drawable/btn_default_small_selected.9.png index 5dec50465bc53c461023b42e86db2674f62efdbe..cc209c6a21c579ef146ab8294127c4c64dfc65d9 100644 Binary files a/core/res/res/drawable/btn_default_small_selected.9.png and b/core/res/res/drawable/btn_default_small_selected.9.png differ diff --git a/core/res/res/drawable/btn_keyboard_key_normal.9.png b/core/res/res/drawable/btn_keyboard_key_normal.9.png index 5c8a94514d9bc80093b7d79c1d02dd434d4cc4a1..7ba18dd25ac8f79d769a2291c77ab2844e3d21b3 100644 Binary files a/core/res/res/drawable/btn_keyboard_key_normal.9.png and b/core/res/res/drawable/btn_keyboard_key_normal.9.png differ diff --git a/core/res/res/drawable/btn_keyboard_key_normal_off.9.png b/core/res/res/drawable/btn_keyboard_key_normal_off.9.png index e6e640a54e9ecc9ec91bac1de1c2a1ca8c0424b6..bda9b83941ff20ac6ce4a46912dfd292957be711 100644 Binary files a/core/res/res/drawable/btn_keyboard_key_normal_off.9.png and b/core/res/res/drawable/btn_keyboard_key_normal_off.9.png differ diff --git a/core/res/res/drawable/btn_keyboard_key_normal_on.9.png b/core/res/res/drawable/btn_keyboard_key_normal_on.9.png index ce97a44140d512a127234e8c0f92c83f86a680b0..0c16ed5093dfcac53807d9d9663c516e52bb07ca 100644 Binary files a/core/res/res/drawable/btn_keyboard_key_normal_on.9.png and b/core/res/res/drawable/btn_keyboard_key_normal_on.9.png differ diff --git a/core/res/res/drawable/btn_keyboard_key_pressed.9.png b/core/res/res/drawable/btn_keyboard_key_pressed.9.png index f2e9f04511cb6eea6c2be1e689203f543e7ac139..39b9314a1a699813ecc408a150b7ac8b7b4217d9 100755 Binary files a/core/res/res/drawable/btn_keyboard_key_pressed.9.png and b/core/res/res/drawable/btn_keyboard_key_pressed.9.png differ diff --git a/core/res/res/drawable/btn_keyboard_key_pressed_off.9.png b/core/res/res/drawable/btn_keyboard_key_pressed_off.9.png index d541f95c9ecc885ce3a2a3827f1ad9b566bfed6d..bdcf06e1b8986fd3d5fc87d41037c7c037c6584b 100644 Binary files a/core/res/res/drawable/btn_keyboard_key_pressed_off.9.png and b/core/res/res/drawable/btn_keyboard_key_pressed_off.9.png differ diff --git a/core/res/res/drawable/btn_keyboard_key_pressed_on.9.png b/core/res/res/drawable/btn_keyboard_key_pressed_on.9.png index 1cd6d459600e20f949e7a2cfa71a3b4673ebcc3f..79621a9e6300cc77259b6af19649931e47611c4a 100644 Binary files a/core/res/res/drawable/btn_keyboard_key_pressed_on.9.png and b/core/res/res/drawable/btn_keyboard_key_pressed_on.9.png differ diff --git a/core/res/res/drawable/btn_radio_off_pressed.png b/core/res/res/drawable/btn_radio_off_pressed.png index 41120ae82e21ecb650781d21282c4c2c3682a3e9..d6d8a9d4b6853f801a82d75a4fd1e3b28bc98ae1 100644 Binary files a/core/res/res/drawable/btn_radio_off_pressed.png and b/core/res/res/drawable/btn_radio_off_pressed.png differ diff --git a/core/res/res/drawable/btn_radio_off_selected.png b/core/res/res/drawable/btn_radio_off_selected.png index 8b5535d0520e34b8099c3e1af0c915c51360c173..53f3e870e77da902b19940b2929b333f92be10c2 100644 Binary files a/core/res/res/drawable/btn_radio_off_selected.png and b/core/res/res/drawable/btn_radio_off_selected.png differ diff --git a/core/res/res/drawable/btn_radio_on.png b/core/res/res/drawable/btn_radio_on.png index 7286b312aeea0290e81f97ed3e69c4b82e5376ba..25a3ccc54e4ae648e204ea0c9072b5f238d124ab 100644 Binary files a/core/res/res/drawable/btn_radio_on.png and b/core/res/res/drawable/btn_radio_on.png differ diff --git a/core/res/res/drawable/btn_radio_on_pressed.png b/core/res/res/drawable/btn_radio_on_pressed.png index 20ce0ec0055c4b7c468eadb2622e03b0fb397a66..c904a35c742bc9a72b022ae741e9f400675350b9 100644 Binary files a/core/res/res/drawable/btn_radio_on_pressed.png and b/core/res/res/drawable/btn_radio_on_pressed.png differ diff --git a/core/res/res/drawable/btn_radio_on_selected.png b/core/res/res/drawable/btn_radio_on_selected.png index ed53dc7f81ded974452e754d5e89bc3c8d9be503..78e1fc0227ca308ec26aca487e4955092981e57c 100644 Binary files a/core/res/res/drawable/btn_radio_on_selected.png and b/core/res/res/drawable/btn_radio_on_selected.png differ diff --git a/core/res/res/drawable/btn_rating_star_off_normal.png b/core/res/res/drawable/btn_rating_star_off_normal.png index bb154040df73853a9be8d832962138762991728d..a99441dc1a7025776bd0b448c192978c1d23c5db 100644 Binary files a/core/res/res/drawable/btn_rating_star_off_normal.png and b/core/res/res/drawable/btn_rating_star_off_normal.png differ diff --git a/core/res/res/drawable/btn_rating_star_off_pressed.png b/core/res/res/drawable/btn_rating_star_off_pressed.png index 45482b9e338883a4d936bd677d24fc9abf540b8f..f47a45415bdca827865050c83e15cc1d4baa4214 100644 Binary files a/core/res/res/drawable/btn_rating_star_off_pressed.png and b/core/res/res/drawable/btn_rating_star_off_pressed.png differ diff --git a/core/res/res/drawable/btn_rating_star_off_selected.png b/core/res/res/drawable/btn_rating_star_off_selected.png index 3fbe92ae7bea62ca6d32c5140566ace933367ba3..5f71e0873ee1f0a7ae5404dbf1338f486ce556f4 100644 Binary files a/core/res/res/drawable/btn_rating_star_off_selected.png and b/core/res/res/drawable/btn_rating_star_off_selected.png differ diff --git a/core/res/res/drawable/btn_rating_star_on_normal.png b/core/res/res/drawable/btn_rating_star_on_normal.png index 1c329a1e7df962f6f34b2a4af64d99ec78add54b..b7825d321770f001fb37767d6013c7f6b45b27c7 100644 Binary files a/core/res/res/drawable/btn_rating_star_on_normal.png and b/core/res/res/drawable/btn_rating_star_on_normal.png differ diff --git a/core/res/res/drawable/btn_rating_star_on_pressed.png b/core/res/res/drawable/btn_rating_star_on_pressed.png index 2a965a7466fed0a9d2a180cbde34707fd5127ba9..4052445ab945a86f0e6ea712a7c5aec0b3f3ab42 100644 Binary files a/core/res/res/drawable/btn_rating_star_on_pressed.png and b/core/res/res/drawable/btn_rating_star_on_pressed.png differ diff --git a/core/res/res/drawable/btn_rating_star_on_selected.png b/core/res/res/drawable/btn_rating_star_on_selected.png index 2c1e207422706bb708579c4b25142ce101b783e9..5d139b6153a9d5c98392ec94ce2fe0ce190bf663 100644 Binary files a/core/res/res/drawable/btn_rating_star_on_selected.png and b/core/res/res/drawable/btn_rating_star_on_selected.png differ diff --git a/core/res/res/drawable/btn_square_overlay.xml b/core/res/res/drawable/btn_square_overlay.xml new file mode 100644 index 0000000000000000000000000000000000000000..a2c698c896c7e3032fe243a77a62abe08b3befbc --- /dev/null +++ b/core/res/res/drawable/btn_square_overlay.xml @@ -0,0 +1,26 @@ + + + + + + + + + + \ No newline at end of file diff --git a/core/res/res/drawable/btn_square_overlay_disabled.png b/core/res/res/drawable/btn_square_overlay_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..cf7e4ea7f2b3e651139f28f659f8b2e1c82b4ab6 Binary files /dev/null and b/core/res/res/drawable/btn_square_overlay_disabled.png differ diff --git a/core/res/res/drawable/btn_square_overlay_disabled_focused.png b/core/res/res/drawable/btn_square_overlay_disabled_focused.png new file mode 100644 index 0000000000000000000000000000000000000000..5aa1143e6741288736afbab56324246599ff3a46 Binary files /dev/null and b/core/res/res/drawable/btn_square_overlay_disabled_focused.png differ diff --git a/core/res/res/drawable/btn_square_overlay_normal.png b/core/res/res/drawable/btn_square_overlay_normal.png new file mode 100644 index 0000000000000000000000000000000000000000..45fa4feaf6d8d99a7b8b3e0160c1178f4c7d0357 Binary files /dev/null and b/core/res/res/drawable/btn_square_overlay_normal.png differ diff --git a/core/res/res/drawable/btn_square_overlay_pressed.png b/core/res/res/drawable/btn_square_overlay_pressed.png new file mode 100644 index 0000000000000000000000000000000000000000..952571bf5e9e8f97ab55ee62d1666c898956b168 Binary files /dev/null and b/core/res/res/drawable/btn_square_overlay_pressed.png differ diff --git a/core/res/res/drawable/btn_square_overlay_selected.png b/core/res/res/drawable/btn_square_overlay_selected.png new file mode 100644 index 0000000000000000000000000000000000000000..ce4515eb94a86a7c9cb81984990ca3f783234201 Binary files /dev/null and b/core/res/res/drawable/btn_square_overlay_selected.png differ diff --git a/core/res/res/drawable/btn_star_big_off.png b/core/res/res/drawable/btn_star_big_off.png index 21ba55751b39a6930a5494896208b419e2f0f071..7e9342b5c33e98925c55367a12088c98a345459c 100755 Binary files a/core/res/res/drawable/btn_star_big_off.png and b/core/res/res/drawable/btn_star_big_off.png differ diff --git a/core/res/res/drawable/btn_star_big_off_pressed.png b/core/res/res/drawable/btn_star_big_off_pressed.png index 2c704ee2a787a7e195014f10d450308c13ede29e..f1b8912f90c5344e985fc35b20d19003b6d7efc3 100755 Binary files a/core/res/res/drawable/btn_star_big_off_pressed.png and b/core/res/res/drawable/btn_star_big_off_pressed.png differ diff --git a/core/res/res/drawable/btn_star_big_off_selected.png b/core/res/res/drawable/btn_star_big_off_selected.png index 101357db07a2d4d96f872de8e74fee34e294a671..0be64c41609522c367a06ef233ada955efd1563d 100755 Binary files a/core/res/res/drawable/btn_star_big_off_selected.png and b/core/res/res/drawable/btn_star_big_off_selected.png differ diff --git a/core/res/res/drawable/btn_star_big_on.png b/core/res/res/drawable/btn_star_big_on.png index 9c2f7d2023f9d5baf8d883164079b61af6a93d8d..a9bdb052a97045083df59295c0d245bc29fa999c 100755 Binary files a/core/res/res/drawable/btn_star_big_on.png and b/core/res/res/drawable/btn_star_big_on.png differ diff --git a/core/res/res/drawable/btn_star_big_on_pressed.png b/core/res/res/drawable/btn_star_big_on_pressed.png index 8ac4bab9075db5b28634363b0f08ffc13a131273..159a84bb8dc74b5537bad66257c1f066e07cc792 100755 Binary files a/core/res/res/drawable/btn_star_big_on_pressed.png and b/core/res/res/drawable/btn_star_big_on_pressed.png differ diff --git a/core/res/res/drawable/btn_star_big_on_selected.png b/core/res/res/drawable/btn_star_big_on_selected.png index d453eabb15778c85bcf1d394d3b4215efc847777..0592d5180afd6292c32bda4e8dbed93849095a4a 100755 Binary files a/core/res/res/drawable/btn_star_big_on_selected.png and b/core/res/res/drawable/btn_star_big_on_selected.png differ diff --git a/core/res/res/drawable/btn_zoom_down.xml b/core/res/res/drawable/btn_zoom_down.xml new file mode 100644 index 0000000000000000000000000000000000000000..e7449aacb9f1930cddedaa940994200d193b2cf2 --- /dev/null +++ b/core/res/res/drawable/btn_zoom_down.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + diff --git a/core/res/res/drawable/btn_zoom_down_disabled.9.png b/core/res/res/drawable/btn_zoom_down_disabled.9.png new file mode 100644 index 0000000000000000000000000000000000000000..7780bd758b40e37cbb6f24710cda0e25320dcc0f Binary files /dev/null and b/core/res/res/drawable/btn_zoom_down_disabled.9.png differ diff --git a/core/res/res/drawable/btn_zoom_down_disabled_focused.9.png b/core/res/res/drawable/btn_zoom_down_disabled_focused.9.png new file mode 100644 index 0000000000000000000000000000000000000000..39131c5629449eb093748e599c79403626085019 Binary files /dev/null and b/core/res/res/drawable/btn_zoom_down_disabled_focused.9.png differ diff --git a/core/res/res/drawable/btn_zoom_down_longpress.9.png b/core/res/res/drawable/btn_zoom_down_longpress.9.png new file mode 100644 index 0000000000000000000000000000000000000000..09a3bb358f8cbe6c86324f8291c9e17458153ed6 Binary files /dev/null and b/core/res/res/drawable/btn_zoom_down_longpress.9.png differ diff --git a/core/res/res/drawable/btn_zoom_down_normal.9.png b/core/res/res/drawable/btn_zoom_down_normal.9.png new file mode 100644 index 0000000000000000000000000000000000000000..b589a84309d9b3eedd9093f15821e9b63918fcae Binary files /dev/null and b/core/res/res/drawable/btn_zoom_down_normal.9.png differ diff --git a/core/res/res/drawable/btn_zoom_down_pressed.9.png b/core/res/res/drawable/btn_zoom_down_pressed.9.png new file mode 100644 index 0000000000000000000000000000000000000000..a8ca467324d2f8c1bb31dcef9de6aee90c4bd3be Binary files /dev/null and b/core/res/res/drawable/btn_zoom_down_pressed.9.png differ diff --git a/core/res/res/drawable/btn_zoom_down_selected.9.png b/core/res/res/drawable/btn_zoom_down_selected.9.png new file mode 100644 index 0000000000000000000000000000000000000000..af551e71ecb50e73362dc53d98955201e404c767 Binary files /dev/null and b/core/res/res/drawable/btn_zoom_down_selected.9.png differ diff --git a/core/res/res/drawable/btn_zoom_up.xml b/core/res/res/drawable/btn_zoom_up.xml new file mode 100644 index 0000000000000000000000000000000000000000..045b3c395120f616a38fd14427deb51f872074ba --- /dev/null +++ b/core/res/res/drawable/btn_zoom_up.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + diff --git a/core/res/res/drawable/btn_zoom_up_disabled.9.png b/core/res/res/drawable/btn_zoom_up_disabled.9.png new file mode 100644 index 0000000000000000000000000000000000000000..5203630e0a72b827e34ec60245cdb50e98ce304a Binary files /dev/null and b/core/res/res/drawable/btn_zoom_up_disabled.9.png differ diff --git a/core/res/res/drawable/btn_zoom_up_disabled_focused.9.png b/core/res/res/drawable/btn_zoom_up_disabled_focused.9.png new file mode 100644 index 0000000000000000000000000000000000000000..c72c9cd90aaf92dbab5bb834919ebe419759cf1a Binary files /dev/null and b/core/res/res/drawable/btn_zoom_up_disabled_focused.9.png differ diff --git a/core/res/res/drawable/btn_zoom_up_longpress.9.png b/core/res/res/drawable/btn_zoom_up_longpress.9.png new file mode 100644 index 0000000000000000000000000000000000000000..8de48d1008dd4d357865cbbdd673e113c127b09c Binary files /dev/null and b/core/res/res/drawable/btn_zoom_up_longpress.9.png differ diff --git a/core/res/res/drawable/btn_zoom_up_normal.9.png b/core/res/res/drawable/btn_zoom_up_normal.9.png new file mode 100644 index 0000000000000000000000000000000000000000..50273487943370ea2346323f24f3dd4170f7951f Binary files /dev/null and b/core/res/res/drawable/btn_zoom_up_normal.9.png differ diff --git a/core/res/res/drawable/btn_zoom_up_pressed.9.png b/core/res/res/drawable/btn_zoom_up_pressed.9.png new file mode 100644 index 0000000000000000000000000000000000000000..1a93e3a292825b9190631c47443ca6c85693fb42 Binary files /dev/null and b/core/res/res/drawable/btn_zoom_up_pressed.9.png differ diff --git a/core/res/res/drawable/btn_zoom_up_selected.9.png b/core/res/res/drawable/btn_zoom_up_selected.9.png new file mode 100644 index 0000000000000000000000000000000000000000..26aafee001c405f5a1b189de3fe0c3183e53c6da Binary files /dev/null and b/core/res/res/drawable/btn_zoom_up_selected.9.png differ diff --git a/core/res/res/drawable/checkbox_label_background.9.png b/core/res/res/drawable/checkbox_label_background.9.png deleted file mode 100644 index e6af4b073fe38fc777f5544348cec1f72efbef98..0000000000000000000000000000000000000000 Binary files a/core/res/res/drawable/checkbox_label_background.9.png and /dev/null differ diff --git a/core/res/res/drawable/checkbox_off_background_focus_yellow.png b/core/res/res/drawable/checkbox_off_background_focus_yellow.png deleted file mode 100644 index ffde6f828b78ff7034e765cc272bdbe707b31288..0000000000000000000000000000000000000000 Binary files a/core/res/res/drawable/checkbox_off_background_focus_yellow.png and /dev/null differ diff --git a/core/res/res/drawable/checkbox_on_background_focus_yellow.png b/core/res/res/drawable/checkbox_on_background_focus_yellow.png deleted file mode 100644 index 301800969c544cc97a2f68ad01ebb1bef48b69da..0000000000000000000000000000000000000000 Binary files a/core/res/res/drawable/checkbox_on_background_focus_yellow.png and /dev/null differ diff --git a/core/res/res/drawable/dark_header.9.png b/core/res/res/drawable/dark_header.9.png new file mode 100644 index 0000000000000000000000000000000000000000..8fa5f0915213677f3cfe086f40b2b546a98b767c Binary files /dev/null and b/core/res/res/drawable/dark_header.9.png differ diff --git a/core/res/res/drawable/divider_horizontal_bright.9.png b/core/res/res/drawable/divider_horizontal_bright.9.png index a1ba2d33d9c0e294f5d602cd884614e308b1a581..144fc224e9269da5436ed4639fac106dd173ba6c 100644 Binary files a/core/res/res/drawable/divider_horizontal_bright.9.png and b/core/res/res/drawable/divider_horizontal_bright.9.png differ diff --git a/core/res/res/drawable/divider_horizontal_dark.9.png b/core/res/res/drawable/divider_horizontal_dark.9.png index 7b32381b108cf3cc5400b34b1ff0f837f977b013..08838cafa8153e8e3aa68fdb2767a2d09589c9f0 100644 Binary files a/core/res/res/drawable/divider_horizontal_dark.9.png and b/core/res/res/drawable/divider_horizontal_dark.9.png differ diff --git a/core/res/res/drawable/divider_horizontal_dim_dark.9.png b/core/res/res/drawable/divider_horizontal_dim_dark.9.png index 20bc4dcf47b98c1709bd07ba0e0b5a291ff150b8..08838cafa8153e8e3aa68fdb2767a2d09589c9f0 100644 Binary files a/core/res/res/drawable/divider_horizontal_dim_dark.9.png and b/core/res/res/drawable/divider_horizontal_dim_dark.9.png differ diff --git a/core/res/res/drawable/extract_edit_text.xml b/core/res/res/drawable/extract_edit_text.xml new file mode 100644 index 0000000000000000000000000000000000000000..c7f66f6b199fefbf815e4b223852d45157c6c084 --- /dev/null +++ b/core/res/res/drawable/extract_edit_text.xml @@ -0,0 +1,21 @@ + + + + + + + + diff --git a/core/res/res/drawable/ic_btn_round_more.xml b/core/res/res/drawable/ic_btn_round_more.xml new file mode 100644 index 0000000000000000000000000000000000000000..82b759337e8f819fc67429e6a42c475b108ce693 --- /dev/null +++ b/core/res/res/drawable/ic_btn_round_more.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/core/res/res/drawable/ic_btn_round_more_disabled.png b/core/res/res/drawable/ic_btn_round_more_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..1ab98c985e7ed7411f702e388fc5f83fcd5444cf Binary files /dev/null and b/core/res/res/drawable/ic_btn_round_more_disabled.png differ diff --git a/core/res/res/drawable/ic_btn_round_more_normal.png b/core/res/res/drawable/ic_btn_round_more_normal.png new file mode 100644 index 0000000000000000000000000000000000000000..ebdc55c272de3cc483ad90984ef6cef7051b3beb Binary files /dev/null and b/core/res/res/drawable/ic_btn_round_more_normal.png differ diff --git a/core/res/res/drawable/ic_btn_speak_now.png b/core/res/res/drawable/ic_btn_speak_now.png new file mode 100644 index 0000000000000000000000000000000000000000..83ee68b5d1f5ccca87d156e682f32f091619ceb7 Binary files /dev/null and b/core/res/res/drawable/ic_btn_speak_now.png differ diff --git a/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page.xml b/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page.xml new file mode 100644 index 0000000000000000000000000000000000000000..bec869a813b0744c1b60d05f5f342b9695621b82 --- /dev/null +++ b/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page.xml @@ -0,0 +1,20 @@ + + + + + + + \ No newline at end of file diff --git a/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page_disabled.png b/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..326397cbf03654ef346c8da5be93be4276a0f468 Binary files /dev/null and b/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page_disabled.png differ diff --git a/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page_normal.png b/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page_normal.png new file mode 100644 index 0000000000000000000000000000000000000000..55834010e7ac9cbde4933e9a405eac96091c185e Binary files /dev/null and b/core/res/res/drawable/ic_btn_square_browser_zoom_fit_page_normal.png differ diff --git a/core/res/res/drawable/ic_btn_square_browser_zoom_page_overview.png b/core/res/res/drawable/ic_btn_square_browser_zoom_page_overview.png new file mode 100644 index 0000000000000000000000000000000000000000..4e8ff35ad97176a3319b3900e70d0c48e7be177c Binary files /dev/null and b/core/res/res/drawable/ic_btn_square_browser_zoom_page_overview.png differ diff --git a/core/res/res/drawable/ic_lock_airplane_mode.png b/core/res/res/drawable/ic_lock_airplane_mode.png new file mode 100755 index 0000000000000000000000000000000000000000..caafcb2ef53d4f4f32dd735a67812c0358c33d56 Binary files /dev/null and b/core/res/res/drawable/ic_lock_airplane_mode.png differ diff --git a/core/res/res/drawable/ic_lock_airplane_mode_off.png b/core/res/res/drawable/ic_lock_airplane_mode_off.png new file mode 100755 index 0000000000000000000000000000000000000000..cb2cbdf181a6badeb0fc3573906470aae3b0cbcd Binary files /dev/null and b/core/res/res/drawable/ic_lock_airplane_mode_off.png differ diff --git a/core/res/res/drawable/ic_lock_power_off.png b/core/res/res/drawable/ic_lock_power_off.png index 14c002e9d5e572cd40a8b0b9e080e7aa232ab0d9..4405b437e59c37607c357c985529aeeefe094fd5 100644 Binary files a/core/res/res/drawable/ic_lock_power_off.png and b/core/res/res/drawable/ic_lock_power_off.png differ diff --git a/core/res/res/drawable/ic_lock_silent_mode.png b/core/res/res/drawable/ic_lock_silent_mode.png index c89291a2073168c418a91fb0045a0adb5dd8c09a..439a6f59ec5a4cf717ca80b38b1b0feded85ea69 100644 Binary files a/core/res/res/drawable/ic_lock_silent_mode.png and b/core/res/res/drawable/ic_lock_silent_mode.png differ diff --git a/core/res/res/drawable/ic_lock_silent_mode_off.png b/core/res/res/drawable/ic_lock_silent_mode_off.png index 4748b9ed7a6c4e2ef684286a5a6a352ab80a912d..fc7e960aa588b43c28ffee1570ef779061f35fe7 100644 Binary files a/core/res/res/drawable/ic_lock_silent_mode_off.png and b/core/res/res/drawable/ic_lock_silent_mode_off.png differ diff --git a/core/res/res/drawable/keyboard_accessory_bg_landscape.9.png b/core/res/res/drawable/keyboard_accessory_bg_landscape.9.png new file mode 100644 index 0000000000000000000000000000000000000000..8f828f6fe7eaf8523b21d86596c867db9b00d97e Binary files /dev/null and b/core/res/res/drawable/keyboard_accessory_bg_landscape.9.png differ diff --git a/core/res/res/drawable/keyboard_background.9.png b/core/res/res/drawable/keyboard_background.9.png index 595acc587efe6e086c9a4a61612683f27c1dc7e7..1d3ce05b86df845bcb7f38f2c4a9f224b8d00798 100644 Binary files a/core/res/res/drawable/keyboard_background.9.png and b/core/res/res/drawable/keyboard_background.9.png differ diff --git a/core/res/res/drawable/keyboard_suggest_strip_shadow.9.png b/core/res/res/drawable/keyboard_suggest_strip_shadow.9.png new file mode 100644 index 0000000000000000000000000000000000000000..d231ae686ec82c175b37690d5cc4481c93e19b35 Binary files /dev/null and b/core/res/res/drawable/keyboard_suggest_strip_shadow.9.png differ diff --git a/core/res/res/drawable/keyboard_textfield_selected.9.png b/core/res/res/drawable/keyboard_textfield_selected.9.png new file mode 100644 index 0000000000000000000000000000000000000000..6e703af76f49f71298b42b06ec25007445280b2c Binary files /dev/null and b/core/res/res/drawable/keyboard_textfield_selected.9.png differ diff --git a/core/res/res/drawable/menu_background.9.png b/core/res/res/drawable/menu_background.9.png index e7266b2c0011e2ae452b0deda0fe02df0c08669a..ee99583594a24c14c411856fb7b9a554b740aa2c 100644 Binary files a/core/res/res/drawable/menu_background.9.png and b/core/res/res/drawable/menu_background.9.png differ diff --git a/core/res/res/drawable/popup_inline_error_above.9.png b/core/res/res/drawable/popup_inline_error_above.9.png new file mode 100644 index 0000000000000000000000000000000000000000..2e601d0c81d63923291d78800f6bce62d0998ed8 Binary files /dev/null and b/core/res/res/drawable/popup_inline_error_above.9.png differ diff --git a/core/res/res/drawable/presence_away.png b/core/res/res/drawable/presence_away.png index a539ec7787190c1e5aa5627bf388478de8c7fbfe..f8120df43bfe56831686901c2aeed0d15f693f4e 100644 Binary files a/core/res/res/drawable/presence_away.png and b/core/res/res/drawable/presence_away.png differ diff --git a/core/res/res/drawable/presence_busy.png b/core/res/res/drawable/presence_busy.png index 1e3f547b8cd31c98c022f9d05392db678e54a2f0..9d7620b1d0c8d50f4e86df6743d11fd6b8558ab8 100644 Binary files a/core/res/res/drawable/presence_busy.png and b/core/res/res/drawable/presence_busy.png differ diff --git a/core/res/res/drawable/presence_invisible.png b/core/res/res/drawable/presence_invisible.png index fb86cf128342148d45bb0c74b8b015cddedd1152..21399a4f3618f0e6549016cd7b53e75767029de6 100644 Binary files a/core/res/res/drawable/presence_invisible.png and b/core/res/res/drawable/presence_invisible.png differ diff --git a/core/res/res/drawable/presence_offline.png b/core/res/res/drawable/presence_offline.png index da54fe7fccf409e86b29ec072f8710d7aeac85c7..3941b8205251753b2a12c04a64c71407ad5d6b56 100644 Binary files a/core/res/res/drawable/presence_offline.png and b/core/res/res/drawable/presence_offline.png differ diff --git a/core/res/res/drawable/presence_online.png b/core/res/res/drawable/presence_online.png index 879a762955d18520d1abb221e5f03ec44398515e..22d5683e2f5970a3f53b9d8970713863b6b83d2d 100644 Binary files a/core/res/res/drawable/presence_online.png and b/core/res/res/drawable/presence_online.png differ diff --git a/core/res/res/drawable/radiobutton_label_background.9.png b/core/res/res/drawable/radiobutton_label_background.9.png deleted file mode 100644 index e6af4b073fe38fc777f5544348cec1f72efbef98..0000000000000000000000000000000000000000 Binary files a/core/res/res/drawable/radiobutton_label_background.9.png and /dev/null differ diff --git a/core/res/res/drawable/radiobutton_off_background_focus_yellow.png b/core/res/res/drawable/radiobutton_off_background_focus_yellow.png deleted file mode 100644 index 1a092e363df13ed0582410d09d82ba55244a44b2..0000000000000000000000000000000000000000 Binary files a/core/res/res/drawable/radiobutton_off_background_focus_yellow.png and /dev/null differ diff --git a/core/res/res/drawable/radiobutton_on_background_focus_yellow.png b/core/res/res/drawable/radiobutton_on_background_focus_yellow.png deleted file mode 100644 index aa59771b38e35920f3de95d51f9ee1f849c6fea2..0000000000000000000000000000000000000000 Binary files a/core/res/res/drawable/radiobutton_on_background_focus_yellow.png and /dev/null differ diff --git a/core/res/res/drawable/scrollbar_handle_accelerated_anim2.9.png b/core/res/res/drawable/scrollbar_handle_accelerated_anim2.9.png index d96cb3f4f86053586424332a88960013c667bf0f..85caddd74e7feb031bbd538cd2c61757f8be53fd 100755 Binary files a/core/res/res/drawable/scrollbar_handle_accelerated_anim2.9.png and b/core/res/res/drawable/scrollbar_handle_accelerated_anim2.9.png differ diff --git a/core/res/res/drawable/scrollbar_handle_horizontal.9.png b/core/res/res/drawable/scrollbar_handle_horizontal.9.png index f333733f85c982a4ff59eaa8699376ab9483649f..8584d1f0adce2e3ff4e3e709490651f7080a0a76 100755 Binary files a/core/res/res/drawable/scrollbar_handle_horizontal.9.png and b/core/res/res/drawable/scrollbar_handle_horizontal.9.png differ diff --git a/core/res/res/drawable/scrollbar_handle_vertical.9.png b/core/res/res/drawable/scrollbar_handle_vertical.9.png index ff0829503c417e020389ebe7821b16e3c5ce524a..331a05dc760b757fb369ff1bae6b13881e6214de 100755 Binary files a/core/res/res/drawable/scrollbar_handle_vertical.9.png and b/core/res/res/drawable/scrollbar_handle_vertical.9.png differ diff --git a/core/res/res/drawable/seek_thumb.xml b/core/res/res/drawable/seek_thumb.xml index 7fe51b382c080db9129110b616fcd788a3d999a6..c7a862d9d1faa3fa5f8e26237c136226cbbd81e4 100644 --- a/core/res/res/drawable/seek_thumb.xml +++ b/core/res/res/drawable/seek_thumb.xml @@ -14,7 +14,7 @@ limitations under the License. --> - + + + + diff --git a/core/res/res/drawable/title_bar_shadow.9.png b/core/res/res/drawable/title_bar_shadow.9.png new file mode 100644 index 0000000000000000000000000000000000000000..0872366579748a8c6f0f13aa1376c605c6aaa61c Binary files /dev/null and b/core/res/res/drawable/title_bar_shadow.9.png differ diff --git a/core/res/res/drawable/title_bar_shadow.png b/core/res/res/drawable/title_bar_shadow.png deleted file mode 100644 index a7178144287fcdc794b97b79909345e04a9f97ec..0000000000000000000000000000000000000000 Binary files a/core/res/res/drawable/title_bar_shadow.png and /dev/null differ diff --git a/core/res/res/drawable/title_bar_tall.png b/core/res/res/drawable/title_bar_tall.png new file mode 100644 index 0000000000000000000000000000000000000000..cd565dc8f7634849842bb39cc6f77a114904ae19 Binary files /dev/null and b/core/res/res/drawable/title_bar_tall.png differ diff --git a/core/res/res/layout/activity_list.xml b/core/res/res/layout/activity_list.xml new file mode 100644 index 0000000000000000000000000000000000000000..2967f0f269f8d0a1b8b30be359a344a15197b3bd --- /dev/null +++ b/core/res/res/layout/activity_list.xml @@ -0,0 +1,38 @@ + + + + + + + + + + diff --git a/core/res/res/layout/activity_list_item_2.xml b/core/res/res/layout/activity_list_item_2.xml new file mode 100644 index 0000000000000000000000000000000000000000..78eca026c2413d91a99c127678879d05c460c6d3 --- /dev/null +++ b/core/res/res/layout/activity_list_item_2.xml @@ -0,0 +1,25 @@ + + + + diff --git a/core/res/res/layout/alert_dialog_simple_text.xml b/core/res/res/layout/alert_dialog_simple_text.xml new file mode 100644 index 0000000000000000000000000000000000000000..ab82be7f74190246eb4919bdae7c7c53f7ef4f50 --- /dev/null +++ b/core/res/res/layout/alert_dialog_simple_text.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/core/res/res/layout/date_picker.xml b/core/res/res/layout/date_picker.xml index a398bd006bccde8a6edbfd25be509322b5a530cf..0760cc0b7123dc783b1419442afd327c954711d0 100644 --- a/core/res/res/layout/date_picker.xml +++ b/core/res/res/layout/date_picker.xml @@ -24,6 +24,7 @@ diff --git a/core/res/res/layout/date_picker_dialog.xml b/core/res/res/layout/date_picker_dialog.xml index 879f3398f1bfdababbf4aabe2fff8dcdf9671f8e..949c8a3082c7394b8c5dbc5cf2b1718cc602b394 100644 --- a/core/res/res/layout/date_picker_dialog.xml +++ b/core/res/res/layout/date_picker_dialog.xml @@ -17,11 +17,9 @@ */ --> - - - + diff --git a/core/res/res/layout/expanded_menu_layout.xml b/core/res/res/layout/expanded_menu_layout.xml index cd4ea12e442c263ca6606a04302fadc112a9614d..5d9877364d8be7ff1c30a092d9d48d354e52e528 100644 --- a/core/res/res/layout/expanded_menu_layout.xml +++ b/core/res/res/layout/expanded_menu_layout.xml @@ -16,5 +16,5 @@ diff --git a/core/res/res/layout/global_actions_item.xml b/core/res/res/layout/global_actions_item.xml index 43831276e9105cd5352c741887738f606490122c..63bb0f457d3f1b33ea4ecabd52678c7b8b1730df 100644 --- a/core/res/res/layout/global_actions_item.xml +++ b/core/res/res/layout/global_actions_item.xml @@ -14,38 +14,48 @@ limitations under the License. --> - - + + + - + android:layout_toRightOf="@id/icon" + android:layout_alignParentRight="true" + android:layout_alignParentTop="true" + android:layout_above="@id/status" + android:layout_alignWithParentIfMissing="true" + android:gravity="center_vertical" + android:textAppearance="?android:attr/textAppearanceLargeInverse" + /> - - - + diff --git a/core/res/res/layout/google_web_content_helper_layout.xml b/core/res/res/layout/google_web_content_helper_layout.xml index 74096212781b46b7d16cd8445fd23335b910bf65..40f84bf8f3da729fce72dc0a8f34abe967940c12 100644 --- a/core/res/res/layout/google_web_content_helper_layout.xml +++ b/core/res/res/layout/google_web_content_helper_layout.xml @@ -20,7 +20,7 @@ diff --git a/core/res/res/layout/input_method_extract_view.xml b/core/res/res/layout/input_method_extract_view.xml index f8a4bdee04799bd46721b398b80b4087eff07741..1244c1daa1b79e738db94f4ba9691f8811e68bae 100644 --- a/core/res/res/layout/input_method_extract_view.xml +++ b/core/res/res/layout/input_method_extract_view.xml @@ -18,11 +18,38 @@ */ --> - - + android:orientation="horizontal"> + + + + + + + + + + + diff --git a/core/res/res/layout/js_prompt.xml b/core/res/res/layout/js_prompt.xml index 9ab9d09fee1e6151abebad372075421483081ff3..86974ba860df090d42ac8c03ef13d4e47e553492 100644 --- a/core/res/res/layout/js_prompt.xml +++ b/core/res/res/layout/js_prompt.xml @@ -20,16 +20,17 @@ android:layout_height="wrap_content" android:gravity="center_horizontal" > - + - + - - - - - + android:layout_height="0px" + android:layout_weight="1" + android:layout_above="@+id/emergencyCall"> + + + + + + + + + + + + + + +

          Nine-patch / 9-patch / Ninepatch image
          diff --git a/docs/html/guide/appendix/media-formats.jd b/docs/html/guide/appendix/media-formats.jd index 41dfd639801f95c4a9ab5da62ef4d76335f570c3..5419ad679297fe506c13cb6e45c96b2fa79420ed 100644 --- a/docs/html/guide/appendix/media-formats.jd +++ b/docs/html/guide/appendix/media-formats.jd @@ -20,7 +20,7 @@ page.title=Android Supported Media Formats -Audio +Audio AAC LC/LTP   X @@ -82,6 +82,14 @@ page.title=Android Supported Media Formats Ogg (.ogg) + +PCM/WAVE +  +X +8- and 16-bit linear PCM (rates up to limit of hardware) +WAVE (.wav) + + Image JPEG diff --git a/docs/html/guide/basics/anatomy.jd b/docs/html/guide/basics/anatomy.jd deleted file mode 100755 index f4b2ad0a6b284f8dcaed780c8d5e493e24113d83..0000000000000000000000000000000000000000 --- a/docs/html/guide/basics/anatomy.jd +++ /dev/null @@ -1,134 +0,0 @@ -page.title=Anatomy of an Android Application -@jd:body -

          Anatomy of an Android Application

          - -

          -There are four building blocks to an Android application: -

          - -
            -
          • Activity
          • -
          • Broadcast Receiver
          • -
          • Service
          • -
          • Content Provider
          • -
          - -

          -Not every application needs to have all four, but your application will be written with some -combination of these. -

          - -

          -Once you have decided what components you need for your application, you should list them in a file -called AndroidManifest.xml. This is an XML file where you declare the components of your application -and what their capabilities and requirements are. See the -Android manifest file documentation -for complete details. -

          - -

          Activity

          -

          -Activities are the most common of the four Android building blocks. An activity is usually a single -screen in your application. Each activity is implemented as a single class that extends the -{@link android.app.Activity Activity} base class. Your class will display a user interface composed -of {@link android.view.View Views} and respond to events. Most applications consist of multiple -screens. For example, a text messaging application might have one screen that shows a list of -contacts to send messages to, a second screen to write the message to the chosen contact, and other -screens to review old messages or change settings. Each of these screens would be implemented as an -activity. Moving to another screen is accomplished by a starting a new activity. In some cases an -activity may return a value to the previous activity -- for example an activity that lets the user -pick a photo would return the chosen photo to the caller. -

          - -

          -When a new screen opens, the previous screen is paused and put onto a history stack. The user can -navigate backward through previously opened screens in the history. Screens can also choose to be -removed from the history stack when it would be inappropriate for them to remain. Android retains -history stacks for each application launched from the home screen. -

          - -

          Intent and Intent Filters

          - -

          -Android uses a special class called an {@link android.content.Intent Intent} to move from screen to -screen. An intent describes what an application wants done. The two most important parts of the -intent data structure are the action and the data to act upon. Typical values for action are MAIN -(the front door of the application), VIEW, PICK, EDIT, etc. The data is expressed as a URI. -For example, to view contact information for a person, you would create an intent with the VIEW -action and the data set to a URI representing that person. -

          - -

          -There is a related class called an {@link android.content.IntentFilter IntentFilter}. While an -intent is effectively a request to do something, an intent filter is a description of what intents - an activity (or broadcast receiver, see below) is capable of handling. An activity that is able to - display contact information for a person would publish an IntentFilter that said that it knows - how to handle the action VIEW when applied to data representing a person. - Activities publish their IntentFilters in the AndroidManifest.xml file. -

          - -

          -Navigating from screen to screen is accomplished by resolving intents. To navigate forward, an -activity calls {@link android.app.Activity#startActivity startActivity(myIntent)}. -The system then looks at the intent filters for all installed applications and picks the activity -whose intent filters best matches myIntent. The new activity is informed of the intent, which causes -it to be launched. The process of resolving intents happens at run time when startActivity is -called, which offers two key benefits: -

          - -
            -
          • Activities can reuse functionality from other components simply by making a request in the form of an Intent
          • -
          • Activities can be replaced at any time by a new Activity with an equivalent IntentFilter
          • -
          - - -

          Broadcast Receiver

          - -

          -You can use a {@link android.content.BroadcastReceiver BroadcastReceiver} when you want code in your -application to execute in reaction to an external event, for example, when the phone rings, or when -the data network is available, or when it's midnight. Broadcast receivers do not display a UI, although -they may use the {@link android.app.NotificationManager NotificationManager} to alert the user if -something interesting has happened. Broadcast receivers are registered in AndroidManifest.xml, but you -can also register them from code using -{@link android.content.Context#registerReceiver Context.registerReceiver()}. -Your application does not have to be running for its broadcast receivers to be called; the system will -start your application, if necessary, when a broadcast receiver is triggered. Applications can also send -their own intent broadcasts to others with -{@link android.content.Context#sendBroadcast Context.sendBroadcast()}. -

          - -

          Service

          - -

          -A {@link android.app.Service Service} is code that is long-lived and runs without a UI. A good -example of this is a media player playing songs from a play list. In a media player application, -there would probably be one or more activities that allow the user to choose songs and start -playing them. However, the music playback itself should not be handled by an activity because the -user will expect the music to keep playing even after navigating to a new screen. In this case, the -media player activity could start a service using -{@link android.content.Context#startService Context.startService()} -to run in the background to keep the music going. The system will then keep the music playback -service running until it has finished. (You can learn more about the priority given to services in -the system by reading -Life Cycle of an Android Application.) -Note that you can connect to a -service (and start it if it's not already running) with the -{@link android.content.Context#bindService Context.bindService() } method. -When connected to a service, you can communicate with it through an interface exposed by the -service. For the music service, this might allow you to pause, rewind, etc. -

          - -

          Content Provider

          -

          -Applications can store their data in files, an SQLite database, or any other mechanism that makes -sense. A content provider, however, is useful if you want your application's data to be shared with -other applications. A content provider is a class that implements a standard set of methods to let -other applications store and retrieve the type of data that is handled by that content provider. -

          - -

          -To get more details on content providers, see -Accessing Content Providers. -

          - diff --git a/docs/html/guide/basics/android-sdk.jd b/docs/html/guide/basics/android-sdk.jd deleted file mode 100644 index d1f3437004380ab49ca2bf644c961a88820491ff..0000000000000000000000000000000000000000 --- a/docs/html/guide/basics/android-sdk.jd +++ /dev/null @@ -1,11 +0,0 @@ -page.title=The Android SDK -@jd:body - -

          FIXME

          - -

          The downloadable Android SDK includes the Android API libraries, sample code, documentation, -and a collection of Android development tools, like the emulator and debugger.

          - -

          The SDK supports developing on Linux, Mac OS X, and Windows (XP and Vista).

          - -

          The Java Development Kit is required.

          \ No newline at end of file diff --git a/docs/html/guide/basics/app-framework.jd b/docs/html/guide/basics/app-framework.jd deleted file mode 100644 index 8513884f66f0bfdc041baeb066075f1b5f28915d..0000000000000000000000000000000000000000 --- a/docs/html/guide/basics/app-framework.jd +++ /dev/null @@ -1,4 +0,0 @@ -page.title=The Application Framework -@jd:body - -TODO \ No newline at end of file diff --git a/docs/html/guide/basics/what-is-android.jd b/docs/html/guide/basics/what-is-android.jd index 9e2801a7d01fd7723884fc686ba83ff5f48956c3..b75321bc62c5403cdfad8bac3835b7bfd934e4cc 100644 --- a/docs/html/guide/basics/what-is-android.jd +++ b/docs/html/guide/basics/what-is-android.jd @@ -2,7 +2,7 @@ page.title=What is Android? @jd:body

          Android is a software stack for mobile devices that includes an operating -system, middleware and key applications. This beta version of the Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

          diff --git a/docs/html/guide/developing/debug-tasks.jd b/docs/html/guide/developing/debug-tasks.jd index a604df2bf84bde2b8abfa0112213207d2c45bfd8..6b7c27a66a94941c378bb0fe06f294a62475e0f4 100644 --- a/docs/html/guide/developing/debug-tasks.jd +++ b/docs/html/guide/developing/debug-tasks.jd @@ -53,7 +53,7 @@ D/ActivityManager( 763): Stopping: HistoryRecord{409dbb20 com.android.home.AllAp graphical reader called Traceview. See the linked topic for more information.
            -
          • Eclipse plugin - The ADT Plugin +
          • Eclipse plugin - The ADT Plugin for Eclipse integrates a number of these tools (ADB, DDMS, logcat output, and other functionality). See the linked topic for more information.
          • Debug and Test Device Settings - Android exposes several settings diff --git a/docs/html/guide/developing/device.jd b/docs/html/guide/developing/device.jd index b7237978eda40bb849cf3d9a20c69afb708e1a21..35c0a1ae0c52269daeefe811a57b18e55467c64b 100644 --- a/docs/html/guide/developing/device.jd +++ b/docs/html/guide/developing/device.jd @@ -7,8 +7,8 @@ page.title=Developing on a Device
            1. Available Devices
                -
              1. T-Mobile G1
              2. -
              3. Android Dev Phone 1
              4. +
              5. T-Mobile G1
              6. +
              7. Android Dev Phone 1
            2. Setting up a Device for Development
            3. @@ -41,8 +41,9 @@ href="http://www.t-mobileg1.com">T-Mobile G1 site.

              Android Dev Phone 1

              -
            + +

            Setting Up Application Signing

            + +

            As you begin developing Android applications, you should understand that all +Android applications must be digitally signed before the system will install +them on the emulator or an actual device.

            + +

            The ADT plugin helps you get started quickly by signing your .apk files with +a debug key, prior to installing them on the emulator. This means that you can +compile your application and install it on the emulator without having to +generate your own private key. However, please note that if you intend to +publish your application, you must sign the application with your own +private key, rather than the debug key generated by the SDK tools.

            + +

            To sign your applications, the ADT plugin requires the Keytool utility +included in the JDK. To set up your development environment for +signing, you need to make sure that Keytool is available on your +machine that the ADT plugin knows how to find it.

            + +

            In most cases, you can tell the SDK build tools how to find Keytool by making +sure that your JAVA_HOME environment variable is set and that it references a +suitable JDK. Alternatively, you can add the JDK version of Keytool to your +PATH variable.

            + +

            If you are developing on a version of Linux that originally came with Gnu +Compiler for Java, make sure that the system is using the JDK version of +Keytool, rather than the gcj version. If keytool is already in your PATH, it +might be pointing to a symlink at /usr/bin/keytool. In this case, check the +symlink target to make sure that it points to the keytool in the JDK.

            + +

            In all cases, please read and understand Signing Your +Applications, which provides an overview of application signing on Android +and what it means to you as an Android application developer.

            + + -

            Running and Debugging an Application

            +

            Running and Debugging an Application

            Once you've set up the project and launch configuration for your application, you can run or debug it as described below.

            @@ -98,7 +145,8 @@ From the Eclipse main menu, select Run > Run -

            Eclipse Tips

            + +

            Eclipse Tips

            Executing arbitrary Java expressions in Eclipse

            You can execute arbitrary code when paused at a breakpoint in Eclipse. For example, when in a function with a String argument called "zip", you can get diff --git a/docs/html/guide/developing/instrumentation/index.jd b/docs/html/guide/developing/instrumentation/index.jd deleted file mode 100644 index 7ebd72e3d9014915ff75252454eff7195695b94c..0000000000000000000000000000000000000000 --- a/docs/html/guide/developing/instrumentation/index.jd +++ /dev/null @@ -1,54 +0,0 @@ -page.title=Instrumentation -@jd:body - -

            -
            Instrumentation Framework
            -
            Instrumentation Testing
            -
            - - \ No newline at end of file diff --git a/docs/html/guide/developing/instrumentation/inst-framework.jd b/docs/html/guide/developing/instrumentation/inst-framework.jd deleted file mode 100644 index 17eea61259031ec8beb36a4644459d5c785cf1f6..0000000000000000000000000000000000000000 --- a/docs/html/guide/developing/instrumentation/inst-framework.jd +++ /dev/null @@ -1,139 +0,0 @@ -page.title=Instrumentation Framework -@jd:body - -

            This document describes how to use the Android Instrumentation Framework to write test cases. You should have a working knowledge of the following:

            -
              -
            • Android Application Framework
            • -
            • Using adb, am and various logging functionality
            • -
            • A brief understanding of the application of interest, that is, he names of the classes which handle the intents etc.
            • -
            • Junit testing.
            • -
            -

            Each Android application runs in its own process. Instrumentation kills the application process and restarts the process with Instrumentation. Instrumentation gives a handle to the application context used to poke around the application to validate test assertions, allowing you to write test cases to test applications at a much lower level than UI screen shot tests. Note that Instrumentation cannot catch UI bugs.

            - -

            This document covers these topics:

            - - - -

            Understanding the am Command

            - -

            am is used to start and instrument activities using the adb shell command, as shown in the snippet below:

            -
            -> adb shell am
            -usage: am [start|instrument]
            -       am start [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
            -                [-c <CATEGORY> [-c <CATEGORY>] ...]
            -                [-e <EXTRA_KEY> <EXTRA_VALUE> [-e <EXTRA_KEY> <EXTRA_VALUE> ...]
            -                [-n <COMPONENT>] [-D] [<URI>]
            -       am instrument [-e <ARG_NAME> <ARG_VALUE>] [-p <PROF_FILE>]
            -                [-w] <COMPONENT>
            -For example, to start the Contacts application you can use
            -> adb shell am start -n com.google.android.contacts/.ContactsActivity
            -
            - - -

            Writing and Running Test Cases

            - -

            Each instrumentation test case is similar to an Android application with the distinction that it starts another application. For example, have a look in the tests/Contacts directory.

            -
              -
            • There should be a Makefile and an Android Manifest file.
            • -
            • Tests are located in tests/Contacts/src/com/google/android/contactstests.
            • -
            • The Instrumentation Test Runner is located at tests/Contacts/src/com/google/android/contactstests/functional/ContactsInstrumentationTestRunner.java.
            • -
            -

            Suppose you have a makefile with Contactstests as the target.

            -
              -
            • make Contactstests: Compiles the test cases.
            • -
            • adb install Contactstests.apk: Installs the apk on the device.
            • -
            • Use the adb shell am command to run them.
            • -
            -

            For options and other details, please see Instrumentation Testing.

            - - -

            Exploring a Test Case

            - -

            The test case described in this section adds and tests a new Contact. Note that you can send intents, register broadcast receivers, etc.

            -

            Instrumentation.java has helper functions that send key events and string, for example:

            -
              -
            • getInstrumentation(): Returns the handle to the instrumentation
            • -
            • sendCharacterSync: Sends a character.
            • -
            • sendStringSync: Sends a string to an input box.
            • -
            • sendKeyDownUpSync: Sends a specific keyevent.
            • -
            • sendTrackballEventSync: Send a trackball event.
            • -
            -

            You can find the test case below at device/tests/Contacts.

            -
            -private void addNewContact(String name, int star, int phoneType, String number, String label,
            -		String email, int emailType){
            -	ContentValues values = new ContentValues();
            -	Uri phoneUri = null;
            -	Uri emailUri = null;
            -
            -	values.put(Contacts.People.NAME, name);
            -	values.put(Contacts.People.STARRED, star);
            -
            -	//Add Phone Numbers
            -	Uri uri = mActivity.getContentResolver().insert(Contacts.People.CONTENT_URI, values);
            -	phoneUri = Uri.withAppendedPath(uri, Contacts.People.Phones.CONTENT_DIRECTORY);
            -
            -	values.clear();
            -	values.put(Contacts.Phones.TYPE, phoneType);
            -	values.put(Contacts.Phones.NUMBER, number);
            -	values.put(Contacts.Phones.LABEL, label);
            -	mActivity.getContentResolver().insert(phoneUri, values);
            -
            -	//Add Email
            -	emailUri = Uri.withAppendedPath(uri, ContactMethods.CONTENT_DIRECTORY);
            -
            -	values.clear();
            -	values.put(ContactMethods.KIND, Contacts.KIND_EMAIL);
            -	values.put(ContactMethods.DATA, email);
            -	values.put(ContactMethods.LABEL, "");
            -	values.put(ContactMethods.TYPE, emailType);
            -	mActivity.getContentResolver().insert(emailUri, values);
            -}
            -
            -
            - public void testAddSaveSingleContact(){
            -	int previousCount = mActivity.getListView().getCount();
            -	String message;
            -
            -	addNewContact(INPUT_NAME_1 + "1", "5435754532", "1" + INPUT_EMAIL_1, CONFIRM_OPTION);
            -
            -	message = "Added 1 to initial length=" + previousCount + ", but resulted with a count=" +
            -		mActivity.getListView().getCount();
            -	assertEquals(message, ++previousCount, mActivity.getListView().getCount());
            -
            -	// Check Content; Name; Num; Starred
            -	assertEquals(INPUT_NAME_1 + "1", getTextFromView(0, android.R.id.text1));
            -	assertEquals("5435754532", getTextFromView(0, android.R.id.text2));
            -
            -	//Check email is saved
            -	//cursor = returnEmailCursorAtId("1");
            -	Uri uri = Uri.parse("content://contacts/people/1");
            -	uri = Uri.withAppendedPath(uri, ContactMethods.CONTENT_DIRECTORY);
            -	Cursor cursor = mActivity.getContentResolver().query(uri, CONTACTS_COLUMNS, null, null, null);
            -	assertTrue("returnEmailCursorAtId: Moving cursor to first row has failed", cursor.first());
            -
            -	int dataIndex = cursor.getColumnIndexOrThrow("data");
            -	assertEquals("1" + INPUT_EMAIL_1, cursor.getString(dataIndex));
            -	cursor.deactivate();
            -}
            -	
            - - -

            Troubleshooting

            - -

            If you run your test cases and nothing appears to happen, have a look at adb logcat. The following is a common problem:

            -
            -I/dalvikvm(  688): threadid=11: attached from native, name=Binder Thread #1
            -I/dalvikvm(  688): threadid=13: attached from native, name=Binder Thread #2
            -W/ActivityManager(  469): Unable to find instrumentation info for: ComponentInfo{com.google.android.browser_instrumentation/com.google.android.browser_instrumentation.BrowserWebkitLayoutInstrumentation}
            -D/AndroidRuntime(  688): Shutting down VM
            -E/AndroidRuntime(  688): ERROR: thread attach failed
            -
            -

            It's possible that the instrumentation apk isn't installed on your device or that the package name is incorrect in the Manifest file.

            - diff --git a/docs/html/guide/developing/instrumentation/inst-testing.jd b/docs/html/guide/developing/instrumentation/inst-testing.jd deleted file mode 100644 index 6f69344d7bad02ce13f164a602966784e935e240..0000000000000000000000000000000000000000 --- a/docs/html/guide/developing/instrumentation/inst-testing.jd +++ /dev/null @@ -1,207 +0,0 @@ - -page.title=Instrumentation Testing -@jd:body - -

            Sometimes you may want to manually interact with your applications to verify that a particular feature or behavior is working properly; why not automate this verification with a JUnit TestCase that can instrument applications?

            -

            Instrumentation testing allows you to verify a particular feature or behavior with an automated JUnit TestCase. You can launch activities and providers within an application, send key events, and make assertions about various UI elements.

            - -This document provides an overview of how to use instrumentation on Android and covers these topics: - - - - - - -

            Classes

            - -

            The following classes help glue together Instrumentation with JUnit testing.

            - - - - - - - - - - - - - - - - -
            ClassDescription
            InstrumentationTestCase -

            This extends the standard JUnit TestCase and offers access to an Instrumentation class. Write tests inside your instrumentation class any way you see fit. For example, your test might launch activities and send key events. For this to work properly, the instrumentation needs to be injected into the test case.

            -
            InstrumentationTestRunnerThe instrumentation test runner is an instrumentation that runs instrumentation test cases and injects itself into each test case. Instrumentation test cases need to be grouped together with an instrumentation test runner with the appropriate target package.
            InstrumentationTestSuiteThe instrumentation test suite is a simple extension of the standard JUnit TestSuite that keeps a member Instrumentation variable on hand to inject into each TestCase before running them. It is used by InstrumentationTestRunner.
            -

            Three additional base classes extend InstrumentationTestCase to allow you to test Activity and Provider classes:

            - - - - - - - - - - - - - - - - - -
            ClassDescription
            ActivityTestCase

            This class can be used to write tests for a specific activity. An activity is launched in its setUp() method and finished with tearDown. If you write a test case that extends ActivityTestCase, you can write tests that access the activity using getActivity() and assume it has been set up properly.

            SingleLaunchActivityTestCaseThis class is similar to ActivityTestCase except that the activity is launched once per class instead of every time the test case calls setup.
            ProviderTestCaseThis class is similar to ActivityTestCase except that it will setup, tear down, and provide access to the Provider of your choice.
            - - -

            Running Tests

            - -

            To run your tests, use the am instrument command with your InstrumentationTestRunner as its argument. Results are printed as a result of the instrumentation. For example, the following snippet displays the output after running the framework tests with one test failing (note the unusual syntax caused by how instrumentations are run via am):

            -
            -$ adb shell am instrument -w com.google.android.frameworktest/.tests.FrameworkInstrumentationTestRunner
            -INSTRUMENTATION_RESULT: test results:=.......F.......
            -Time: 6.837
            -There was 1 failure:
            -1) testSetUpConditions(com.google.android.frameworktest.tests.focus.RequestFocusTest)junit.framework.AssertionFailedError: requestFocus() should work from onCreate.
            -        at com.google.android.frameworktest.tests.focus.RequestFocusTest.testSetUpConditions(RequestFocusTest.java:66)
            -        at java.lang.reflect.Method.invokeNative(Native Method)
            -        at android.test.InstrumentationTestSuite.runTest(InstrumentationTestSuite.java:73)
            -        at android.test.InstrumentationTestSuite.runTest(InstrumentationTestSuite.java:73)
            -        at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:151)
            -        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1088)
            -
            -FAILURES!!!
            -Tests run: 14,  Failures: 1,  Errors: 0
            -
            -<RETURN> to continue
            -
            -INSTRUMENTATION_CODE: -1
            -$ 
            -
            - - -

            All Tests

            - -
            -$ adb shell am instrument -w MyInstrumentationTestRunner
            -
            - - -

            A Single Test Case

            - -
            -$ adb shell am instrument \
            -     -e class MyInstrumentationTestCase \
            -     -w MyInstrumentationTestRunner
            -
            - - -

            A Single Test

            - -
            -$ adb shell am instrument \
            -     -e class MyInstrumentationTestCase#myTestMethod \
            -     -w MyInstrumentationTestRunner
            -
            - - -

            Creating Tests

            - - - - - -

            New Instrumentation TestRunner

            - -
            -public class FrameworkInstrumentationTestRunner extends InstrumentationTestRunner {
            -
            -    @Override
            -    public TestSuite getAllTests() {
            -        InstrumentationTestSuite suite = new InstrumentationTestSuite(this);
            -
            -        suite.addTestSuite(FocusAfterRemovalTest.class);
            -        suite.addTestSuite(RequestFocusTest.class);
            -        suite.addTestSuite(RequestRectangleVisibleTest.class);
            -        return suite;
            -    }
            -
            -    @Override
            -    public ClassLoader getLoader() {
            -        return FrameworkInstrumentationTestRunner.class.getClassLoader();
            -    }
            -}
            -
            - -

            Next, in an appropriate AndroidManifest.xml, define the instrumentation for the derived class with the appropriate android:targetPackage set. For example, the snippet below defines the instrumentation runner for the framework tests.

            - -
            -<uses-permission android:name="android.permission.RUN_INSTRUMENTATION" />
            -
            -<instrumentation android:name="android.tests.FrameworkInstrumentationTestRunner"
            -                 android:targetPackage="com.google.android.frameworktest"
            -                 android:label="framework instrumentation test runner" />
            -
            - - - - -

            New InstrumentationTestCase

            - -

            To create a new test case, write a class that extends InstrumentationTestCase in the same application archive as your test runner. The following snippet illustrates an example ActivityTestCase that tests an activity named MyActivity.

            -
            -public class ButtonPressTest extends ActivityTestCase<MyActivity> {
            -
            -    Button mLeftButton;
            -
            -    public ButtonPressTest() {
            -        super("com.example", MyActivity.class);
            -    }
            -
            -    @Override
            -    public void setUp() throws Exception {
            -      super.setUp();
            -      mLeftButton = (Button) getActivity().findViewById(R.id.leftButton);
            -    }
            -
            -    public void testFocusMovesToRight() throws Exception {
            -        assertTrue(mLeftButton.hasFocus());
            -        getInstrumentation().sendCharacterSync(KeyEvent.KEYCODE_DPAD_RIGHT);
            -
            -        Button rightButton = (Button) getActivity().findViewById(R.id.rightButton);
            -        assertTrue(rightButton.hasFocus());
            -    }
            -
            -    // could have several more tests...
            -}
            -
            - - -

            Aliases for Running Framework Instrumentation Tests

            - -
            -# compiles and installs FrameworkTests
            -alias deploytests="(cd tests/FrameworkTests/ && mm) && adb install out/target/product/dream/system/app/FrameworkTest.apk"
            -
            -# runs all of FrameworkTests unit tests
            -alias runtests="adb shell am instrument -w com.google.android.frameworktest/.tests.FrameworkInstrumentationTestRunner"
            -
            -# runtest TEST: runs a single unit test, for instance runtest view.VisibilityTest
            -# -- for convenience, you don't have to type the com.google.android.frameworktest.tests.
            -function runtest {
            -    adb shell am instrument -e class com.google.android.frameworktest.tests.$1 -w com.google.android.frameworktest/.tests.FrameworkInstrumentationTestRunner
            -}
            -
            -# debugtest TEST: runs a single unit test in debug mode, for instance runtest view.VisibilityTest
            -function debugtest {
            -    adb shell am instrument -e debug true -e class com.google.android.frameworktest.tests.$1 -w com.google.android.frameworktest/.tests.FrameworkInstrumentationTestRunner
            -}
            -
            - - diff --git a/docs/html/guide/developing/other-ide.jd b/docs/html/guide/developing/other-ide.jd index 78871c55600941c0662188c6e111fc0c3c0ff3fa..7bcb509a4f4eee5ea10d335e32810d88891397ff 100644 --- a/docs/html/guide/developing/other-ide.jd +++ b/docs/html/guide/developing/other-ide.jd @@ -2,9 +2,9 @@ page.title=In Other IDEs @jd:body

            The recommended way to develop an Android application is to use - Eclipse - with the ADT plugin. This plugin provides editing, building, - and debugging functionality integrated right into the IDE.

            + Eclipse with the Android + Development Tools (ADT) plugin, provided in the SDK. The ADT plugin + provides editing, building,and debugging functionality integrated right into the IDE.

            However, if you'd rather develop your application in another IDE, such as IntelliJ, or use Eclipse without the ADT plugin, you can do that instead. The SDK @@ -82,6 +82,45 @@ activity_name: ActivityName latest version of the application for you to deploy.

          • +

            Setting Up Application Signing

            + +

            As you begin developing Android applications, you should understand that all +Android applications must be digitally signed before the system will install +them on the emulator or an actual device.

            + +

            The Android build tools help you get started quickly by signing your .apk +files with a debug key, prior to installing them on the emulator. This means +that you can compile your application and install it on the emulator without +having to generate your own private key. However, please note that if you intend +to publish your application, you must sign the application with your +own private key, rather than the debug key generated by the SDK tools.

            + +

            To sign your applications, the ADT plugin requires the Keytool utility +included in the JDK. To set up your development environment for +signing, all you need to do is make sure that Keytool is available on your +machine that the build tools know how to find it.

            + +

            In most cases, you can tell the SDK build tools how to find Keytool by making +sure that +your JAVA_HOME environment variable is set and that it references a suitable +JDK. Alternatively, +you can add the JDK version of Keytool to your PATH variable.

            + +

            If you are developing on a version of Linux that originally came with Gnu +Compiler for Java, +make sure that the system is using the JDK version of Keytool, rather than the +gcj version. +If keytool is already in your PATH, it might be pointing to a symlink at +/usr/bin/keytool. +In this case, check the symlink target to make sure that it points to the +keytool in the JDK.

            + +

            In all cases, please read and understand Signing Your +Applications, which provides an overview of application signing on Android +and what it means to you as an Android application developer.

            + +

            Running an Android Application

            To run a compiled application, you will upload the .apk file to the /data/app/ directory @@ -122,7 +161,7 @@ activity_name: ActivityName can be used without DDMS, such as displaying CPU usage or screen refresh rate on the emulator.

          • Configure your IDE to attach to port 8700 for debugging. We - include information on how to set up Eclipse to debug - your project.
          • + include information on + how to set up Eclipse to debug your project. diff --git a/docs/html/guide/developing/tools/adb.jd b/docs/html/guide/developing/tools/adb.jd index 50fb0248bb3331599b2d26b7778a22c9671e1be7..b111047e60bf4ded592454e388a755973fe7e5ba 100644 --- a/docs/html/guide/developing/tools/adb.jd +++ b/docs/html/guide/developing/tools/adb.jd @@ -104,7 +104,7 @@ Emulator 2, adb: 5557 ...
            adb [-d|-e|-s <serialNumber>] <command> 
            -

            When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.

            +

            When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.

            diff --git a/docs/html/guide/developing/tools/adt.jd b/docs/html/guide/developing/tools/adt.jd index c3bd25505a51991230bfcfcb09ac2901590f5c23..f28b24c2af013f8b305312e9218cd98ed1474c19 100644 --- a/docs/html/guide/developing/tools/adt.jd +++ b/docs/html/guide/developing/tools/adt.jd @@ -90,7 +90,7 @@ If you are having trouble downloading the ADT plugin after following the steps a If you are still unable to use Eclipse to download the ADT plugin, follow these steps to download and install the plugin from your computer:

              -
            1. Download the ADT zip file (do not unpack it). +
            2. Download the ADT zip file (do not unpack it).
            3. Follow steps 1 and 2 in the default install instructions (above).
            4. In Eclipse 3.3, click New Archive Site....
              In Eclipse 3.4, click Add Site..., then Archive... diff --git a/docs/html/guide/developing/tools/emulator.jd b/docs/html/guide/developing/tools/emulator.jd index dd367b708938e56a0784da0a8dee0ccc744fb196..769491b4f14bdffd97a5c4754105cb9529a6d8f5 100644 --- a/docs/html/guide/developing/tools/emulator.jd +++ b/docs/html/guide/developing/tools/emulator.jd @@ -812,7 +812,7 @@ in the default directory, or in a custom location (if you specified a path with userdata-qemu.img An image to which the emulator writes runtime user-data for a unique user. - Override using -data <;filepath>, where <filepath> is the + Override using -data <filepath>, where <filepath> is the path the image, relative to the current working directory. If you supply a filename only, the emulator looks for the file in the current working directory. If the file at <filepath> does not exist, the emulator creates an image from the default userdata.img, stores it under the name you diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs index 3e01172842d0eb53821226f676ce7beef60025aa..77d3522ce72aefec8c177f5babaee5d74da755c1 100644 --- a/docs/html/guide/guide_toc.cs +++ b/docs/html/guide/guide_toc.cs @@ -3,9 +3,9 @@
            5. Android Basics

            6. @@ -15,15 +15,16 @@
          -
        • Intents and Intent Filtering
        • +
        • Intents and Intent Filters
        • Data Storage
        • Content Providers
        • -
        • Notifications
        • +
        • Security and Permissions
        • -
        • The Manifest File
        • +
        • + + +
          • @@ -51,22 +76,22 @@
        • Audio and Video
        • -
        • - +
        • Location
        • -
        • - +
        • @@ -86,7 +111,7 @@
        • aapt
        • adb
        • activitycreator
        • -
        • ADT Plugin
        • +
        • aidl
        • ddms
        • dx
        • @@ -98,8 +123,8 @@
        • sqlite3
        • Traceview
        • -
        • Instrumentation
        • -
        • JUnit
        • + @@ -118,28 +143,34 @@
        • Designing for Performance
        • Designing for Responsiveness
        • Designing for Seamlessness
        • -
        • User Interface Guidelines
        • + - - -
        • Tutorials

          +
        • Tutorials and Sample Code

          +
        • + +
        • Appendix

          • Supported Media Formats
          • @@ -155,4 +186,4 @@ - \ No newline at end of file + diff --git a/docs/html/guide/index.jd b/docs/html/guide/index.jd index e7232356ff292847b525a6dda3d806063db9d4ac..ecbf97bd40d686ace5e2848f09880dce6b0c6662 100644 --- a/docs/html/guide/index.jd +++ b/docs/html/guide/index.jd @@ -1,62 +1,84 @@ -page.title=Get Started +page.title=The Developer's Guide @jd:body -

            Welcome to the Android Developer Guide! The Dev Guide is your conceptual and practical -introduction to developing applications for Android. With this guide, you're free to explore -which ever topics interest you, based on your goals and experience.

            - -

            If you're new to Android, you're probably wondering what it takes to -write a "Hello, World" application. So here it is:

            - -
            -package com.example.hello;
            -
            -import android.app.Activity;
            -import android.os.Bundle;
            -import android.widget.TextView;
            -
            -public class HelloWorld extends Activity {
            -
            -   public void onCreate(Bundle savedInstanceState) {
            -       super.onCreate(savedInstanceState);
            -       TextView tv = new TextView(this);
            -       tv.setText("Hello, World");
            -       setContentView(tv);
            -   }
            -
            -}
            -
            - -

            That's the only code you need to write!

            - -

            Not convinced?

            -

            If you're still shouting "Show me the code!" then take a look at -more Android code in the Hello World Samples.

            - -

            Ready to start?

            -

            If you're already convinced you want to develop on Android, -then we'll teach you how to build and run this "Hello, World" application in the -Hello World Introduction.

            - -

            Ready for more?

            -

            Once you've got your feet wet (or just want to skip to the heart of Android), the following -sections of the Dev Guide will educate you on the Android ins, outs, idioms and techniques:

            -
              -
            • Android Basics: - Learn more about what Android is, what it offers, and how your application fits in.
            • -
            • Framework Topics: - Become well versed in the practical matters of developing on Android — from drawing a UI, to storing data, - to drawing 3D graphics, and much more.
            • -
            • Developing: - Learn more about developing with IDEs, using Android develop/debug tools, and testing.
            • -
            • Publishing: - Learn how to get you application out there, for the world to enjoy!
            • -
            • Best Practices: - Get some recommendations on preferred techniques to write the best applications.
            • -
            • Tutorials: - Get help doing some of the basics, step by step.
            • -
            • Appendix: - Flotsam and jetsam. Find some of those spare nuggets of information.
            • -
            - -

            For more help, you should consider joining one or more of the Android discussion groups. See the Community for more information.

            +

            +Welcome to the Android Dev Guide! The Dev Guide is +a practical introduction to developing applications for Android. +It explores the concepts behind Android, the framework for +constructing an application, and the tools for developing, +testing, and publishing software for the platform. +

            + +

            +The Dev Guide holds most of the documentation for the Android +platform, except for reference material on the framework API. +For API specifications, go to the +Reference tab above. +

            + +

            +As you can see in the panel on the left, the Dev Guide is +divided into a handful of sections. They are: +

            + +

            +
            Android Basics
            +
            An initial orientation to Android — what it is, +what it offers, and how your application fits in.
            + +
            Framework Topics
            +
            Discussions of particular parts of the Android framework +and API. For an overview of the framework, begin with +Application +Fundamentals. Then explore other topics — from +designing a user interface and setting up resources to storing +data and using permissions — as needed.
            + +
            Developing
            +
            Directions for using Android's development and debugging tools, +and for testing the results.
            + +
            Publishing
            +
            Instructions on how to prepare your application for deployment +and how to publish it when it's ready.
            + +
            Best Practices
            +
            Recommendations on preferred techniques for writing +applications that perform efficiently and work well for the +user.
            + +
            Tutorials and Samples
            +
            Step-by-step tutorials and sample code demonstrating how +an Android application is constructed.
            + +
            Appendix
            +
            Reference information and specifications, as well as FAQs, +a glossary of terms, and other information.
            +
            + +

            +The first step in programming for Android is downloading the SDK +(software development kit). For instructions and information about +the kit, go to the SDK tab above. +

            + +

            +After you have the SDK, begin by looking over the Dev Guide. +If you want to start by getting a quick look at the code, the short +Hello World +tutorial walks you through a standard "Hello, World" application as +it would be written for the Android platform. The +Application +Fundamentals document is a good place to start for an +understanding of the application framework. +

            + + +

            +For additional help, consider joining one or more of the Android +discussion groups. Go to the +Community tab above +for more information. +

            + +

            To return to this page later, just click the "Dev Guide" tab while any Dev Guide page is loaded.

            \ No newline at end of file diff --git a/docs/html/guide/practices/design/seamlessness.jd b/docs/html/guide/practices/design/seamlessness.jd index caf0d6a0b62184ae14cd3097bfc4b3ec65fd1f4f..a6c164192b33db382e2da3b55c96f111c0577f21 100644 --- a/docs/html/guide/practices/design/seamlessness.jd +++ b/docs/html/guide/practices/design/seamlessness.jd @@ -164,7 +164,7 @@ interface they've come to expect. When designing your UIs, you should try and avoid rolling your own as much as possible. Instead, use a Theme. You can override or extend those parts of the theme that you need to, but at least you're starting from the same UI base as all the other applications. For all -the details, read Applying Styles and Themes.

            +the details, read Applying Styles and Themes.

            Design Your UI to Work with Multiple Screen Resolutions

            @@ -208,7 +208,6 @@ option when starting the emulator.

            Don't Assume Touchscreen or Keyboard

            -Keyboad Different Keystrokes for Different Folks

            Android will support a variety of handset form-factors. That's a fancy way of saying that some Android devices will have full "QWERTY" keyboards, while @@ -220,8 +219,6 @@ about specific keyboard layouts -- unless, of course, you're really interested in restricting your application so that it can only be used on those devices.

            -

            Assume the Network is Slow

            -

            Don't Assume Touchscreen or Keyboard

            Do Conserve the Device Battery

            A mobile device isn't very mobile if it's constantly plugged into the diff --git a/docs/html/guide/publishing/app-signing.jd b/docs/html/guide/publishing/app-signing.jd index 1862b50f8fefd0bc093a4ce201df9a7909c29416..28c927aed29c5deaac5aa9f7cab08274eed6c6c6 100644 --- a/docs/html/guide/publishing/app-signing.jd +++ b/docs/html/guide/publishing/app-signing.jd @@ -94,7 +94,7 @@ you can run Keytool manually to generate your own keystore/key and then sign you application with Jarsigner.

          -

          Signing Strategies

          +

          Signing Strategies

          Some aspects of application signing may affect how you approach the development of your application, especially if you are planning to release multiple diff --git a/docs/html/guide/publishing/preparing.jd b/docs/html/guide/publishing/preparing.jd index 1f3c6243aaa2acfa6357ddacfa6abe4d0222dd5a..d355265efb68e92a9b33d7cee6745932e36a9792 100644 --- a/docs/html/guide/publishing/preparing.jd +++ b/docs/html/guide/publishing/preparing.jd @@ -18,9 +18,11 @@ page.title=Preparing to Publish: A Checklist

          Publishing an application means testing it, packaging it appropriately, and making it available to users of Android-powered mobile devices.

          -

          If you plan to publish your application for installation on Android-powered devices, -there are several things you need to do, to get your application ready. This document -the significant checkpoints for preparing your application for a successful release.

          +

          If you plan to publish your application for installation on +Android-powered devices, there are several things you need to do, to get +your application ready. This document highlights the significant +checkpoints for preparing your application for a successful release. +

          If you will publish your application on Android Market, please also see Publishing on Android Market @@ -67,7 +69,7 @@ testing classes and tools. You can use {@link android.app.Instrumentation Instrumentation} to run JUnit and other test cases, and you can use testing tools such as the UI/Application -Exerciser Monkey.

          +Exerciser Monkey.

          • To ensure that your application will run properly for users, you should make @@ -94,12 +96,12 @@ orientation changes.

          2. Consider adding an End User License Agreement in your -application

          +application

          To protect your person, organization, and intellectual property, you may want to provide an End User License Agreement (EULA) with your application. -

          3. Specify an icon and label in the application's manifest

          +

          3. Specify an icon and label in the application's manifest

          The icon and label that you specify in an application's manifest are important because they are displayed to users as your application's icon and @@ -114,7 +116,7 @@ display the icon and label to users.

          As regards the design of your icon, you should try to make it match as much as possible the style used by the built-in Android applications.

          -

          4. Turn off logging and debugging and clean up data/files

          +

          4. Turn off logging and debugging and clean up data/files

          For release, you should make sure that debug facilities are turned off and that debug and other unnecessary data/files are removed from your application @@ -129,9 +131,9 @@ application project.

        • code. -

          Before you do the final compile of your application

          +

          Before you do the final compile of your application

          -

          5. Version Your Application

          +

          5. Version your application

          Before you compile your application, you must make sure that you have defined a version number for your application, specifying an appropriate value for both @@ -147,9 +149,10 @@ increment both the android:versionCode and element in the application's manifest file, using appropriate values.

          For detailed information about how to define version information for your -application, see Versioning Your Applications.

          +application, see Versioning +Your Applications.

          -

          6. Obtain a suitable cryptographic key

          +

          6. Obtain a suitable cryptographic key

          If you have read and followed all of the preparation steps up to this point, your application is compiled and ready for signing. Inside the .apk, the @@ -158,7 +161,8 @@ private data, as described above.

          Before you sign your application, you need to make sure that you have a suitable private key. For complete information about how to obtain (or generate) -a private key, see Obtaining a Private Key.

          +a private key, see +Obtaining a Suitable Private Key.

          Once you have obtained (or generated) a suitable private key, you will use it to:

          @@ -166,20 +170,18 @@ to:

          • Register for a Maps API Key (see below), if your application uses MapView elements.
          • -
          • Sign your application for release
          • +
          • Sign your application for release, later in the preparation process
          -

          7. Register for a Maps API Key, if your application is using MapView elements

          -

          Android applications are written in the Java programming language. -The compiled Java code — along with data and -resource files required by the application and a manifest describing the -application — is bundled by the aapt tool into an Android package, -an archive file marked by an {@code .apk} suffix. This file is the vehicle -for distributing the application and installing it on mobile devices; it's -the file users download to their devices. All the code in a single -{@code .apk} file is considered to be one application. +The compiled Java code — along with any data and resource +files required by the application — is bundled by the +aapt +tool into an Android package, an archive file +marked by an {@code .apk} suffix. This file is the vehicle +for distributing the application and installing it on mobile devices; +it's the file users download to their devices. All the code in a +single {@code .apk} file is considered to be one application.

          @@ -76,7 +85,7 @@ in the same Linux process, sharing the same VM.

          -

          Application Components

          +

          Application Components

          A central feature of Android is that one application can make use of elements @@ -125,24 +134,31 @@ current activity start the next one. Each activity is given a default window to draw in. Typically, the window fills the screen, but it might be smaller than the screen and float on top of other windows. An activity can also make use of additional windows — -for example, a window that presents users with vital information when they -select a particular item on-screen, or a pop-up dialog that calls for a user -response in the midst of the activity. +for example, a pop-up dialog that calls for a user response in the midst of +the activity, or a window that presents users with vital information when they +select a particular item on-screen.

          The visual content of the window is provided by a hierarchy of views — objects derived from the base {@link android.view.View} class. Each view -draws in a particular rectangular space within the window and responds to user -actions directed at that space. Android has a number of ready-made views that -you can use — including buttons, text fields, scroll bars, menu items, -check boxes, and more. A view hierarchy is placed within the activity's -window by the {@link android.app.Activity#setContentView -Activity.setContentView()} method. The content view -is the View object at the root of the hierarchy. -(See Views and Layout -for more information on views and the heirarchy.) -

          +controls a particular rectangular space within the window. Parent views +contain and organize the layout of their children. Leaf views (those at the +bottom of the hierarchy) draw in the rectangles they control and respond to +user actions directed at that space. Thus, views are where the activity's +interaction with the user takes place. For example, a view might display +a small image and initiate an action when the user taps that image. Android +has a number of ready-made views that you can use — including buttons, +text fields, scroll bars, menu items, check boxes, and more. +

          + +

          +A view hierarchy is placed within an activity's window by the +{@link android.app.Activity#setContentView Activity.setContentView()} +method. The content view is the View object at the root of the hierarchy. +(See the separate User Interface +document for more information on views and the hierarchy.) +

          Services
          A service doesn't have a visual user interface, but rather runs in @@ -152,13 +168,13 @@ data over the network or calculate something and provide the result to activitie that need it. Each service extends the {@link android.app.Service} base class.

          -A good example is a media player playing songs from a play list. The player +A prime example is a media player playing songs from a play list. The player application would probably have one or more activities that allow the user to choose songs and start playing them. However, the music playback itself would not be handled by an activity because users will expect the music to keep playing even after they leave the player and begin something different. To keep the music going, the media player activity could start a service to run -in the background. The system will then keep the music playback service running +in the background. The system would then keep the music playback service running even after the activity that started it leaves the screen.

          @@ -180,8 +196,10 @@ user interface, they often spawn another thread for time-consuming tasks
          A broadcast receiver is a component that does nothing but receive and react to broadcast announcements. Many broadcasts originate in system code — for example, announcements that the timezone has changed, -that the battery is low, that the keyboard has been exposed, or that the user -changed a language preference. +that the battery is low, that a picture has been taken, or that the user +changed a language preference. Applications can also initiate broadcasts +— for example, to let other applications know that some data has been +downloaded to the device and is available for them to use.

          An application can have any number of broadcast receivers to respond to any @@ -227,19 +245,19 @@ is available, creating the instance if necessary.

          -

          Activating components: intents

          +

          Activating components: intents

          Content providers are activated when they're targeted by a request from a ContentResolver. The other three components — activities, services, and broadcast receivers — are activated by asynchronous messages called intents. An intent is an {@link android.content.Intent} -object that holds the content of the message. Among other things, it names -the action an activity or service is being requested to take and specifies -the URI of the data to act on. For broadcast receivers, it names the -action being announced. For example, it might convey a request for +object that holds the content of the message. For activities and services, +it names the action being requested and specifies the URI of the data to +act on, among other things. For example, it might convey a request for an activity to present an image to the user or let the user edit some -text. Or it might announce to interested broadcast receivers that the +text. For broadcast receivers, the Intent object names the action being +announced. For example, it might announce to interested parties that the camera button has been pressed.

          @@ -281,13 +299,19 @@ onStart()} method and passes it the Intent object.

          Similarly, an intent can be passed to {@link android.content.Context#bindService Context.bindService()} to establish an ongoing connection between the calling component and a -target service. It initiates the service if it's not already running. -The service receives the Intent object in +target service. The service receives the Intent object in an {@link android.app.Service#onBind onBind()} call. -For example, an activity might establish a connection with the music -playback service mentioned earlier so that it could provide the user -with an interface for controlling the playback. The activity would -call {@code bindService()} to set up that connection. +(If the service is not already running, {@code bindService()} can +optionally start it.) For example, an activity might establish a connection +with the music playback service mentioned earlier so that it can provide +the user with the means (a user interface) for controlling the playback. +The activity would call {@code bindService()} to set up that connection, +and then call methods defined by the service to affect the playback. +

          + +

          +A later section, Remote procedure calls, has more details +about binding to a service.

          @@ -304,12 +328,49 @@ android.content.BroadcastReceiver#onReceive onReceive()} methods.

          -For more on intent messages, see the separate article, Intents +For more on intent messages, see the separate article, +Intents and Intent Filters. +

          + + +

          Shutting down components

          +

          +A content provider is active only while it's responding to a request from +a ContentResolver. And a broadcast receiver is active only while it's +responding to a broadcast message. So there's no need to explicitly shut +down these components. +

          + +

          +Activities, on the other hand, provide the user interface. They're +in a long-running conversation with the user and may remain active, +even when idle, as long as the conversation continues. Similarly, services +may also remain running for a long time. So Android has methods to shut +down activities and services in an orderly way: +

          -

          The manifest file

          +
            +
          • An activity can be shut down by calling its +{@link android.app.Activity#finish finish()} method. One activity can +shut down another activity (one it started with {@code startActivityForResult()}) by +calling {@link android.app.Activity#finishActivity finishActivity()}.
          • + +
          • A service can be stopped by calling its +{@link android.app.Service#stopSelf stopSelf()} method, or by calling +{@link android.content.Context#stopService Context.stopService()}.
          • +
          + +

          +Components might also be shut down by the system when they are no longer being +used or when Android must reclaim memory for more active components. A later +section, Component Lifecycles, discusses this +possibility and its ramifications in more detail. +

          + + +

          The manifest file

          Before Android can start an application component, it must learn that @@ -341,11 +402,12 @@ components. For example, an activity might be declared as follows: </activity> . . . </application> -</manifest> +</manifest>

          -The {@code name} attribute of the {@code <activity>} element -names the {@link android.app.Activity} subclass that implements the +The {@code name} attribute of the +<activity> +element names the {@link android.app.Activity} subclass that implements the activity. The {@code icon} and {@code label} attributes point to resource files containing an icon and label that can be displayed to users to represent the activity. @@ -353,24 +415,28 @@ to users to represent the activity.

          The other components are declared in a similar way — -{@code <service>} elements for services, {@code <receiver>} -elements for broadcast receivers, and {@code <provider>} elements -for content providers. Activities, services, and content providers that -are not declared in the manifest are not visible to the system and are -consequently never run. Broadcast receivers can be declared in the -manifest, or they can be created dynamically in code (as -{@link android.content.BroadcastReceiver} objects) -and registered with the system by calling {@link -android.content.Context#registerReceiver Context.registerReceiver()}. +<service> +elements for services, +<receiver> +elements for broadcast receivers, and +<provider> +elements for content providers. Activities, services, and content providers +that are not declared in the manifest are not visible to the system and are +consequently never run. However, broadcast receivers can either be +declared in the manifest, or they can be created dynamically in code +(as {@link android.content.BroadcastReceiver} objects) +and registered with the system by calling +{@link android.content.Context#registerReceiver Context.registerReceiver()}.

          For more on how to structure a manifest file for your application, see -The Manifest File. +The +AndroidManifest.xml File.

          -

          Intent filters

          +

          Intent filters

          An Intent object can explicitly name a target component. If it does, @@ -404,7 +470,7 @@ two intent filters to the activity: </activity> . . . </application> -</manifest> +</manifest>

          The first filter in the example — the combination of the action @@ -442,7 +508,7 @@ and Intent Filters.

          -

          Activities and Tasks

          +

          Activities and Tasks

          As noted earlier, one activity can start another, including one defined @@ -467,14 +533,14 @@ the one that is the focus for user actions. When one activity starts another, the new activity is pushed on the stack; it becomes the running activity. The previous activity remains in the stack. When the user presses the BACK key, the current activity is popped from the stack, and the previous one resumes as -the running activity. Activities in the stack are never rearranged, only -pushed and popped. +the running activity.

          The stack contains objects, so if a task has more than one instance of the same Activity subclass open — multiple map viewers, for example — the -stack has a separate entry for each instance. +stack has a separate entry for each instance. Activities in the stack are never +rearranged, only pushed and popped.

          @@ -505,7 +571,8 @@ The behavior just described is the default behavior for activities and tasks. But there are ways to modify almost all aspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that -started the activity and attributes set in the activity's {@code <activity>} +started the activity and attributes set in the activity's +<activity> element in the manifest. Both requester and respondent have a say in what happens.

          @@ -529,19 +596,19 @@ The principal {@code <activity>} attributes are:

          The following sections describe what some of these flags and attributes do, -and how they interact. +how they interact, and what considerations should govern their use.

          -

          Affinities and new tasks

          +

          Affinities and new tasks

          By default, all the activities in an application have an affinity for each other — that is, there's a preference for them all to belong to the same task. However, an individual affinity can be set for each activity -with the {@code taskAffinity} attribute. Activities defined in different -applications can share an affinity, or activities defined in the same -application can be assigned different affinities. +with the {@code taskAffinity} attribute of the {@code <activity>} element. +Activities defined in different applications can share an affinity, or activities +defined in the same application can be assigned different affinities. The affinity comes into play in two circumstances: When the Intent object that launches an activity contains the {@code FLAG_ACTIVITY_NEW_TASK} flag, and when an activity has its {@code allowTaskReparenting} attribute set @@ -550,26 +617,28 @@ to "{@code true}".

          The {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag
          -
          As mentioned earlier, a new activity is, by default, launched into +
          As described earlier, a new activity is, by default, launched into the task of the activity that called {@code startActivity()}. It's pushed onto the same stack as the caller. However, if the Intent object passed to {@code startActivity()} contains the {@code FLAG_ACTIVITY_NEW_TASK} flag, the system looks for a different task to house the new activity. Often, as the name of the flag implies, it's a new task. However, it -doesn't have to be. If there's an existing task with the same affinity -as the new activity, the activity is launched into that task. If not, -it begins a new task.
          - -
          The {@code allowTaskReparenting} attribute
          -
          If an activity has its {@code allowTaskReparenting} attribute is -set to "{@code true}", it can move from the task it starts in to the task +doesn't have to be. If there's already an existing task with the same +affinity as the new activity, the activity is launched into that task. If +not, it begins a new task.
          + +
          The allowTaskReparenting +attribute
          +
          If an activity has its {@code allowTaskReparenting} attribute set +to "{@code true}", it can move from the task it starts in to the task it has an affinity for when that task comes to the fore. For example, suppose that an activity that reports weather conditions in selected cities is defined as part of a travel application. It has the same affinity as other activities in the same application (the default affinity) and it allows reparenting. One of your activities starts the weather reporter, so it initially belongs to the same task as -your activity. However, when the travel application, next comes forward, +your activity. However, when the travel application next comes forward, the weather reporter will be reassigned to and displayed with that task.
          @@ -580,65 +649,116 @@ affinities to the activities associated with each of them.

          -

          Launch modes

          +

          Launch modes

          There are four different launch modes that can be assigned to an {@code -<activity>} element's {@code launchMode} attribute: +<activity>} element's +launchMode +attribute:

          -

          "{@code standard}" (the default value) +

          "{@code standard}" (the default mode)
          "{@code singleTop}"
          "{@code singleTask}"
          "{@code singleInstance}"

          -The launch mode determines three things: +The modes differ from each other on these four points:

            -
          • Whether the activity can belong to a task that includes other -activities. The answer is yes for all the modes except -"{@code singleInstance}". A "{@code singleInstance}" activity is always -the only activity in its task. If it tries to launch another activity, -that activity is assigned to a different task — as if {@code -FLAG_ACTIVITY_NEW_TASK} was in the intent.
          • - -
          • Whether the activity always begins a task. For "{@code singleTask}" -and "{@code singleInstance}" the answer is yes. They mark activities that -can only be the root activities of a task; they define a task. In contrast, -"{@code standard}" and "{@code singleTop}" activities can belong to any task. + +

          • Which task will hold the activity that responds to the intent. +For the "{@code standard}" and "{@code singleTop}" modes, it's the task that +originated the intent (and called +{@link android.content.Context#startActivity startActivity()}) +— unless the Intent object contains the +{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag. +In that case, a different task is chosen as described in the previous +section, Affinities and new tasks. + +

            +In contrast, the "{@code singleTask}" and "{@code singleInstance}" modes mark +activities that are always at the root of a task. They define a task; they're +never launched into another task. +

            + +
          • Whether there can be multiple instances of the activity. +A "{@code standard}" or "{@code singleTop}" activity can be instantiated +many times. They can belong to multiple tasks, and a given task can have +multiple instances of the same activity. +

            + +

            +In contrast, "{@code singleTask}" and "{@code singleInstance}" activities +are limited to just one instance. Since these activities are at the root +of a task, this limitation means that there is never more than a single +instance of the task on the device at one time. +

            + +
          • Whether the instance can have other activities in its task. +A "{@code singleInstance}" activity stands alone as the only activity in its +task. If it starts another activity, that activity will be launched into a +different task regardless of its launch mode — as if {@code +FLAG_ACTIVITY_NEW_TASK} was in the intent. In all other respects, the +"{@code singleInstance}" mode is identical to "{@code singleTask}".

            + +

            +The other three modes permit multiple activities to belong to the task. +A "{@code singleTask}" activity will always be the root activity of the task, +but it can start other activities that will be assigned to its +task. Instances of "{@code standard}" and "{@code singleTop}" +activities can appear anywhere in a stack.

          • -
          • Whether an existing instance of the activity can handle new -intents. The answer is yes for all the modes except "{@code standard}". -Existing "{@code singleTask}" and "{@code singleInstance}" activities -handle all new intents that come their way; a new instance is never -created. In the case of "{@code singleTask}", all other activities in -the task are popped from the stack, so that the root "{@code singleTask}" -activity is at the top and in position to respond to the intent. +

          • Whether a new instance of the class will be launched +to handle a new intent. For the default "{@code standard}" mode, a +new instance is created to respond to every new intent. Each instance +handles just one intent. For the "{@code singleTop}" mode, an existing +instance of the class is re-used to handle a new intent if it resides +at the top of the activity stack of the target task. If it does not +reside at the top, it is not re-used. Instead, a new instance +is created for the new intent and pushed on the stack. + +

            +For example, suppose a task's activity stack consists of root activity A with +activities B, C, and D on top in that order, so the stack is A-B-C-D. An intent +arrives for an activity of type D. If D has the default "{@code standard}" launch +mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. +However, if D's launch mode is "{@code singleTop}", the existing instance is +expected to handle the new intent (since it's at the top of the stack) and the +stack remains A-B-C-D.

            -If a "{@code singleTop}" activity is at the -top of its stack, that object is expected to handle any new intents. -However, if it's farther down the stack, a new instance is created for -the intent and pushed on the stack. +If, on the other hand, the arriving intent is for an activity of type B, a new +instance of B would be launched no matter whether B's mode is "{@code standard}" +or "{@code singleTop}" (since B is not at the top of the stack), so the resulting +stack would be A-B-C-D-B.

            -In contrast, a new instance of a "{@code standard}" activity is always -created for each new intent. +As noted above, there's never more than one instance of a "{@code singleTask}" +or "{@code singleInstance}" activity, so that instance is expected to handle +all new intents. A "{@code singleInstance}" activity is always at the top of +the stack (since it is the only activity in the task), so it is always in +position to handle the intent. However, a "{@code singleTask}" activity may +or may not have other activities above it in the stack. If it does, it is not +in position to handle the intent, and the intent is dropped. (Even though the +intent is dropped, its arrival would have caused the task to come to the +foreground, where it would remain.)

          • +

          When an existing activity is asked to handle a new intent, the Intent -object is passed to the activity in an {@link android.app.Activity#onNewIntent -onNewIntent()} call. (The intent object that originally started the -activity can be retrieved by calling -{@link android.app.Activity#getIntent getIntent()}.) +object is passed to the activity in an +{@link android.app.Activity#onNewIntent onNewIntent()} call. +(The intent object that originally started the activity can be retrieved by +calling {@link android.app.Activity#getIntent getIntent()}.)

          @@ -650,13 +770,13 @@ return to what that instance was doing before the new intent arrived.

          -For more on launch modes, see -The -AndroidManifest.xml File +For more on launch modes, see the description of the +<activity> +element.

          -

          Clearing the stack

          +

          Clearing the stack

          If the user leaves a task for a long time, the system clears the task of all @@ -673,24 +793,30 @@ control this behavior and modify it:

          -
          The {@code alwaysRetainTaskState} attribute
          +
          The alwaysRetainTaskState +attribute
          If this attribute is set to "{@code true}" in the root activity of a task, the default behavior just described does not happen. -Activities are retained in the stack even after a long period.
          +The task retains all activities in its stack even after a long period.
          -
          The {@code clearTaskOnLaunch} attribute
          +
          The clearTaskOnLaunch +attribute
          If this attribute is set to "{@code true}" in the root activity of a task, the stack is cleared down to the root activity whenever the user leaves the task and returns to it. In other words, it's the polar opposite of {@code alwaysRetainTaskState}. The user always returns to the task in its initial state, even after a momentary absence.
          -
          The {@code finishOnTaskLaunch} attribute
          +
          The finishOnTaskLaunch +attribute
          This attribute is like {@code clearTaskOnLaunch}, but it operates on a single activity, not an entire task. And it can cause any activity to go away, including the root activity. When it's set to "{@code true}", the activity remains part of the task only for the current session. If the user -leaves and then relaunches the task, it no longer is present.
          +leaves and then returns to the task, it no longer is present.

          @@ -700,7 +826,11 @@ android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_CLEAR_TOP} flag, and the target task already has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away so that it stands at the top of the stack and can respond -to the intent. +to the intent. +If the launch mode of the designated activity is "{@code standard}", it too +will be removed from the stack, and a new instance will be launched to handle +the incoming intent. That's because a new instance is always created for +a new intent when the launch mode is "{@code standard}".

          @@ -711,7 +841,7 @@ a position where it can respond to the intent.

          -

          Starting tasks

          +

          Starting tasks

          An activity is set up as the entry point for a task by giving it @@ -731,7 +861,7 @@ and then come back to it later. For this reason, the two launch modes that mark activities as always initiating a task, "{@code singleTask}" and "{@code singleInstance}", should be used only when the activity has a {@code MAIN} and {@code LAUNCHER} filter. -Imagine, for example, what could happen if the filter is missing. +Imagine, for example, what could happen if the filter is missing: An intent launches a "{@code singleTask}" activity, initiating a new task, and the user spends some time working in that task. The user then presses the HOME key. The task is now ordered behind and obscured by the home @@ -760,7 +890,7 @@ See Clearing the stack, earlier.

          -

          Processes and Threads

          +

          Processes and Threads

          When the first of an application's components needs to be run, Android @@ -769,12 +899,15 @@ all components of the application run in that process and thread.

          -However, you can arrange for components to run in other processes as well as -spawn additional threads: +However, you can arrange for components to run in other processes, and you +can spawn additional threads for any process.

          -
            -
          • The process where a component runs is controlled by the manifest file. + +

            Processes

            + +

            +The process where a component runs is controlled by the manifest file. The component elements — {@code <activity>}, {@code <service>}, {@code <receiver>}, and {@code <provider>} — each have a {@code process} attribute that can specify a process @@ -784,26 +917,27 @@ while others do not. They can also be set so that components of different applications run in the same process — provided that the applications share the same Linux user ID and are signed by the same authorities. The {@code <application>} element also has a {@code process} attribute, -for setting a default value that applies to all components.

          • - -
          • Threads are created in code using standard Java {@link java.lang.Thread} -objects. Android provides a number of convenience classes for managing threads -— {@link android.os.Looper} for running a message loop within a thread, -{@link android.os.Handler} for processing messages, and -{@link android.os.HandlerThread} for setting up a thread with a message loop.

            +for setting a default value that applies to all components. +

            -Even though you may confine your application to a single process, there may be -times when you will need to spawn a thread to do some background work. Since the -user interface must always be quick to respond to user actions, the -thread that hosts an activity should not also host time-consuming operations like -network downloads, or anything else that may not be completed quickly. -

          • -
          +All components are instantiated in the main thread of the specified +process, and system calls to the component are dispatched from that +thread. Separate threads are not created for each instance. Consequently, +methods that respond to those calls — methods like +{@link android.view.View#onKeyDown View.onKeyDown()} that report +user actions and the lifecycle notifications discussed later in the +Component Lifecycles section — always run in the +main thread of the process. This means +that no component should perform long or blocking operations (such as networking +operations or computation loops) when called by the system, since this will block +any other components also in the process. You can spawn separate threads for +long operations, as discussed under Threads, next. +

          Android may decide to shut down a process at some point, when memory is -low and required by other applications that are more immediately serving +low and required by other processes that are more immediately serving the user. Application components running in the process are consequently destroyed. A process is restarted for those components when there's again work for them to do. @@ -816,17 +950,176 @@ with activities that are no longer visible on screen than a process with visible activities. The decision whether to terminate a process, therefore, depends on the state of the components running in that process. Those states are the subject of -the next section, Lifecycles. +a later section, Component Lifecycles. +

          + + +

          Threads

          + +

          +Even though you may confine your application to a single process, there will +likely be times when you will need to spawn a thread to do some background +work. Since the user interface must always be quick to respond to user actions, +the thread that hosts an activity should not also host time-consuming operations +like network downloads. Anything that may not be completed quickly should be +assigned to a different thread. +

          + +

          +Threads are created in code using standard Java {@link java.lang.Thread} +objects. Android provides a number of convenience classes for managing +threads — {@link android.os.Looper} for running a message loop within +a thread, {@link android.os.Handler} for processing messages, and +{@link android.os.HandlerThread} for setting up a thread with a message loop.

          -

          Lifecycles

          +

          Remote procedure calls

          + +

          +Android has a lightweight mechanism for remote procedure calls (RPCs) +— where a method is called locally, but executed remotely (in another +process), with any result returned back to the caller. +This entails decomposing the method call and all its attendant data to a +level the operating system can understand, transmitting it from the local +process and address space to the remote process and address space, and +reassembling and reenacting the call there. Return values have to be +transmitted in the opposite direction. Android provides all the code +to do that work, so that you can concentrate on defining and implementing +the RPC interface itself. +

          + +

          +An RPC interface can include only methods. +All methods are executed synchronously (the local method blocks until the +remote method finishes), even if there is no return value. +

          + +

          +In brief, the mechanism works as follows: You'd begin by declaring the +RPC interface you want to implement using a simple IDL (interface definition +language). From that declaration, the +aidl +tool generates a Java interface definition that must be made available to +both the local and the remote process. It contains two inner class, as shown +in the following diagram: +

          + +

          +RPC mechanism. +

          + +

          +The inner classes have all the code needed to administer remote procedure +calls for the interface you declared with the IDL. +Both inner classes implement the {@link android.os.IBinder} +interface. One of them is used locally and internally by the system; +the code you write can ignore it. +The other, called Stub, extends the {@link android.os.Binder} +class. In addition to internal code for effectuating the IPC calls, it +contains declarations for the methods in the RPC interface you declared. +You would subclass Stub to implement those methods, as indicated in the +diagram. +

          + +

          +Typically, the remote process would be managed by a service (because a +service can inform the system about the process and its connections to +other processes). It would have both the interface file generated by +the {@code aidl} tool and the Stub subclass implementing the +RPC methods. Clients of the service would have only the interface file +generated by the {@code aidl} tool. +

          + +

          +Here's how a connection between a service and its clients is set up: +

          + +
            +
          • Clients of the service (on the local side) would implement +{@link android.content.ServiceConnection#onServiceConnected +onServiceConnected()} and +{@link android.content.ServiceConnection#onServiceDisconnected +onServiceDisconnected()} methods so they can be notified +when a successful connection to the remote service is established, and +when it goes away. They would then call +{@link android.content.Context#bindService bindService()} +to set up the connection. +
          • + +
          • +The service's {@link android.app.Service#onBind onBind()} +method would be implemented to either accept or reject the connection, +depending on the intent it receives (the intent passed to +{@code bindService()}). If the connection is accepted, it returns +an instance of the Stub subclass. +
          • + +
          • If the service accepts the connection, Android calls the +client's {@code onServiceConnected()} method and passes it an IBinder +object, a proxy for the Stub subclass managed by the service. Through +the proxy, the client can make calls on the remote service. +
          • +
          + +

          +This brief description omits some details of the RPC mechanism. For more +information, see +Designing a Remote +Interface Using AIDL and the {@link android.os.IBinder IBinder} class +description. +

          + + +

          Thread-safe methods

          + +

          +In a few contexts, the methods you implement may be called from more +than one thread, and therefore must be written to be thread-safe. +

          + +

          +This is primarily true for methods that can be called remotely — +as in the RPC mechanism discussed in the previous section. +When a call on a method implemented in an IBinder object originates +in the same process as the IBinder, the method is executed in the +caller's thread. However, when the call originates in another process, +the method is executed in a thread chosen from a pool of threads that +Android maintains in the same process as the IBinder; it's not executed +in the main thread of the process. For example, whereas a service's +{@code onBind()} method would be called from the main thread of the +service's process, methods implemented in the object that {@code onBind()} +returns (for example, a Stub subclass that implements RPC methods) would +be called from threads in the pool. +Since services can have more than one client, more than one pool thread +can engage the same IBinder method at the same time. IBinder methods +must, therefore, be implemented to be thread-safe. +

          + +

          +Similarly, a content provider can receive data requests that originate in +other processes. Although the ContentResolver and ContentProvider classes +hide the details of how the interprocess communication is managed, +ContentProvider methods that respond to those requests — the methods +{@link android.content.ContentProvider#query query()}, +{@link android.content.ContentProvider#insert insert()}, +{@link android.content.ContentProvider#delete delete()}, +{@link android.content.ContentProvider#update update()}, and +{@link android.content.ContentProvider#getType getType()} +— are called from a pool of threads in the content provider's +process, not the main thread of the process. Since these methods +may be called from any number of threads at the same time, they too must +be implemented to be thread-safe. +

          + + +

          Component Lifecycles

          Application components have a lifecycle — a beginning when Android instantiates them to respond to intents through to an end when the instances are destroyed. In between, they may sometimes be active -or inactive, or, in the case of activities, visible to the user or +or inactive,or, in the case of activities, visible to the user or invisible. This section discusses the lifecycles of activities, services, and broadcast receivers — including the states that they can be in during their lifetimes, the methods that notify you of transitions @@ -835,7 +1128,7 @@ the process hosting them might be terminated and the instances destroyed.

          -

          Activity lifecycle

          +

          Activity lifecycle

          An activity has essentially three states:

          @@ -864,12 +1157,10 @@ method), or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

          - -

          Lifecycle methods

          -

          As an activity transitions from state to state, it is notified of the change by calls to the following protected methods: +

          {@code void onCreate(Bundle savedInstanceState)}
          {@code void onStart()} @@ -881,15 +1172,15 @@ by calls to the following protected methods:

          All of these methods are hooks that you can override to do appropriate work -when the state changes. -All activities must implement {@link android.app.Activity#onCreate -onCreate()} to do initial setup when the activity is first instantiated. +when the state changes. All activities must implement +{@link android.app.Activity#onCreate onCreate()} to do the +initial setup when the object is first instantiated. Many will also implement {@link android.app.Activity#onPause onPause()} to commit data changes and otherwise prepare to stop interacting with the user.

           
          - -
          - - - - - -
          -
          -

          Featured Developer App: BreadCrumbz

          -

          Amos Yoffe takes navigation to the next level with BreadCrumbz.

          -

          Learn more about this developer »

          -
          - -
          -
          - + - - - - - + @@ -79,16 +61,25 @@ page.title=Home - + + + + + +

          Download

          -

          Latest SDK

          -

          Download now

          +

          The Android SDK has the tools, sample code, and docs you need to create great apps.

          +

          Learn more »

           

          Market

          -
          -

          Android Market is an open service that will give developers the opportunity to distribute applications to handsets.

          +
          +

          Publish

          +

          Android Market is an open service that lets you distribute your apps to handsets.

          Learn more »

           

          Contribute

          -

          Create using our open source codebase and help us keep this project growing.

          +

          Android Open Source Project gives you access to the entire platform source.

          Learn more »

           
          +

          Watch

          + +

          More Android videos »

          +
          @@ -125,10 +116,10 @@ page.title=Home 'sdk': { 'layout':"imgLeft", 'icon':"sdk-small.png", - 'name':"SDK 1.0 r1", + 'name':"SDK 1.1 r1", 'img':"sdk-large.png", - 'title':"Android 1.0 SDK r1", - 'desc': "

          The first Android 1.0 SDK is available for download. This is the first release guaranteed to operate on the first Android devices. If you want to release an application for Android, you should be developing with this SDK.

          Download Android 1.0 SDK r1

          " + 'title':"Android 1.1 SDK r1", + 'desc': "

          A new Android SDK is available for download. The new SDK includes minor API changes, new UI localizations, bug fixes and some new application features.

          Download Android 1.1 SDK r1

          " }, 'mapskey': { @@ -137,7 +128,7 @@ page.title=Home 'name':"Maps API Key", 'img':"maps-large.png", 'title':"Maps API Key", - 'desc':"

          If you're writing an Android application that uses Google Maps (with MapView), you must register your application to obtain a Maps API Key. Without the key, your maps application will not work on Android devices. Obtaining a key requires just a couple of steps.

          Learn how to get a Maps API Key

          " + 'desc':"

          If you're writing an Android application that uses Google Maps (with MapView), you must register your application to obtain a Maps API Key. Without the key, your maps application will not work on Android devices. Obtaining a key requires just a couple of steps.

          Learn how to get a Maps API Key

          " }, 'market': { @@ -147,6 +138,15 @@ page.title=Home 'img':"market-large.png", 'title':"", 'desc': "

          Android Market helps you get your applications into the hands of users. The beta version of Market is now open and you can begin sharing your applications with users of the first Android-powered phone, the T-Mobile G1.

          Publish your Android app on Market »

          " + }, + + 'devphone': { + 'layout':"imgLeft", + 'icon':"devphone-small.png", + 'name':"Dev Phone 1", + 'img':"devphone-large.png", + 'title':"Android Dev Phone 1", + 'desc': "

          Run and debug your Android applications directly on this device. Modify and rebuild the Android operating system, and flash it onto the phone. The Android Dev Phone 1 is carrier independent, and available for purchase by any developer registered with Android Market.

          Learn more about the Android Dev Phone 1 »

          " } } diff --git a/docs/html/license.jd b/docs/html/license.jd new file mode 100644 index 0000000000000000000000000000000000000000..88932b60b5fc4d296265b6e1a040c857590f216b --- /dev/null +++ b/docs/html/license.jd @@ -0,0 +1,143 @@ +page.title=Content License +hide_license_footer=true +@jd:body + +
          +

          Content License

          + +

          For the purposes of licensing, the content of this site is divided +into two categories:

          +
            +
          • Documentation content, found under the "Dev Guide" and "Reference" + tabs, including both static content and content extracted from source + code modules, as well as sample code, and
          • +
          • All other site content
          • +
          + +

          The documentation content on this site is made available to +you as part of the Android Open +Source Project. This documentation, including any code shown in it, +is licensed under the Apache 2.0 +license, the preferred license for all parts of the of the Android +Open Source Project.

          + +

          Apache 2.0 is a commercial and open-source-friendly software +license. The majority of the Android platform and documentation is +licensed under the Apache 2.0 license. While the project strives to +adhere to the preferred license, there may be exceptions, such as for +documentation (code comments) extracted from a source code module that +is licensed under GPLv2 or other license. In those cases, the license +covering the source code module will apply to the documentation +extracted from it.

          + +

          All other content on this site, except the license documents themselves +and as otherwise noted, is licensed under the Creative Commons +Attribution 2.5 license.

          + +

          You may use the content of this site in any way that is consistent +with the specific license that applies to the content, as described +above. For content licensed under Creative Commons Attribution 2.5, we +ask that you give proper attribution.

          + + +

          Terms of Use

          + +

          We are pleased to license the Android documentation and sample code under +terms that encourage you to take, modify, reuse, re-purpose, and remix the +content as you see fit. Except as noted in the Restrictions section below, you +are free to use the documentation content in your own creations. For example, +you could quote the text in a book, cut-and-paste sections to your blog, record +it as an audiobook for the visually impaired, or even translate it.

          + + +

          Restrictions

          + +
            +
          • While the documentation itself is available to you under the Apache 2.0 +license, note that proprietary trademarks and brand features are not +included in that license.
          • + +
          • Google's trademarks and other brand features (including the +ANDROID stylized typeface logo) are not included in the license. +Please see +Guidelines for Third Party Use of Google Brand Features for +information about this usage.
          • + +
          • In some cases, a page may include content, such as an image, that is not +covered by the license. In that case, we will label the content that is not licensed.
          • + +
          • In addition, content linked from a page on this site is not covered +by the license unless specifically noted. For example, pages may link to videos or +slide decks that are not covered.
          • + +
          • The use of sample source code provided in the SDK or shown in this +documentation is subject to the conditions detailed in the SDK Terms and Conditions.
          • +
          + + +

          Attribution

          +

          +Proper attribution is required when you reuse or create modified +versions of content that appears on a page made available under the +terms of the Creative Commons Attribution license. On this site, the +requirement for attribution applies only to the non-documentation +content, as described earlier in this document. The complete +requirements for attribution can be found in section 4b of the + +Creative Commons legal code. +

          +

          + In practice we ask that you provide attribution to the Android Open + Source project to the best of the ability of the medium in which you + are producing the work. There are several typical ways in which this + might apply: +

          +

          Exact Reproductions

          +

          + If your online work exactly reproduces text or images from this + site, in whole or in part, please include a paragraph at the bottom + of your page that reads: +

          +
          + Portions of this page are reproduced from work created and shared by the Android Open Source Project + and used according to terms described in the Creative Commons + 2.5 Attribution License. + +
          +

          + Also, please link back to the original source page so that readers can + refer there for more information. +

          +

          Modified Versions

          +

          + If your online work shows modified text or images based on + the content from this site, please include a paragraph at the bottom of + your page that reads: +

          +
          + Portions of this page are modifications based on work created and shared by the Android Open + Source Project and used according to terms described in the Creative Commons + 2.5 Attribution License. +
          +

          + Again, please link back to the original source page so that readers can + refer there for more information. This is even more important when + the content has been modified. +

          +

          Other Media

          +

          + If you produce non-hypertext works, such as books, audio, or + video, we ask that you make a best effort to include a spoken or + written attribution in the spirit of the messages above. +

          + +
          + + diff --git a/docs/html/offline.jd b/docs/html/offline.jd new file mode 100644 index 0000000000000000000000000000000000000000..d41459b4d64c7170363cb3cf068040466d318e60 --- /dev/null +++ b/docs/html/offline.jd @@ -0,0 +1,36 @@ +home=true +page.title=Welcome +@jd:body + +
          + +

          Welcome to the Android SDK!

          + + + +

          If you've just downloaded the SDK, then continue with +Installing the Android SDK.

          + +

          If you're upgrading from a previously installed version, then refer to the +Upgrading guide.

          + +

          Once you've completed the SDK installation, you can start learning about +development on the Android framework by reading the Developer's Guide. The SDK package +also includes a wide variety of very helpful code samples.

          + +

          Please note that you are currently viewing a local, offline version of the +Android developer documentation. The offline documentation offers the same +content and features as the online documentation, but since the search +capability is network-based, it will not work while you are offline. +Autocompletion for API packages and classes, also offered from the search box, +is available both online and offline and loads the reference documentation for +the item you select.

          + +

          For the most current, fully searchable documentation, please visit

          + +

          +http://developer.android.com.

          + +
          diff --git a/docs/html/resources/bootcamp.pdf b/docs/html/resources/bootcamp.pdf deleted file mode 100644 index a817b96384f1ea9af79717f0ba7eca709e1693c2..0000000000000000000000000000000000000000 Binary files a/docs/html/resources/bootcamp.pdf and /dev/null differ diff --git a/docs/html/roadmap.jd b/docs/html/roadmap.jd deleted file mode 100644 index 11986382a086e5364ac0e44f80cf769777834ded..0000000000000000000000000000000000000000 --- a/docs/html/roadmap.jd +++ /dev/null @@ -1,120 +0,0 @@ -page.title=Developer Roadmap -@jd:body -

          Android Developer Roadmap

          -

          Introduction

          -

          -On 12 November, 2007, we made available the first early look at the Android -SDK to give developers an opportunity to explore Android and build -applications for the Android Developer Challenge. That was followed by the -"M5" early look build. -

          -Since then, we've been hard at work with our partners preparing the first -device for launch and finalizing the APIs and platform. The developer -feedback we received via the "early look" SDKs has been extremely valuable in -that process. This Roadmap outlines our plans for -the coming months, and lets you know what to expect as we near device -availability. -

          -This is the top-level Roadmap. Individual components of Android (such as -the Dalvik virtual machine, the Android Developer Tools, and so on) will have -their own roadmaps, once we complete the source code release. Those roadmaps -will be linked to this page, as they become available. -

          -

          Timeline

          -

          -To orient yourself, consult this brief timeline. Read on for details on these -milestones. -

            -
          • 12 November, 2007 - "Early Look" SDK released
          • -
          • January to August, 2008 - Android Developer Challenge I
          • -
          • 18 August, 2008 - Android 0.9 SDK beta released
          • -
          • 28 August, 2008 - Android Market introduced
          • -
          • 23 September, 2008 - Android 1.0 SDK Release 1 available (first actual -1.0-compatible SDK)
          • -
          • 22 October, 2008 - Android 1.0 devices available at retail
          • -
          • Q4 2008 - Source code released
          • -
          • Q4 2008 - Key Announcement on Android Developer Challenge II
          • -
          -

          SDK Naming and Compatibility

          -

          -Before we dive into details, here is a quick note on how we name SDKs. -

          -We've adopted the following naming convention for Android SDKs: - "Android <Platform> SDK, release <Release>" -

          -The downloadable file names for the SDKs will have this naming convention: - "android-sdk-<Host-OS>-<Platform>_r<Release>.zip" -

          -The "<Platform>" refers to the version of the Android platform with which the -SDK is compatible. For instance, an SDK that can be used to build -applications that will run on Android 1.0 is considered to be an "Android 1.0 -SDK". However, since we do expect to release bug fixes and enhancements for -the various tools included in the SDK (such as the emulator, Eclipse plugin, -DDMS, and so on) we need to distinguish between releases of the SDK that can -be used to build for the same Android platform. That's what we will use the -"<Release>" for. -

          -For example, the first SDK that is compatible with Android 1.0 is named -"Android 1.0 SDK, release 1", and will have file names such as -"android-sdk-windows-1.0_r1.zip". In the future, after we release a -hypothetical Android 2.0 platform version, you might see an SDK named "Android -2.0 SDK, release 3", which would refer to the third released SDK compatible -with Android 2.0. -

          -

          Details of Key Events

          -

          Ongoing SDK Releases

          -

          -The SDK consists of two general pieces: a version of the Android platform -itself (that runs in the emulator), and the accompanying developer tools that -surround it. This means that when we ship SDK releases, all releases within a -given series (such as all the SDKs for Android 1.0) will consist of -essentially the same platform image, but with different, updated tools. -

          -In August, we released Android 0.9 SDK, beta. The Android -platform image was not quite 1.0-final (which is why we identified it as 0.9), -and the tools were not yet final (which is why we referred to it as -beta.)

          - -

          For the SDK that includes the Android 1.0 platform and updated tools, -we've dropped the beta labeling and released "Android 1.0 SDK, release -1". Applications developed on this SDK version will be compatible with -devices that run the Android 1.0 platform.

          - -

          Device Availability

          -

          The first Android-powered device, the T-Mobile G1, was announced on 23 September, -2008. To learn more about the T-Mobile G1, see the T-Mobile G1 site. - -

          Other partners will be releasing Android-powered devices in the future. -We will update this space with more specific information about each device -release, as it becomes -available.

          - -

          Source Code Release

          -

          -We are currently in the process of preparing for the release of the source -code. This includes a few key tasks: -

            -
          • Selection of hosting infrastructure
          • -
          • Updating the build infrastructure for general use
          • -
          • Creation of a project governance framework
          • -
          • Final examination of source code for release approval
          • -
          • Physical upload and release packaging of the source code
          • -

          -This work is already under way, but since Android contains some 8 million -lines of code, it's a lengthy process. We expect this process to conclude -(and source code to be released) in Q4 of 2008. -

          -

          Android Developer Challenge II

          -

          -When Android was announced on 5 November, 2007, Google also announced a $10 -million Android Developer Challenge, split into two separate $5 million -events. The first Android Developer Challenge ran from January 2008 through -August 2008, and was intended to give developers an opportunity to explore -their ideas using the early look SDK and build prototype applications -- to -"get in on the ground floor." The second Challenge will give developers a -chance to build polished applications once hardware is available. -

          -We'll be making some interesting announcements regarding ADC II soon, in Q3 or -Q4. -

          diff --git a/docs/html/robots.txt b/docs/html/robots.txt new file mode 100644 index 0000000000000000000000000000000000000000..a8729444413854ba0c0bb026f6911d477eaf02c6 --- /dev/null +++ b/docs/html/robots.txt @@ -0,0 +1,6 @@ +User-Agent: * +Allow: / +Disallow: /gae_shell/ +Disallow: /assets/ +Disallow: /images/ +Sitemap: http://developer.android.com/sitemap.txt diff --git a/docs/html/samples/index.jd b/docs/html/samples/index.jd index 6219f9abd60097187e95c5bd504ff6650ed5e736..c5c0b7132eb9bcd9f8427cba8489c97c5b52a94a 100644 --- a/docs/html/samples/index.jd +++ b/docs/html/samples/index.jd @@ -17,7 +17,7 @@ page.onlyfortemplate=codesite

          To run these samples, you should import them into -Eclipse or use +href="{@docRoot}guide/developing/eclipse-adt.html#creatingaproject">import them into +Eclipse or use activitycreator.py, as described in the Installing the SDK.

          +href="{@docRoot}sdk/1.1_r1/installing.html">Installing the SDK.

          diff --git a/docs/html/sdk/1.0_r1/RELEASENOTES.jd b/docs/html/sdk/1.0_r1/RELEASENOTES.jd deleted file mode 100644 index c6a38bb9179f76ea26151ebeff003831fbccb429..0000000000000000000000000000000000000000 --- a/docs/html/sdk/1.0_r1/RELEASENOTES.jd +++ /dev/null @@ -1,100 +0,0 @@ -page.title=Release Notes, 1.0 r1 -@jd:body - - -

          This SDK release is the first to include the Android 1.0 platform and application API. Applications developed on this SDK will be compatible with mobile devices running the Android 1.0 platform, when such devices are available.

          - -

          This release includes mainly bug fixes, although some smaller features were added. The Android 1.0 also includes several API changes from the 0.9 version. For more information on API changes, see the Overview of Changes and the API Differences Report. For those porting from the M5 release, the SDK also includes the legacy changes overview and API Differences Reports. See the current Overview of Changes for more information.

          - -

          ADT Plugin Compatibility

          - -

          For this version of the SDK — Android 1.0 SDK, Release 1 — the compatible version of the Android Development Tools (ADT) Plugin for Eclipse is 0.8.0. If you are using a previous version of ADT, you should update to the latest version for use with this SDK. For information about how to update your ADT plugin, see Upgrading the SDK.

          - -

          Installation and Upgrade Notes

          - -

          If you've been developing an application using a previous SDK version and you want the application to run on Android-powered mobile devices, you must port the application to the Android 1.0 SDK. Please see Upgrading the SDK for detailed instructions on how to make the transition to this release. Be sure to wipe application user data (emulator option -wipe-data) when running your application on the Android 1.0 SDK emulator.

          - -

          If you're installing the Android SDK for the first time, please see the instructions in Installing the SDK. - -

          Other Notes

          - -

          MapView API Key

          - -

          MapView is a class that lets you easily integrate Google Maps into your application. Before you can access the maps data, you will need to register with the Google Maps service and receive a Maps API Key, which you then add to your MapView for authentication to the server.

          - -

          Currently, the registration service for MapView is not yet active and Google Maps is not yet enforcing the Maps API Key requirement. However, note that the registration service will be activated soon, so that MapViews in any application deployed to a mobile device will require registration and a valid Maps API Key.

          - -

          As soon as the registration service becomes available, we will update the page at http://code.google.com/android/toolbox/apis/mapkey.html with details about how and where to register. Please check that page periodically for registration information, if you are using a MapView.

          - - -

          Resolved Issues, Changes

          - -

          Emulator

          -
            -
          • Emulator now saves the user image in <android>/SDK1.0/
          • -
          • Fixed EsounD-related freezes on Linux.
          • -
          • Fixed the documentation in -help-audio. '-audio list' doesn't work, one - needs to call -help-audio-out and -help-audio-in to get the list of valid - audio backends.
          • -
          • Fixed scrollwheel Dpad emulation in rotated mode. before that, using the - scroll-wheel would always generated Dpad Up/Down events, even when in - landscape mode.
          • -
          • Several Obsolete command options were removed.
          • -
          • Setting the network speed through the console or the -netspeed option will - properly modify the connectivity icon on the device.
          • -
          • Setting the GSM voice registration state to 'roaming' in the console will - properly modify the voice icon on the device
          • -
          - -

          SQLite

          -
            -
          • SQLite is now included in the SDK package on all platforms.
          • -
          - -

          Known Issues

          - -

          JUnit and Eclipse/ADT

          -
            -
          • If you are developing in Eclipse/ADT and want to add JUnit test -classes, you can do so. However, you need to set up a custom JUnit configuration -before your tests will run properly. For detailed information about how to set -up the JUnit configuration, see the troubleshooting topic Running a Junit test class -in Eclipse.
          • -
          - -

          Other

          - -
            -
          • It is not possible to send MMS messages between emulator instances.
          • -
          • In some cases, you may encounter problems when using the browser on an -emulator started with the command-line option -http-proxy.
          • -
          • We regret to inform developers that Android 1.0 will not include support for -dot-matrix printers.
          • -
          • On the OSX platform, if you manually remove the ~/.android directory -using rm -rf ~/.android, then try to run -the emulator, it crashes. This happens because the emulator fails to create -a new .android directory before attempting to create the child SDK1.0 directory. -To work around this issue, manually create a new .android directory using -mkdir ~/.android, then run the emulator. The emulator -creates the SDK1.0 directory and starts normally.
          • -
          • The final set of Intent patterns honored by Android 1.0 has not yet been -fully documented. Documentation will be provided in future releases.
          • -
          • In ADT Editor, you can add at most ten new resource values at a time, -in a given res/values/*.xml, using the form in the Android Resources pane. -If you add more than ten, the Android Resources pane will not display the -attributes fields for the additional resource entries. To work around this -problem, you can close the file in the editor and open it again, or you -can edit the resource entries in the XML text mode.
          • -
          • The emulator's battery-control commands (power <option>) -are not working in this release.
          • -
          • We regret to inform developers that Android 1.0 will not support 3.5" floppy disks. -
          • -
          • Unfortunately, the ability to play audio streams from memory (such as via an InputStream or Reader) will not be possible in Android 1.0.  As a workaround, we recommend that developers save media content to SD card and use MediaPlayer to play from a file URI, or embed a small HTTP server and play from a URI on localhost (such as http://127.0.0.1:4242/something). -
          • -
          • Android now supports modules or libraries that can be optionally linked into applications; a good example is the MapView, which has been moved into such a library. However, Android 1.0 will not support the ability for third-party developers to create such libraries for sharing with other applications. -
          • -
          • We believe that we have eliminated the problem with very long emulator startups on Windows, but had some trouble reproducing the issue.  We are interested in feedback from developers, if this issue persists. -
          • -
          - diff --git a/docs/html/sdk/1.0_r1/index.jd b/docs/html/sdk/1.0_r1/index.jd index 7ad4e882bc638abf8adeb8787aaea74a1b275b5c..b6e0e9f20992dea4bffb364c1cdf080d7dd9c466 100644 --- a/docs/html/sdk/1.0_r1/index.jd +++ b/docs/html/sdk/1.0_r1/index.jd @@ -1,6 +1,8 @@ -page.title=Download 1.0r1 +page.title=Android 1.0 SDK, release 1 -sdk.version=Android 1.0 SDK, release 1 +sdk.not_latest_version=true + +sdk.version=1.0_r1 sdk.date=September 23, 2008 sdk.win_download=android-sdk-windows-1.0_r1.zip @@ -15,4 +17,49 @@ sdk.linux_download=android-sdk-linux_x86-1.0_r1.zip sdk.linux_bytes=87.8 MB sdk.linux_checksum=2660b4029039b7d714e59827e9a9a11d + @jd:body + +

          Included in this SDK

          + +

          Development tools

          + +

          The SDK includes a variety of tools for developing and debugging application code and designing +an application UI. You can read about the tools in the documentation included with the SDK. +You can access the tools in the <sdk>/tools/ directory.

          + +

          System Images

          + +

          The Android system images listed below are included in this SDK.

          + + + + + + + + + + + + + + +
          System ImageAPI LevelNotesDescription
          Android 1.01N/AIncludes the {@code com.google.android.maps} external library and a set of standard development +applications.
          + +

          Sample Code and Applications

          + +

          You can look at a variety of tutorials and samples in the +documentation included with the SDK and access the sample code itself +in the <sdk>/samples/ directory of the SDK package.

          + +

          Documentation

          + +

          The SDK package provides a full set of local documentation, including installation and upgrade +instructions. To view it, open the <sdk>/documentation.html file in a web browser. +If you are developing in an IDE such as Eclipse, you can also view the reference documentation +directly in the IDE.

          + + + diff --git a/docs/html/sdk/1.0_r1/installing.jd b/docs/html/sdk/1.0_r1/installing.jd index 0f15396025880d6975629a5358c707946d1a677d..8ac524c443639238d3c0df95dd5a74c35e15659e 100644 --- a/docs/html/sdk/1.0_r1/installing.jd +++ b/docs/html/sdk/1.0_r1/installing.jd @@ -1,29 +1,27 @@ page.title=Installing the SDK +sdk.version=1.0_r1 @jd:body +

          For the current SDK release, see the links under Current SDK Release in the side navigation.

          -

          This page describes how to install the Android SDK and set up your development environment. If you haven't -downloaded the SDK yet, follow the link below.

          +

          This page describes how to install the Android 1.0 SDK, Release 1, and set up your development environment. +If you haven't downloaded the SDK yet, you can so from the Download page.

          - +

          Before you begin, be sure that your development environment meets the SDK +System Requirements. If you encounter any problems during installation, +see the Installation Notes at the bottom of this page.

          -

          Before you begin, be sure that you're development environment meets the SDK -System and Software Requirements.

          - -

          Upgrading?

          If you have already developed applications using an earlier version of the SDK, please skip this page and read the -Upgrading the SDK document. +Upgrading the SDK document instead.

          -
          -

          Installing the SDK

          -

          After downloading the SDK, unpack the .zip archive to a suitable location on your machine. By default, the SDK files are unpacked into a directory named android_sdk_<platform>_<release>_<build>. The directory contains the subdirectories tools/, samples/, and others.

          +

          After downloading the SDK, unpack the .zip archive to a suitable location on your machine. By default, the SDK files are unpacked into a directory named android_sdk_<platform>_<release>_<build>. The directory contains a link to a local copy of the documentation and the subdirectories tools/, samples/, and others.

          Make a note of the name and location of the unpacked SDK directory on your system — you will need to refer to the SDK directory later, when setting up the Android plugin or using SDK tools.

          @@ -47,10 +45,86 @@ SDK, please skip this page and read the

          Adding tools to your path lets you run Android Debug Bridge (adb) and the other command line tools without needing to supply the full path to the tools directory. Note that, if you update your SDK, you should remember to update your PATH settings to point to the new location, if different.

          -

          Setting up Eclipse

          -

          If you'll be developing with the Eclipse IDE, follow the following procedure to setup the IDE -to use the Android SDK.

          -

          Basically, you just need to update your Eclipse preferences to point to the Android SDK directory:

          + +

          If you will be using the Eclipse IDE as your environment for developing Android applications, continue reading the next +section in order to install the Android Development Tools plugin and setup Eclipse. If you choose not to use Eclipse, you can +develop Android applications using other tools — read the guide to developing +In other IDEs.

          + + +

          Setting up Eclipse

          + +

          First, you should install a custom plugin called Android Development Tools (ADT), which adds integrated support for Android projects and tools. The ADT plugin includes a variety of powerful extensions that make creating, running, and debugging Android applications faster and easier. Developing in ADT/Eclipse is highly recommended for Eclipse users and those new to Android.

          + +

          To download and install the ADT plugin, follow the steps below for your respective Eclipse version.

          + + + + + + + +
          Eclipse 3.3 (Europa)Eclipse 3.4 (Ganymede)
          +
            +
          1. Start Eclipse, then select Help > Software Updates > Find + and Install....
          2. + +
          3. In the dialog that appears, select Search for new features to install and click Next.
          4. +
          5. Click New Remote Site.
          6. +
          7. In the resulting dialog box, enter a name for the remote site (e.g. Android Plugin) and enter this as its URL: +
            https://dl-ssl.google.com/android/eclipse/
            +

            Alternatively, you can use http in the Location URL, if you are having + trouble with https (https is preferred for security reasons).

            +
            http://dl-ssl.google.com/android/eclipse/
            +

            Click OK.

          8. +
          9. You should now see the new site added to the search list (and checked). + Click Finish.
          10. +
          11. In the subsequent Search Results dialog box, select the checkbox for + Android Plugin > Developer Tools. + This will check both features: "Android Developer Tools", and "Android + Editors". The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next.
          12. +
          13. Read the license agreement and then select Accept terms of the license agreement. + Click Next.
          14. +
          15. Click Finish.
          16. + +
          17. The ADT plugin is not signed; you can accept the installation anyway + by clicking Install All.
          18. +
          19. Restart Eclipse.
          20. +
          + +
          + +
            +
          1. Start Eclipse, then select Help > Software Updates.... +
          2. +
          3. In the dialog that appears, click the Available Software tab. +
          4. +
          5. Click Add Site... +
          6. +
          7. Enter this as the Location: +
            https://dl-ssl.google.com/android/eclipse/
            +

            Alternatively, you can use http in the Location URL, if you are having + trouble with https (https is preferred for security reasons).

            +
            http://dl-ssl.google.com/android/eclipse/
            +

            Click OK.

          8. +
          9. Back in the Available Software view, you should see the plugin. Select the checkbox next to + Developer Tools and click Install... +
          10. +
          11. On the subsequent Install window, "Android Developer Tools", and "Android Editors" should both be checked. + The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next. +
          12. +
          13. Accept the license agreement and click Finish.
          14. +
          15. Restart Eclipse.
          16. +
          + +
          + + +

          Now, you just need to modify your Eclipse preferences to point to the Android SDK directory:

          1. Select Window > Preferences... to open the Preferences panel. (Mac OS X: Eclipse > Preferences)
          2. @@ -58,16 +132,55 @@ to use the Android SDK.

          3. For the SDK Location in the main panel, click Browse... and locate the SDK directory.
          4. Click Apply, then OK.
          -

          Done! We now recommend that you install the ADT Eclipse plugin, which will provide some much-appreciated assistance in developing Android apps with Eclipse...

          - -

          Installing the Eclipse Plugin (ADT)

          +

          Done! If you haven't encountered any problems, then you're ready to begin developing Android applications. +We recommend you begin with the Hello World tutorial, +which will teach you some basics about Android applications and how to create projects using Eclipse.

          -

          If you will be using the Eclipse IDE as your environment for developing Android applications, you can install a custom plugin called Android Development Tools (ADT), which adds integrated support for Android projects and tools. The ADT plugin includes a variety of powerful extensions that make creating, running, and debugging Android applications faster and easier. This plugin is highly recommended for Eclipse users.

          -

          If you will not be using the Eclipse IDE, you do not need to download or install the ADT plugin.

          +

          Troubleshooting ADT Installation

          +

          +If you are having trouble downloading the ADT plugin after following the steps above, here are some suggestions:

          -

          Follow this guide to install the ADT Plugin

          +
            +
          • If Eclipse can not find the remote update site containing the ADT plugin, try changing the remote site URL to use http, rather than https. That is, set the Location for the remote site to: +
            http://dl-ssl.google.com/android/eclipse/
          • +
          • If you are behind a firewall (such as a corporate firewall), make + sure that you have properly configured your proxy settings in Eclipse. + In Eclipse 3.3/3.4, you can configure proxy information from the main + Eclipse menu in Window (on Mac, Eclipse) > Preferences > General > Network Connections.
          • +
          +

          +If you are still unable to use Eclipse to download the ADT plugin as a remote update site, you can download the ADT files to your local machine using a browser and the install the files in Eclipse from there: +

          +
            +
          1. Download the ADT zip file (do not unpack it). +
          2. Follow steps 1 and 2 in the default install instructions (above). +
          3. In Eclipse 3.3, click New Archive Site....
            + In Eclipse 3.4, click Add Site..., then Archive... +
          4. Browse and select the downloaded the zip file. +
          5. Follow the remaining procedures, above, starting from steps 5. +
          +

          +Note that to update your plugin, you will have to follow these steps again instead of the default update instructions.

          + +

          Note that the "Android Editors" feature of ADT requires several optional +Eclipse components (for example, WST). If you encounter an error when +installing ADT, your Eclipse installion might not include those components. +For information about how to quickly add the necessary components to your +Eclipse installation, see the troubleshooting topic +ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".

          + +

          For Linux users

          +

          If you encounter this error when installing the ADT Plugin for Eclipse: +

          +An error occurred during provisioning.
          +Cannot connect to keystore.
          +JKS
          +

          +...then your development machine lacks a suitable Java VM. Installing Sun +Java 6 will resolve this issue and you can then reinstall the ADT +Plugin.

          Installation Notes

          @@ -106,19 +219,3 @@ at the top of this page. In particular, note that some Linux distributions may include JDK 1.4 or Gnu Compiler for Java, both of which are not supported for Android development. - - - - - - - - - - - - - - - - diff --git a/docs/html/sdk/1.0_r1/terms.jd b/docs/html/sdk/1.0_r1/terms.jd deleted file mode 100644 index 5c6e6fcb9d5c29998185cd0f52e7184d21582338..0000000000000000000000000000000000000000 --- a/docs/html/sdk/1.0_r1/terms.jd +++ /dev/null @@ -1,7 +0,0 @@ -page.title=Terms and Conditions -@jd:body - - - - - diff --git a/docs/html/sdk/1.0_r1/upgrading.jd b/docs/html/sdk/1.0_r1/upgrading.jd index 168f1be288a50e37eb781f8c272da958fd984aad..480bff384a9f545479c31e6e146e7fc019812164 100644 --- a/docs/html/sdk/1.0_r1/upgrading.jd +++ b/docs/html/sdk/1.0_r1/upgrading.jd @@ -1,37 +1,12 @@ page.title=Upgrading the SDK +sdk.version=1.0_r1 @jd:body - - +

          For the current SDK release, see the links under Current SDK Release in the side navigation.

          This guide will help you migrate your development environment and applications -to the latest version of the SDK. Use this guide if you've been developing applications -on a previous version of the Android SDK. -

          +to version 1.0, release 1, of the Android SDK. Use this guide if you've been developing applications +on a different version of the Android SDK.

          To ensure that your applications are compliant with the Android 1.0 system available on mobile devices, you need to install the new SDK and port your existing Android @@ -39,9 +14,7 @@ applications to the updated API. The sections below guide you through the proces

          Install the new SDK

          -

          Download the SDK and unpack it into a safe location.

          - -

          After unpacking the new SDK, you should:

          +

          After unpacking the SDK, you should:

          • Wipe your emulator data.

            Some data formats have changed since the last @@ -60,27 +33,58 @@ applications to the updated API. The sections below guide you through the proces

            Update your ADT Eclipse Plugin

            -

            If you develop on Eclipse and are using the ADT plugin, follow these steps to install the new plugin that accompanies the latest SDK.

            +

            If you develop on Eclipse and are using the ADT plugin, follow these steps to install the +plugin that's required for this version of the SDK.

            -
            Eclipse 3.3 (Europa)Eclipse 3.4 (Ganymede)
            +
              -
            1. Select Help > Software Updates > Find and Install....
            2. -
            3. Select Search for updates of the currently installed features and click Finish.
            4. -
            5. If any update for ADT is available, select and install.
            6. -
            7. Restart Eclipse.
            8. +
            9. Download the ADT v0.8.0 zip + file (do not unpack it).
            10. +
            11. Start Eclipse, then select Help > Software Updates > Find + and Install....
            12. +
            13. In the dialog that appears, select Search for new features to install and click + Next.
            14. +
            15. Click New Archive Site...
            16. +
            17. Browse and select the downloaded the zip file.
            18. +
            19. You should now see the new site added to the search list (and checked). + Click Finish.
            20. +
            21. In the subsequent Search Results dialog box, select the checkbox for + Android Plugin > Developer Tools. + This will check both features: "Android Developer Tools", and "Android + Editors". The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next.
            22. +
            23. Read the license agreement and then select Accept terms of the license agreement. + Click Next.
            24. +
            25. Click Finish.
            26. +
            27. The ADT plugin is not signed; you can accept the installation anyway + by clicking Install All.
            28. +
            29. Restart Eclipse.
            +
            +
              -
            1. Select Help > Software Updates...
            2. -
            3. Select the Installed Software tab.
            4. -
            5. Click Update...
            6. -
            7. If an update for ADT is available, select it and click Finish.
            8. -
            9. Restart Eclipse.
            10. +
            11. Download the ADT v0.8.0 zip + file (do not unpack it).
            12. +
            13. Start Eclipse, then select Help > Software Updates....
            14. +
            15. In the dialog that appears, click the Available Software tab.
            16. +
            17. Click Add Site..., then Archive....
            18. +
            19. Browse and select the downloaded the zip file.
            20. +
            21. Back in the Available Software view, you should see the plugin. Select the checkbox next to + Developer Tools and click Install...
            22. +
            23. On the subsequent Install window, "Android Developer Tools", and "Android Editors" should both be checked. + The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next.
            24. +
            25. Accept the license agreement and click Finish.
            26. +
            27. Restart Eclipse.
            +
            @@ -99,7 +103,7 @@ applications to the updated API. The sections below guide you through the proces the ADT plugin and the Ant-based build tools support this requirement by signing compiled .apk files with a debug key. To do so, the build tools use the Keytool utility included in the JDK to to create a keystore and a key with a known alias and password. For more -information, see Signing Your Applications. +information, see "Signing and Publishing Your App" in the documentation included with the SDK.

            To support signing, you should first make sure that Keytool is available to the SDK build tools. In most cases, you can tell the SDK build tools how to find Keytool by making sure that @@ -133,10 +137,7 @@ to place 3rd jar files, which are now automatically handled by the Ant script.

            One way to start is to open your project in Eclipse and see where the ADT -identifies errors in your application. From there, you can lookup -respective changes in the -Overview of Changes -and API Diffs Report.

            +identifies errors in your application.

            If you have additional trouble updating your code, visit the Android Developers Group @@ -144,8 +145,4 @@ to seek help from other Android developers.

            If you have modified one of the ApiDemos applications and would like to migrate it to the new SDK, note that you will need to uninstall the version of ApiDemos that comes -preinstalled in the emulator. For more information, or if you encounter an "reinstallation" -error when running or installing ApiDemos, see the troubleshooting topic -I can't install ApiDemos -apps in my IDE because of a signing error for information about how to solve the problem.

            - +preinstalled in the emulator.

            diff --git a/docs/html/sdk/1.0_r2/index.jd b/docs/html/sdk/1.0_r2/index.jd new file mode 100644 index 0000000000000000000000000000000000000000..2446c0913ac51e4d0eb44fe769900929ad4385dc --- /dev/null +++ b/docs/html/sdk/1.0_r2/index.jd @@ -0,0 +1,65 @@ +page.title=Android 1.0 SDK, release 2 + +sdk.not_latest_version=true + +sdk.version=1.0_r2 +sdk.date=November 2008 + +sdk.win_download=android-sdk-windows-1.0_r2.zip +sdk.win_bytes=98360564 +sdk.win_checksum=a5e1af8ac145946b4a9627516ad4a711 + +sdk.mac_download=android-sdk-mac_x86-1.0_r2.zip +sdk.mac_bytes=93771410 +sdk.mac_checksum=87b99d5e9f59b78363a63200c11498e8 + +sdk.linux_download=android-sdk-linux_x86-1.0_r2.zip +sdk.linux_bytes=94186463 +sdk.linux_checksum=a1f3b6d854596f850f5008856d0f380e + + +@jd:body + +

            Included in this SDK

            + +

            Development tools

            + +

            The SDK includes a variety of tools for developing and debugging application code and designing +an application UI. You can read about the tools in the documentation included with the SDK. +You can access the tools in the <sdk>/tools/ directory.

            + +

            System Images

            + +

            The Android system images listed below are included in this SDK.

            + + + + + + + + + + + + + + +
            System ImageAPI LevelNotesDescription
            Android 1.01N/AIncludes the {@code com.google.android.maps} external library and a set of standard development +applications.
            + +

            Sample Code and Applications

            + +

            You can look at a variety of tutorials and samples in the +documentation included with the SDK and access the sample code itself +in the <sdk>/samples/ directory of the SDK package.

            + +

            Documentation

            + +

            The SDK package provides a full set of local documentation, including installation and upgrade +instructions. To view it, open the <sdk>/documentation.html file in a web browser. +If you are developing in an IDE such as Eclipse, you can also view the reference documentation +directly in the IDE.

            + + + diff --git a/docs/html/sdk/1.0_r2/installing.jd b/docs/html/sdk/1.0_r2/installing.jd new file mode 100644 index 0000000000000000000000000000000000000000..2c58dfd9ad794467f162bdbdfad293344b99c524 --- /dev/null +++ b/docs/html/sdk/1.0_r2/installing.jd @@ -0,0 +1,221 @@ +page.title=Installing the SDK +sdk.version=1.0_r2 +@jd:body + +

            For the current SDK release, see the links under Current SDK Release in the side navigation.

            + +

            This page describes how to install the Android 1.0 SDK, Release 2, and set up your development environment. +If you haven't downloaded the SDK yet, you can so from the Download page.

            + +

            Before you begin, be sure that your development environment meets the SDK +System Requirements. If you encounter any problems during installation, +see the Installation Notes at the bottom of this page.

            + +

            Upgrading?

            +

            If you have already developed applications using an earlier version of the +SDK, please skip this page and read the +Upgrading the SDK document instead. +

            + + + +

            Installing the SDK

            + +

            After downloading the SDK, unpack the .zip archive to a suitable location on your machine. By default, the SDK files are unpacked into a directory named android_sdk_<platform>_<release>_<build>. The directory contains a link to a local copy of the documentation and the subdirectories tools/, samples/, and others.

            + +

            Make a note of the name and location of the unpacked SDK directory on your system — you will need to refer to the SDK directory later, when setting up the Android plugin or using SDK tools.

            + +

            Optionally, you can add the path to the SDK tools directory to your path. As mentioned above, the tools/ directory is located in the SDK directory.

            +
              +
            • On Linux, edit your ~/.bash_profile or ~/.bashrc file. Look + for a line that sets the PATH environment variable and add the + full path to the tools/ directory to it. If you don't + see a line setting the path, you can add one:
            • + +
                export PATH=${PATH}:<your_sdk_dir>/tools
              + +
            • On a Mac, look in your home directory for .bash_profile and + proceed as for Linux. You can create the .bash_profile, if + you haven't already set one up on your machine.
            • + +
            • On Windows, right click on My Computer, and select Properties. + Under the Advanced tab, hit the Environment Variables button, and in the + dialog that comes up, double-click on Path under System Variables. Add the full path to the tools/ directory to the path.
            • +
            + +

            Adding tools to your path lets you run Android Debug Bridge (adb) and the other command line tools without needing to supply the full path to the tools directory. Note that, if you update your SDK, you should remember to update your PATH settings to point to the new location, if different.

            + + +

            If you will be using the Eclipse IDE as your environment for developing Android applications, continue reading the next +section in order to install the Android Development Tools plugin and setup Eclipse. If you choose not to use Eclipse, you can +develop Android applications using other tools — read the guide to developing +In other IDEs.

            + + +

            Setting up Eclipse

            + +

            First, you should install a custom plugin called Android Development Tools (ADT), which adds integrated support for Android projects and tools. The ADT plugin includes a variety of powerful extensions that make creating, running, and debugging Android applications faster and easier. Developing in ADT/Eclipse is highly recommended for Eclipse users and those new to Android.

            + +

            To download and install the ADT plugin, follow the steps below for your respective Eclipse version.

            + + + + + + + +
            Eclipse 3.3 (Europa)Eclipse 3.4 (Ganymede)
            +
              +
            1. Start Eclipse, then select Help > Software Updates > Find + and Install....
            2. + +
            3. In the dialog that appears, select Search for new features to install and click Next.
            4. +
            5. Click New Remote Site.
            6. +
            7. In the resulting dialog box, enter a name for the remote site (e.g. Android Plugin) and enter this as its URL: +
              https://dl-ssl.google.com/android/eclipse/
              +

              Alternatively, you can use http in the Location URL, if you are having + trouble with https (https is preferred for security reasons).

              +
              http://dl-ssl.google.com/android/eclipse/
              +

              Click OK.

            8. +
            9. You should now see the new site added to the search list (and checked). + Click Finish.
            10. +
            11. In the subsequent Search Results dialog box, select the checkbox for + Android Plugin > Developer Tools. + This will check both features: "Android Developer Tools", and "Android + Editors". The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next.
            12. +
            13. Read the license agreement and then select Accept terms of the license agreement. + Click Next.
            14. +
            15. Click Finish.
            16. + +
            17. The ADT plugin is not signed; you can accept the installation anyway + by clicking Install All.
            18. +
            19. Restart Eclipse.
            20. +
            + +
            + +
              +
            1. Start Eclipse, then select Help > Software Updates.... +
            2. +
            3. In the dialog that appears, click the Available Software tab. +
            4. +
            5. Click Add Site... +
            6. +
            7. Enter this as the Location: +
              https://dl-ssl.google.com/android/eclipse/
              +

              Alternatively, you can use http in the Location URL, if you are having + trouble with https (https is preferred for security reasons).

              +
              http://dl-ssl.google.com/android/eclipse/
              +

              Click OK.

            8. +
            9. Back in the Available Software view, you should see the plugin. Select the checkbox next to + Developer Tools and click Install... +
            10. +
            11. On the subsequent Install window, "Android Developer Tools", and "Android Editors" should both be checked. + The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next. +
            12. +
            13. Accept the license agreement and click Finish.
            14. +
            15. Restart Eclipse.
            16. +
            + +
            + + +

            Now, you just need to modify your Eclipse preferences to point to the Android SDK directory:

            +
              +
            1. Select Window > Preferences... to open the Preferences + panel. (Mac OS X: Eclipse > Preferences)
            2. +
            3. Select Android from the left panel.
            4. +
            5. For the SDK Location in the main panel, click Browse... and locate the SDK directory.
            6. +
            7. Click Apply, then OK.
            8. +
            + +

            Done! If you haven't encountered any problems, then you're ready to begin developing Android applications. +We recommend you begin with the Hello World tutorial, +which will teach you some basics about Android applications and how to create projects using Eclipse.

            + + +

            Troubleshooting ADT Installation

            +

            +If you are having trouble downloading the ADT plugin after following the steps above, here are some suggestions:

            + +
              +
            • If Eclipse can not find the remote update site containing the ADT plugin, try changing the remote site URL to use http, rather than https. That is, set the Location for the remote site to: +
              http://dl-ssl.google.com/android/eclipse/
            • +
            • If you are behind a firewall (such as a corporate firewall), make + sure that you have properly configured your proxy settings in Eclipse. + In Eclipse 3.3/3.4, you can configure proxy information from the main + Eclipse menu in Window (on Mac, Eclipse) > Preferences > General > Network Connections.
            • +
            +

            +If you are still unable to use Eclipse to download the ADT plugin as a remote update site, you can download the ADT files to your local machine using a browser and the install the files in Eclipse from there: +

            +
              +
            1. Download the ADT zip file (do not unpack it). +
            2. Follow steps 1 and 2 in the default install instructions (above). +
            3. In Eclipse 3.3, click New Archive Site....
              + In Eclipse 3.4, click Add Site..., then Archive... +
            4. Browse and select the downloaded the zip file. +
            5. Follow the remaining procedures, above, starting from steps 5. +
            +

            +Note that to update your plugin, you will have to follow these steps again instead of the default update instructions.

            + +

            Note that the "Android Editors" feature of ADT requires several optional +Eclipse components (for example, WST). If you encounter an error when +installing ADT, your Eclipse installion might not include those components. +For information about how to quickly add the necessary components to your +Eclipse installation, see the troubleshooting topic +ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".

            + +

            For Linux users

            +

            If you encounter this error when installing the ADT Plugin for Eclipse: +

            +An error occurred during provisioning.
            +Cannot connect to keystore.
            +JKS
            +

            +...then your development machine lacks a suitable Java VM. Installing Sun +Java 6 will resolve this issue and you can then reinstall the ADT +Plugin.

            + + +

            Installation Notes

            +

            Ubuntu Linux Notes

            +
              +
            • If you need help installing and configuring Java on your +development machine, you might find these resources helpful: + +
            • +
            • Here are the steps to install Java and Eclipse, prior to installing +the Android SDK and ADT Plugin. +
                +
              1. If you are running a 64-bit distribution on your development +machine, you need to install the ia32-libs package using +apt-get:: +
                apt-get install ia32-libs
              2. +
              3. Next, install Java: +
                apt-get install sun-java6-bin
              4. +
              5. The Ubuntu package manager does not currently offer an Eclipse 3.3 + version for download, so we recommend that you download Eclipse from +eclipse.org (http://www.eclipse.org/ +downloads/). A Java or RCP version of Eclipse is recommended.
              6. +
              7. Follow the steps given in previous sections to install the SDK +and the ADT plugin.
              8. +
              +
            +

            Other Linux Notes

            +
              +
            • If JDK is already installed on your development computer, please +take a moment to make sure that it meets the version requirements listed +at the top of this page. In particular, note that some Linux +distributions may include JDK 1.4 or Gnu Compiler for Java, both of +which are not supported for Android development.
            • +
            diff --git a/docs/html/sdk/1.0_r2/requirements.jd b/docs/html/sdk/1.0_r2/requirements.jd new file mode 100644 index 0000000000000000000000000000000000000000..74d90ef0a3322acaa8b04a3fc46aba5a8bb5e821 --- /dev/null +++ b/docs/html/sdk/1.0_r2/requirements.jd @@ -0,0 +1,44 @@ +page.title=System Requirements +sdk.version=1.0_r2 + + +@jd:body + +

            The sections below describe the system and software requirements for developing Android applications using the Android SDK tools included in Android 1.0 SDK, Release 2.

            + +

            System and Software Requirements

            +

            The following systems and development environments are supported by this SDK.

            + +

            Supported Operating Systems:

            +
              +
            • Windows XP or Vista
            • +
            • Mac OS X 10.4.8 or later (x86 only)
            • +
            • Linux (tested on Linux Ubuntu Dapper Drake)
            • +
            + +

            Supported Development Environments:

            +
              +
            • Eclipse IDE + +
            • +
            • Other development environments or IDEs +
                +
              • JDK 5 or JDK 6 (JRE alone is not sufficient)
              • +
              • Apache Ant 1.6.5 or later for Linux and Mac, 1.7 or later for Windows
              • +
              • Not compatible with Gnu Compiler for Java (gcj)
              • +
              +
            • +
            + +

            Note: If JDK is already installed on your development computer, please take a moment to make sure that it meets the version requirements listed above. In +particular, note that some Linux distributions may include JDK 1.4 or Gnu Compiler for Java, both of which are not supported for Android development.

            \ No newline at end of file diff --git a/docs/html/sdk/1.0_r2/upgrading.jd b/docs/html/sdk/1.0_r2/upgrading.jd new file mode 100644 index 0000000000000000000000000000000000000000..df9b6579273b0227bd9f70d1ee20a1ba06681586 --- /dev/null +++ b/docs/html/sdk/1.0_r2/upgrading.jd @@ -0,0 +1,148 @@ +page.title=Upgrading the SDK +sdk.version=1.0_r2 +@jd:body + +

            For the current SDK release, see the links under Current SDK Release in the side navigation.

            + +

            This guide will help you migrate your development environment and applications +to version 1.0, release 2, of the Android SDK. Use this guide if you've been developing applications +on a different version of the Android SDK.

            + +

            To ensure that your applications are compliant with the Android 1.0 system available +on mobile devices, you need to install the new SDK and port your existing Android +applications to the updated API. The sections below guide you through the process.

            + +

            Install the new SDK

            + +

            After unpacking the SDK, you should:

            + +
              +
            • Wipe your emulator data.

              Some data formats have changed since the last + SDK release, so any previously saved data in your emulator must be removed. Open a console/terminal + and navigate to the /tools directory of your SDK. Launch the + emulator with the -wipe-data option.

              +

              Windows: emulator -wipe-data
              + Mac/Linux: ./emulator -wipe-data

              +
            • +
            • Update your PATH variable (Mac/Linux; optional).

              If you had previously setup your + PATH variable to point to the SDK tools directory, then you'll need to update it to + point to the new SDK. E.g., for a .bashrc or .bash_profile file: + export PATH=$PATH:<your_new_sdk_dir>/tools

              +
            • +
            + +

            Update your ADT Eclipse Plugin

            + +

            If you develop on Eclipse and are using the ADT plugin, follow these steps to install the +plugin that's required for this version of the SDK.

            + + + + + + + +
            Eclipse 3.3 (Europa)Eclipse 3.4 (Ganymede)
            +
              +
            1. Download the ADT v0.8.0 zip + file (do not unpack it).
            2. +
            3. Start Eclipse, then select Help > Software Updates > Find + and Install....
            4. +
            5. In the dialog that appears, select Search for new features to install and click + Next.
            6. +
            7. Click New Archive Site...
            8. +
            9. Browse and select the downloaded the zip file.
            10. +
            11. You should now see the new site added to the search list (and checked). + Click Finish.
            12. +
            13. In the subsequent Search Results dialog box, select the checkbox for + Android Plugin > Developer Tools. + This will check both features: "Android Developer Tools", and "Android + Editors". The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next.
            14. +
            15. Read the license agreement and then select Accept terms of the license agreement. + Click Next.
            16. +
            17. Click Finish.
            18. +
            19. The ADT plugin is not signed; you can accept the installation anyway + by clicking Install All.
            20. +
            21. Restart Eclipse.
            22. +
            + +
            + +
              +
            1. Download the ADT v0.8.0 zip + file (do not unpack it).
            2. +
            3. Start Eclipse, then select Help > Software Updates....
            4. +
            5. In the dialog that appears, click the Available Software tab.
            6. +
            7. Click Add Site..., then Archive....
            8. +
            9. Browse and select the downloaded the zip file.
            10. +
            11. Back in the Available Software view, you should see the plugin. Select the checkbox next to + Developer Tools and click Install...
            12. +
            13. On the subsequent Install window, "Android Developer Tools", and "Android Editors" should both be checked. + The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next.
            14. +
            15. Accept the license agreement and click Finish.
            16. +
            17. Restart Eclipse.
            18. +
            + +
            + +

            After restart, update your Eclipse preferences to point to the SDK directory:

            +
              +
            1. Select Window > Preferences... to open the Preferences panel. (Mac OSX: Eclipse > Preferences)
            2. +
            3. Select Android from the left panel.
            4. +
            5. For the SDK Location in the main panel, click Browse... and locate the SDK directory.
            6. +
            7. Click Apply, then OK.
            8. +
            + +

            Set Up Application Signing

            + +

            All applications must now be signed before you can install them on the emulator. Both +the ADT plugin and the Ant-based build tools support this requirement by signing compiled +.apk files with a debug key. To do so, the build tools use the Keytool utility included +in the JDK to to create a keystore and a key with a known alias and password. For more +information, see "Signing and Publishing Your App" in the documentation included with the SDK. + +

            To support signing, you should first make sure that Keytool is available to the SDK build +tools. In most cases, you can tell the SDK build tools how to find Keytool by making sure that +your JAVA_HOME environment variable is set and that it references a suitable JDK. Alternatively, +you can add the JDK version of Keytool to your PATH variable.

            + +

            If you are developing on a version of Linux that originally came with Gnu Compiler for Java, +make sure that the system is using the JDK version of Keytool, rather than the gcj version. +If keytool is already in your PATH, it might be pointing to a symlink at /usr/bin/keytool. +In this case, check the symlink target to make sure that it points to the keytool in the JDK.

            + +

            If you use Ant to build your .apk files (rather than ADT for Eclipse), you must regenerate +your build.xml file. To do that, follow these steps:

            +
              +
            1. In your Android application project directory, locate and delete the current build.xml file.
            2. +
            3. Run activitycreator, directing output to the folder containing your application project. + +
              - exec activitycreator --out <project folder> your.activity.YourActivity
              + +
            4. +
            + +

            Run in this way, activitycreator will not erase or create new Java files (or manifest files), +provided the activity and package already exists. It is important that the package and the activity +are real. The tool creates a new build.xml file, as well as a new directory called "libs" in which +to place 3rd jar files, which are now automatically handled by the Ant script.

            + +

            Migrate your applications

            + +

            After updating your SDK, you will likely encounter breakages in your code, due to +framework and API changes. You'll need to update your code to match changes in the Android APIs.

            + +

            One way to start is to open your project in Eclipse and see where the ADT +identifies errors in your application.

            + +

            If you have additional trouble updating your code, visit the +Android Developers Group +to seek help from other Android developers.

            + +

            If you have modified one of the ApiDemos applications and would like to migrate it +to the new SDK, note that you will need to uninstall the version of ApiDemos that comes +preinstalled in the emulator.

            diff --git a/docs/html/sdk/1.1_r1/index.jd b/docs/html/sdk/1.1_r1/index.jd new file mode 100644 index 0000000000000000000000000000000000000000..c4a9bf0e7f6367ae6d1d4231b452be58e2e0d7b3 --- /dev/null +++ b/docs/html/sdk/1.1_r1/index.jd @@ -0,0 +1,62 @@ +page.title=Android 1.1 SDK, Release 1 + +sdk.version=1.1_r1 +sdk.date=February 2009 + +sdk.win_download=android-sdk-windows-1.1_r1.zip +sdk.win_bytes=86038515 +sdk.win_checksum=8c4b9080b430025370689e03d20842f3 + +sdk.mac_download=android-sdk-mac_x86-1.1_r1.zip +sdk.mac_bytes=79046151 +sdk.mac_checksum=becf0f1763d61eedce15d2a903d6c1dd + +sdk.linux_download=android-sdk-linux_x86-1.1_r1.zip +sdk.linux_bytes=79345522 +sdk.linux_checksum=ebcb16b0cd4aef198b4dd9a1418efbf1 + + +@jd:body + +

            SDK Contents

            + +

            Development tools

            + +

            The SDK includes a variety of tools for developing and debugging application code and designing an application UI. You can read about the tools in the +Dev Guide and access them in the <sdk>/tools/ directory. + +

            The tools package included in this SDK is the same as that included in the Android 1.0, Release 2 SDK.

            + +

            System Images

            + +

            The Android system images listed below are included in this SDK. For more information about a system image — features, applications included, localizations, API changes, and so on — see its Version Notes.

            + + + + + + + + + + + + + + +
            System ImageAPI LevelNotesDescription
            Android 1.12Version NotesIncludes com.google.android.maps external library and a set of standard development applications.
            + +

            Sample Code and Applications

            + +

            You can look at a variety of tutorials and samples in the Dev Guide and access the sample code itself +in the <sdk>/samples/ directory of the SDK package.

            + +

            Documentation

            + +

            The SDK package includes a full set of local documentation. To view it, open the <sdk>/documentation.html file in a web browser. If you are developing in an IDE such as Eclipse, you can also view the reference documentation directly in the IDE.

            + +

            The most current documentation is always available on the Android Developers site:

            + +

            http://developer.android.com/

            + + diff --git a/docs/html/sdk/1.1_r1/installing.jd b/docs/html/sdk/1.1_r1/installing.jd new file mode 100644 index 0000000000000000000000000000000000000000..d5a7106483636287a1735cb04ba0ed01eea45d87 --- /dev/null +++ b/docs/html/sdk/1.1_r1/installing.jd @@ -0,0 +1,312 @@ +page.title=Installing the Android SDK +sdk.version=1.1_r1 + +@jd:body + + +

            This page describes how to install the Android SDK and set up your +development environment. If you haven't downloaded the SDK, you can +do so from the +Download page.

            + +

            If you encounter any problems during installation, see the +Installation Notes at the bottom of +this page.

            + +

            Upgrading?

            +

            If you have already developed applications using an earlier version +of the SDK, please skip this page and read the +Upgrading the +SDK document instead. +

            + + +

            Preparing for Installation

            + +

            Before you get started with the Android SDK, take a moment to confirm +that your development machine meets the system requirements. +

            + +

            If you will be developing on Eclipse with the Android Development +Tools (ADT) Plugin — the recommended path if you are new to +Android — make sure that you have a suitable version of Eclipse +installed on your computer. If you need to install Eclipse, you can +download it from this location:

            + +

            http://www.eclipse.org/downloads/

            + +

            A Java or RCP version of Eclipse is recommended.

            + +

            Installing the SDK

            + +

            After downloading the SDK, unpack the .zip archive to a suitable location on your machine. By default, the SDK files are unpacked into a directory named android_sdk_<platform>_<release>_<build>. The directory contains a link to a local copy of the documentation and the subdirectories tools/, samples/, and others.

            + +

            Make a note of the name and location of the unpacked SDK directory on your system — you will need to refer to the SDK directory later, when setting up the Android plugin or using SDK tools.

            + +

            Optionally, you can add the path to the SDK tools directory to your path. As mentioned above, the tools/ directory is located in the SDK directory.

            +
              +
            • On Linux, edit your ~/.bash_profile or ~/.bashrc file. Look + for a line that sets the PATH environment variable and add the + full path to the tools/ directory to it. If you don't + see a line setting the path, you can add one:
            • + +
                export PATH=${PATH}:<your_sdk_dir>/tools
              + +
            • On a Mac, look in your home directory for .bash_profile and + proceed as for Linux. You can create the .bash_profile, if + you haven't already set one up on your machine.
            • + +
            • On Windows, right click on My Computer, and select Properties. + Under the Advanced tab, hit the Environment Variables button, and in the + dialog that comes up, double-click on Path under System Variables. Add the full path to the tools/ directory to the path.
            • +
            + +

            Adding tools to your path lets you run Android Debug Bridge (adb) and the other command line tools without needing to supply the full path to the tools directory. Note that, if you update your SDK, you should remember to update your PATH settings to point to the new location, if different.

            + + +

            If you will be using the Eclipse IDE as your environment for developing Android applications, continue reading the next +section in order to install the Android Development Tools plugin and set up Eclipse. If you choose not to use Eclipse, you can +develop Android applications using other tools — read the guide to developing +in other IDEs.

            + + +

            Installing the ADT Plugin for Eclipse

            + +

            Android offers a custom plugin for the Eclipse IDE, called Android +Development Tools (ADT), that is designed to give you a powerful, +integrated environment in which to build Android applications. It +extends the capabilites of Eclipse to let you quickly set up new Android +projects, create an application UI, add components based on the Android +Framework API, and debug using the Android SDK tools.

            + +

            If you are new to Android or want to develop using the Eclipse IDE, +the ADT plugin will be an essential part of your development +environment. In general, using Eclipse with ADT is a highly recommended +approach and is the fastest way to get started. This section describes +how to install ADT into your Eclipse environment. + +

            If you prefer to work in a development environment other than Eclipse, +you do not need to install Eclipse or the ADT Plugin. Instead, you can +access the SDK tools directly to build and debug your application.

            + +

            Once you have Eclipse installed, as described in +Preparing for Installation, follow the steps below to +download the ADT plugin and install it in your respective Eclipse +environment.

            + + + + + + + +
            Eclipse 3.3 (Europa)Eclipse 3.4 (Ganymede)
            +
              +
            1. Start Eclipse, then select Help > Software Updates > Find + and Install....
            2. + +
            3. In the dialog that appears, select Search for new features to install and click Next.
            4. +
            5. Click New Remote Site.
            6. +
            7. In the resulting dialog box, enter a name for the remote site (e.g. Android Plugin) and enter this as its URL: +
              https://dl-ssl.google.com/android/eclipse/
              +

              Alternatively, you can use http in the Location URL, if you are having + trouble with https (https is preferred for security reasons).

              +
              http://dl-ssl.google.com/android/eclipse/
              +

              Click OK.

            8. +
            9. You should now see the new site added to the search list (and checked). + Click Finish.
            10. +
            11. In the subsequent Search Results dialog box, select the checkbox for + Android Plugin > Developer Tools. + This will check both features: "Android Developer Tools", and "Android + Editors". The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next.
            12. +
            13. Read the license agreement and then select Accept terms of the license agreement. + Click Next.
            14. +
            15. Click Finish.
            16. + +
            17. The ADT plugin is not signed; you can accept the installation anyway + by clicking Install All.
            18. +
            19. Restart Eclipse.
            20. +
            + +
            + +
              +
            1. Start Eclipse, then select Help > Software Updates.... +
            2. +
            3. In the dialog that appears, click the Available Software tab. +
            4. +
            5. Click Add Site... +
            6. +
            7. Enter this as the Location: +
              https://dl-ssl.google.com/android/eclipse/
              +

              Alternatively, you can use http in the Location URL, if you are having + trouble with https (https is preferred for security reasons).

              +
              http://dl-ssl.google.com/android/eclipse/
              +

              Click OK.

            8. +
            9. Back in the Available Software view, you should see the plugin. Select the checkbox next to + Developer Tools and click Install... +
            10. +
            11. On the subsequent Install window, "Android Developer Tools", and "Android Editors" should both be checked. + The Android Editors feature is optional, but recommended. If + you choose to install it, you need the WST plugin mentioned earlier in this + page. Click Next. +
            12. +
            13. Accept the license agreement and click Finish.
            14. +
            15. Restart Eclipse.
            16. +
            + +
            + +

            Now, you just need to modify your Eclipse preferences to point to the Android SDK directory:

            +
              +
            1. Select Window > Preferences... to open the Preferences + panel. (Mac OS X: Eclipse > Preferences)
            2. +
            3. Select Android from the left panel.
            4. +
            5. For the SDK Location in the main panel, click Browse... and locate the SDK directory.
            6. +
            7. Click Apply, then OK.
            8. +
            + +

            Done! If you haven't encountered any problems, then you're ready to +begin developing Android applications. See the After +Installation: Next Steps section for suggestions on how to start.

            + + +

            Troubleshooting ADT Installation

            +

            +If you are having trouble downloading the ADT plugin after following the steps above, here are some suggestions:

            + +
              +
            • If Eclipse can not find the remote update site containing the ADT plugin, try changing the remote site URL to use http, rather than https. That is, set the Location for the remote site to: +
              http://dl-ssl.google.com/android/eclipse/
            • +
            • If you are behind a firewall (such as a corporate firewall), make + sure that you have properly configured your proxy settings in Eclipse. + In Eclipse 3.3/3.4, you can configure proxy information from the main + Eclipse menu in Window (on Mac, Eclipse) > Preferences > General > Network Connections.
            • +
            +

            +If you are still unable to use Eclipse to download the ADT plugin as a remote update site, you can download the ADT files to your local machine using a browser and the install the files in Eclipse from there: +

            +
              +
            1. Download the ADT zip file (do not unpack it). +
            2. Follow steps 1 and 2 in the default install instructions (above). +
            3. In Eclipse 3.3, click New Archive Site....
              + In Eclipse 3.4, click Add Site..., then Archive... +
            4. Browse and select the downloaded the zip file. +
            5. Follow the remaining procedures, above, starting from steps 5. +
            +

            +Note that to update your plugin, you will have to follow these steps again instead of the default update instructions.

            + +

            Note that the "Android Editors" feature of ADT requires several optional +Eclipse components (for example, WST). If you encounter an error when +installing ADT, your Eclipse installion might not include those components. +For information about how to quickly add the necessary components to your +Eclipse installation, see the troubleshooting topic +ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".

            + +

            For Linux users

            +

            If you encounter this error when installing the ADT Plugin for Eclipse: +

            +An error occurred during provisioning.
            +Cannot connect to keystore.
            +JKS
            +

            +...then your development machine lacks a suitable Java VM. Installing Sun +Java 6 will resolve this issue and you can then reinstall the ADT +Plugin.

            + + +

            After Installation: Next Steps

            +

            Once you have installed the SDK and the ADT Plugin, you are ready to +begin developing applications. Here are a few ways you can get started:

            + +

            Learn about Android

            +
              +
            • Take a look at the Dev +Guide and the types of information it provides
            • +
            • Read an introduction to Android as a platform in What is +Android?
            • +
            • Learn about the Android framework and how applications run on it in +Application +Fundamentals
            • +
            • Take a look at the Android framework API specification in the Reference tab
            • +
            + +

            Explore the SDK

            + + +

            Explore some code

            +
              +
            • Set up a Hello +World application
            • +
            • Follow the +Notepad Tutorial to build a full Android application
            • +
            • Create a new project for one of the other sample applications +included in <sdk>/samples, then compile and run it in +your development environment
            • +
            + +

            Visit the Android developer groups

            +
              +
            • Take a look at the Community tab to see a list of +Android developers groups. In particular, you might want to look at the +Android +Developers group to get a sense for what the Android developer +community is like.
            • +
            + + +

            Installation Notes

            +

            Ubuntu Linux Notes

            +
              +
            • If you need help installing and configuring Java on your +development machine, you might find these resources helpful: + +
            • +
            • Here are the steps to install Java and Eclipse, prior to installing +the Android SDK and ADT Plugin. +
                +
              1. If you are running a 64-bit distribution on your development +machine, you need to install the ia32-libs package using +apt-get:: +
                apt-get install ia32-libs
              2. +
              3. Next, install Java: +
                apt-get install sun-java6-bin
              4. +
              5. The Ubuntu package manager does not currently offer an Eclipse 3.3 + version for download, so we recommend that you download Eclipse from +eclipse.org (http://www.eclipse.org/ +downloads/). A Java or RCP version of Eclipse is recommended.
              6. +
              7. Follow the steps given in previous sections to install the SDK +and the ADT plugin.
              8. +
              +
            +

            Other Linux Notes

            +
              +
            • If JDK is already installed on your development computer, please +take a moment to make sure that it meets the version requirements listed +in the System Requirements. +In particular, note that some Linux distributions may include JDK 1.4 or Gnu +Compiler for Java, both of which are not supported for Android development.
            • +
            + + diff --git a/docs/html/sdk/1.0_r1/requirements.jd b/docs/html/sdk/1.1_r1/requirements.jd similarity index 81% rename from docs/html/sdk/1.0_r1/requirements.jd rename to docs/html/sdk/1.1_r1/requirements.jd index 6af3900e68114493ad68fb5c86d13020bf1d45bc..95b658bea2037278815cf70f89dc0f5c44eca52b 100644 --- a/docs/html/sdk/1.0_r1/requirements.jd +++ b/docs/html/sdk/1.1_r1/requirements.jd @@ -1,18 +1,20 @@ -page.title=System and Software Requirements -@jd:body +page.title=System Requirements + +sdk.version=1.1_r1 +sdk.date=February 2009 +@jd:body -

            To develop Android applications using the code and tools in the Android SDK, -you need a suitable development computer and development environment, as described below.

            +

            The sections below describe the system and software requirements for developing Android applications using the Android SDK tools included in Android 1.1 SDK, Release 1.

            -

            Supported Operating Systems:

            +

            Supported Operating Systems

              -
            • Windows XP or Vista
            • +
            • Windows XP (32-bit) or Vista (32- or 64-bit)
            • Mac OS X 10.4.8 or later (x86 only)
            • Linux (tested on Linux Ubuntu Dapper Drake)
            -

            Supported Development Environments:

            +

            Supported Development Environments

            • Eclipse IDE
                diff --git a/docs/html/sdk/1.1_r1/upgrading.jd b/docs/html/sdk/1.1_r1/upgrading.jd new file mode 100644 index 0000000000000000000000000000000000000000..2ad6757c0904dc8b006b7cb0cf32e93002fc26a6 --- /dev/null +++ b/docs/html/sdk/1.1_r1/upgrading.jd @@ -0,0 +1,150 @@ +page.title=Upgrading the SDK +sdk.version=1.1_r1 +@jd:body + + + +

                This document describes how to move your development environment and existing +Android applications from an Android 1.0 SDK to the Android 1.1, Release 1 SDK. +If you are migrating applications from an earlier SDK, please read the upgrading +document available in the Android 1.0 SDK package. +

                + +

                To ensure that your applications are compliant with the Android 1.1 system available +on mobile devices, you need to install the Android 1.1 SDK and port your existing Android +applications to it. The sections below will guide you through the process.

                + +

                Installing the Latest SDK

                + +

                Download the SDK and unpack it into a safe location.

                + +

                After unpacking the new SDK and saving it an appropriate location, you should:

                + +
                  +
                • Wipe your emulator data.

                  Some data formats have changed since the last + SDK release, so any previously saved data in your emulator must be removed. Open a console/terminal + and navigate to the /tools directory of your new SDK. Launch the + emulator with the -wipe-data option. +

                  Windows: emulator -wipe-data
                  + Mac/Linux: ./emulator -wipe-data

                  +
                • +
                • Update your PATH variable (Mac/Linux; optional).

                  If you had previously setup your + PATH variable to point to the SDK tools directory, then you'll need to update it to + point to the new SDK. For example, for a .bashrc or .bash_profile file: + export PATH=$PATH:<your_new_sdk_dir>/tools

                  +
                • +
                • If (and only if) you are developing using Ant, you will also need to modify + your build.xml properties to point to the new SDK. +

                  Open the default.properties file associated with your build.xml + file (typically located in the same directory). In the default.properties + file, update the sdk-folder property with the full path to + the new SDK directory.

                • +
                + + +

                Update your ADT Eclipse Plugin

                + +

                If you develop on Eclipse and are migrating from an Android 1.0 +SDK, no update of the ADT plugin is needed — skip to Update your Eclipse SDK Preferences.

                + +

                If you are migrating from an earlier version of the SDK, you will +need to update the ADT plugin.

                You may also want to upgrade your +ADT plugin when a new version becomes available for your existing version +of the SDK.

                + +

                The steps below describe how to update the ADT plugin to the latest +version available.

                + + + + + + + +
                Eclipse 3.3 (Europa)Eclipse 3.4 (Ganymede)
                +
                  +
                1. Select Help > Software Updates > Find and Install....
                2. +
                3. Select Search for updates of the currently installed features and click Finish.
                4. +
                5. If any update for ADT is available, select and install.
                6. +
                7. Restart Eclipse.
                8. +
                +

                Alternatively,

                +
                  +
                1. Select Help > Software Updates > Manage Configuration.
                2. + +
                3. Navigate down the tree and select Android Development Tools <version>
                4. +
                5. Select Scan for Updates under Available Tasks.
                6. +
                +
                +
                  +
                1. Select Help > Software Updates...
                2. +
                3. Select the Installed Software tab.
                4. +
                5. Click Update...
                6. +
                7. If an update for ADT is available, select it and click Finish.
                8. +
                9. Restart Eclipse.
                10. +
                +
                + +

                Update your Eclipse SDK Preferences

                + +

                The last step is to update your Eclipse preferences to point to the new SDK directory:

                +
                  +
                1. Select Window > Preferences... to open the Preferences panel. (Mac OSX: Eclipse > Preferences)
                2. +
                3. Select Android from the left panel.
                4. +
                5. For the SDK Location in the main panel, click Browse... and locate the SDK directory.
                6. +
                7. Click Apply, then OK.
                8. +
                + +

                Migrate Your Applications, if Necessary

                + +

                If (and only if) you have written apps in an SDK released previous to +the Android 1.0 SDK, you will need to migrate your applications. After +installing the new SDK and updating the ADT Plugin (if applicable), you +may encounter breakages in your application code, due to +framework and API changes. You'll need to update your code to match the +latest APIs.

                + +

                One way to start is to open your project in Eclipse and see where the ADT +identifies errors in your application. From there, you can lookup +specific API changes in the Android 1.0 APIs in the + +Overview of Changes and +API Diffs Report.

                + +

                If you have additional trouble updating your code, visit the +Android Developers Group +to seek help from other Android developers.

                + +

                If you have modified one of the ApiDemos applications and would like to migrate it +to the new SDK, note that you will need to uninstall the version of ApiDemos that comes +preinstalled in the emulator. For more information, or if you encounter an "reinstallation" +error when running or installing ApiDemos, see the troubleshooting topic +I can't install ApiDemos +apps in my IDE because of a signing error for information about how to solve the problem.

                + diff --git a/docs/html/sdk/RELEASENOTES.jd b/docs/html/sdk/RELEASENOTES.jd new file mode 100644 index 0000000000000000000000000000000000000000..bad71a2a59da3894cc7a5a9a3a02ad2f0538ffd7 --- /dev/null +++ b/docs/html/sdk/RELEASENOTES.jd @@ -0,0 +1,327 @@ +page.title=SDK Release Notes +@jd:body + +

                This document provides version-specific information about Android SDK releases. For the latest known issues, please ensure that you're viewing this page at: http://developer.android.com/sdk/RELEASENOTES.html.

                + +

                Android 1.1 SDK, Release 1

                + +

                This SDK provides the development tools and Android system image you need to create applications for Android-powered devices. Applications developed on this SDK will be compatible with mobile devices running the Android 1.1 platform.

                + +

                This release provides an updated system image (Android 1.1), updated documentation, and the same set of development tools provided in the Android 1.0 r2 SDK. The updated system image includes bug fixes and some smaller features, as well as a few minor API changes from the 1.0 version.

                + +

                For details about the Android 1.1 system image included in the SDK — including bug fixes, features, and API changes — please read the Android 1.1 Version Notes.

                + +

                App Versioning for Android 1.1

                + +

                If you are using this SDK to build an application that is compatible only with Android-powered devices running the Android 1.1 platform, please note that you must set the the android:minSdkVersion attribute in the application's manifest to the API Level of Android 1.1 — "2".

                + +

                Specifically, you specify the android:minSdkVersion attribute in a <uses-sdk> element as a child of <manifest> in the manifest file. When set, the attribute looks like this:

                + +
                <manifest>
                +  ...
                +  <uses-sdk minSdkVersion="2" />
                +  ...
                +</manifest>
                +
                + +

                By setting android:minSdkVersion in this way, you ensure that users will only be able to install your application if their devices are running the Android 1.1 platform. In turn, this ensures that your application will function properly on their devices, especially if it uses APIs introduced in Android 1.1.

                + +

                If your application uses APIs introduced in Android 1.1 but does not declare <uses-sdk minSdkVersion="2" />, then it will run properly on Android 1.1 devices but not on Android 1.0 devices.

                + +

                If your application does not use any new APIs introduced in Android 1.1, you can indicate Android 1.0 compatibility by removing minSdkVersion or setting the attribute to "1". However, before publishing your application, you must make sure to compile your application against the Android 1.0 system image (available in the Android 1.0 SDK), to ensure that it builds and functions properly for Android 1.0 devices. You should test the application against system images corresponding to the API Levels that the application is designed to be compatible with.

                + +

                If you are sure your application is not using Android 1.1 APIs and has no need to use them, you might find it easier to keep working in the Android 1.0 SDK, rather than migrating to the Android 1.1 SDK and having to do additional testing.

                + + +

                ADT Plugin Compatibility

                + +

                For this version of the SDK — Android 1.1 SDK, Release 1 +— the compatible version of the Android Development Tools (ADT) +Plugin for Eclipse is 0.8.0. If you are using a +previous version of ADT, you should update to the latest version for use +with this SDK. For information about how to update your ADT plugin, see +Upgrading +the SDK.

                + +

                Installation and Upgrade Notes

                + +

                If you've been developing an application using an Android 1.0 SDK no +changes to your application are needed. You may want to wipe application +user data (emulator option -wipe-data) when running your +application on the Android 1.1 emulator for the first time.

                + +

                If you're installing the Android SDK for the first time, please see +the instructions in Installing the SDK. + +

                Other Notes

                + +

                MapView API Key

                + +

                com.google.android.maps.MapView is a class that lets you +easily integrate Google Maps into your application. Before you can +access the maps data, you will need to register with the Google Maps +service and receive a Maps API Key, which you then add to your MapView +for authentication to the server.

                + +

                Developers should note that the registration service for MapView is now +active and Google Maps is actively enforcing the Maps API Key requirement. +For information about how to register for a Maps API Key, see + +Obtaining a Maps API Key.

                + +

                USB Drivers for Windows

                + +

                If you using Windows and want to develop or test your application on an +Android-powered device (such as the T-Mobile G1), you need an appropriate USB +driver. For your convenience, the Windows version of the Android SDK includes +these USB drivers that you can install, to let you develop on the device:

                + +
                  +
                • USB driver for 32-bit XP and Vista
                • +
                • USB driver for 64-bit Vista only
                • +
                + +

                The USB driver files are located in the +<SDK>/usb_driver directory. For details and +installation instructions, see Setting Up a +Device for Development.

                +

                + +

                Resolved Issues, Changes

                + +

                Emulator

                +
                  +
                • Emulator now saves the user image in <android>/SDK1.1/
                • +
                + +

                Known Issues

                + +

                JUnit and Eclipse/ADT

                +
                  +
                • If you are developing in Eclipse/ADT and want to add JUnit test +classes, you can do so. However, you need to set up a custom JUnit configuration +before your tests will run properly. For detailed information about how to set +up the JUnit configuration, see the troubleshooting topic Running a Junit test class +in Eclipse.
                • +
                + +

                Other

                + +
                  +
                • It is not possible to send MMS messages between emulator instances.
                • +
                • In some cases, you may encounter problems when using the browser on an +emulator started with the command-line option -http-proxy.
                • +
                • On the OSX platform, if you manually remove the ~/.android directory +using rm -rf ~/.android, then try to run +the emulator, it crashes. This happens because the emulator fails to create +a new .android directory before attempting to create the child SDK1.0 directory. +To work around this issue, manually create a new .android directory using +mkdir ~/.android, then run the emulator. The emulator +creates the SDK1.0 directory and starts normally.
                • +
                • We regret to inform developers that Android 1.1 will not include support +for ARCNet network interfaces.
                • +
                • The final set of Intent patterns honored by Android 1.0 has not yet been +fully documented. Documentation will be provided in future releases.
                • +
                • In ADT Editor, you can add at most ten new resource values at a time, +in a given res/values/*.xml, using the form in the Android Resources pane. +If you add more than ten, the Android Resources pane will not display the +attributes fields for the additional resource entries. To work around this +problem, you can close the file in the editor and open it again, or you +can edit the resource entries in the XML text mode.
                • +
                • The emulator's battery-control commands (power <option>) +are not working in this release.
                • +
                + + + + + +

                Android 1.0 SDK, Release 2

                + +

                This SDK release includes the Android 1.0 platform and application API. +Applications developed on this SDK will be compatible with mobile devices +running the Android 1.0 platform.

                + +

                This release includes mainly bug fixes, although some smaller features were +added.

                + +

                ADT Plugin Compatibility

                + +

                For this release of the SDK, the compatible version of the Android +Development Tools (ADT) Plugin for Eclipse is 0.8.0. If you are +using a previous version of ADT, you should update to the latest version for use +with this SDK. For information about how to update your ADT plugin, see Upgrading the SDK.

                + +

                Installation and Upgrade Notes

                + +

                If you're installing the Android SDK for the first time, please see the +instructions in Installing the +SDK. + +

                Other Notes

                + +

                T-Mobile G1 Compatability

                + +

                This version of the SDK has been tested for compatability with the first +Android-powered mobile device, the T-Mobile +G1.

                + +

                MapView API Key

                + +

                MapView is a class that lets you easily integrate Google Maps into your +application. Before you can access the maps data, you will need to register with +the Google Maps service and receive a Maps API Key, which you then add to your +MapView for authentication to the server.

                + +

                Developers should note that the registration service for MapView is now +active and Google Maps is actively enforcing the Maps API Key requirement. For +information about how to register for a Maps API Key, see http://code. +google.com/android/toolbox/apis/mapkey.html.

                + +

                USB Driver for Windows

                +

                If you using Windows and want to develop or test your application on an +Android-powered device (such as the T-Mobile G1), you need an appropriate USB +driver. For your convenience, the Windows version of the Android SDK includes a +USB driver that you can install, to let you develop on the device. The USB +driver files are located in the <SDK>/usb_driver directory. + +

                + +

                Resolved Issues, Changes

                +
                  +
                • The android.jar in this SDK release now includes several classes that were +missing from the previous SDK.
                • +
                • The android.R.styleable class and its fields were removed from the public +API, to better ensure forward-compatibility for applications. The constants +declared in android.R.styleable were platform-specific and subject to arbitrary +change across versions, so were not suitable for use by applications. You can +still access the platform's styleable attributes from your resources or code. To +do so, declare a custom resource element using a +<declare-styleable> in your project's res/values/R.attrs +file, then declare the attribute inside. For examples, see +<sdk>/samples/ApiDemos/res/values/attrs.xml. For more information about +custom resources, see Custom +Layout Resources. Note that the android.R.styleable documentation is still +provided in the SDK, but only as a reference of the platform's styleable +attributes for the various elements.
                • +
                • The VM now properly ensures that private classes are not +available to applications through reflection. If you were using reflection +to access private classes in a previous release, you will now get a run-time +error.
                • + +
                • The Settings and Email applications are now included in the SDK and +available in the emulator.
                • +
                • We regret to inform developers that SDK 1.0_r2 does not support MFM, RLL, +or Winchester hard disk drives.
                • +
                • In the emulator, the control key for enabling/disabling trackball mode +is changed from Control-T to F6. You can also enter trackball mode temporarily +using the Delete key. While the key is pressed, you can send trackball events.
                • +
                + +

                Unless otherwise noted, Known Issues from the previous SDK release also apply +to this release.

                + + + + + + +

                Android 1.0 SDK, Release 1

                + +

                This SDK release is the first to include the Android 1.0 platform and application API. Applications developed on this SDK will be compatible with mobile devices running the Android 1.0 platform, when such devices are available.

                + +

                This release includes mainly bug fixes, although some smaller features were added. The Android 1.0 also includes several API changes from the 0.9 version. For more information on API changes, see the Overview of Changes and the API Differences Report. For those porting from the M5 release, the SDK also includes the legacy changes overview and API Differences Reports. See the current Overview of Changes for more information.

                + +

                ADT Plugin Compatibility

                + +

                For this version of the SDK — Android 1.0 SDK, Release 1 — the compatible version of the Android Development Tools (ADT) Plugin for Eclipse is 0.8.0. If you are using a previous version of ADT, you should update to the latest version for use with this SDK. For information about how to update your ADT plugin, see Upgrading the SDK.

                + +

                Installation and Upgrade Notes

                + +

                If you've been developing an application using a previous SDK version and you want the application to run on Android-powered mobile devices, you must port the application to the Android 1.0 SDK. Please see Upgrading the SDK for detailed instructions on how to make the transition to this release. Be sure to wipe application user data (emulator option -wipe-data) when running your application on the Android 1.0 SDK emulator.

                + +

                If you're installing the Android SDK for the first time, please see the instructions in Installing the SDK. + +

                Other Notes

                + +

                MapView API Key

                + +

                MapView is a class that lets you easily integrate Google Maps into your application. Before you can access the maps data, you will need to register with the Google Maps service and receive a Maps API Key, which you then add to your MapView for authentication to the server.

                + +

                Currently, the registration service for MapView is not yet active and Google Maps is not yet enforcing the Maps API Key requirement. However, note that the registration service will be activated soon, so that MapViews in any application deployed to a mobile device will require registration and a valid Maps API Key.

                + +

                As soon as the registration service becomes available, we will update the page at http://code.google.com/android/toolbox/apis/mapkey.html with details about how and where to register. Please check that page periodically for registration information, if you are using a MapView.

                + + +

                Resolved Issues, Changes

                + +

                Emulator

                +
                  +
                • Emulator now saves the user image in <android>/SDK1.0/
                • +
                • Fixed EsounD-related freezes on Linux.
                • +
                • Fixed the documentation in -help-audio. '-audio list' doesn't work, one + needs to call -help-audio-out and -help-audio-in to get the list of valid + audio backends.
                • +
                • Fixed scrollwheel Dpad emulation in rotated mode. before that, using the + scroll-wheel would always generated Dpad Up/Down events, even when in + landscape mode.
                • + +
                • Several Obsolete command options were removed.
                • +
                • Setting the network speed through the console or the -netspeed option will + properly modify the connectivity icon on the device.
                • +
                • Setting the GSM voice registration state to 'roaming' in the console will + properly modify the voice icon on the device
                • +
                + +

                SQLite

                +
                  +
                • SQLite is now included in the SDK package on all platforms.
                • +
                + +

                Known Issues

                + +

                JUnit and Eclipse/ADT

                +
                  +
                • If you are developing in Eclipse/ADT and want to add JUnit test +classes, you can do so. However, you need to set up a custom JUnit configuration +before your tests will run properly. For detailed information about how to set +up the JUnit configuration, see the troubleshooting topic Running a Junit test class +in Eclipse.
                • +
                + +

                Other

                + +
                  +
                • It is not possible to send MMS messages between emulator instances.
                • +
                • In some cases, you may encounter problems when using the browser on an +emulator started with the command-line option -http-proxy.
                • + +
                • We regret to inform developers that Android 1.0 will not include support for +dot-matrix printers.
                • +
                • On the OSX platform, if you manually remove the ~/.android directory +using rm -rf ~/.android, then try to run +the emulator, it crashes. This happens because the emulator fails to create +a new .android directory before attempting to create the child SDK1.0 directory. +To work around this issue, manually create a new .android directory using +mkdir ~/.android, then run the emulator. The emulator +creates the SDK1.0 directory and starts normally.
                • +
                • The final set of Intent patterns honored by Android 1.0 has not yet been +fully documented. Documentation will be provided in future releases.
                • +
                • In ADT Editor, you can add at most ten new resource values at a time, +in a given res/values/*.xml, using the form in the Android Resources pane. +If you add more than ten, the Android Resources pane will not display the +attributes fields for the additional resource entries. To work around this +problem, you can close the file in the editor and open it again, or you +can edit the resource entries in the XML text mode.
                • +
                • The emulator's battery-control commands (power <option>) +are not working in this release.
                • + +
                + diff --git a/docs/html/guide/developing/tools/adt_download.jd b/docs/html/sdk/adt_download.jd similarity index 90% rename from docs/html/guide/developing/tools/adt_download.jd rename to docs/html/sdk/adt_download.jd index f03cc4651029d542693437ef2e649e2ef4d0d99f..6e9eec4a2b73617c2ab7099e0eb0b9e2f7615aca 100644 --- a/docs/html/guide/developing/tools/adt_download.jd +++ b/docs/html/sdk/adt_download.jd @@ -29,8 +29,8 @@ page. 0.8.0 ADT-0.8.0.zip 23 September 2008 - Android 1.0 SDK, Release 1 - Required for users of Android 1.0 SDK, Release 1. + Android 1.1 SDK, Release 1
                Android 1.0 SDK, Release 1
                + Required for users of Android 1.1 SDK, Release 1 and Android 1.0 SDK, Release 1
                0.7.1 diff --git a/docs/html/sdk/android-1.1.jd b/docs/html/sdk/android-1.1.jd new file mode 100644 index 0000000000000000000000000000000000000000..f70ad262a51458cb72248d1484d65dd1c6dc4a8b --- /dev/null +++ b/docs/html/sdk/android-1.1.jd @@ -0,0 +1,249 @@ +page.title=Android 1.1 Version Notes +sdk.version=1.1_r1 +sys.date=February 2009 +@jd:body + +

                +Date: February 2009
                +API Level: 2

                + + +

                This document provides version notes for the Android 1.1 system image included in the SDK. + +

                + +

                Overview

                + +

                The Android 1.1 system image delivered in the SDK is the development +counterpart to the Android 1.1 production system image, deployable to +Android-powered handsets starting in February 2009.

                + +

                The Android 1.1 system image delivers an updated version of the framework +API. As with the Android 1.0 API, the Android 1.1 API +is assigned an integer identifier — 2 — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

                + +

                Applications can reference a specific API Level value in their +manifest files, to indicate the minimum version of the Android system +required to run the app. To reference a minimum API Level, applications +can add a minSdkVersion attribute in their manifest files. +The value of the attribute is an integer corresponding to an API Level +identifier. Prior to installing an application, the system then checks the value of +minSdkVersion and allows the install only +if the referenced integer is less than or equal to the API Level integer stored +in the system itself.

                + +

                If you use the Android 1.1 system image to build an application +compatible with Android-powered devices running the Android 1.1 +platform, please note that you must set the the +android:minSdkVersion attribute in the application's +manifest to "2", which is the API strictly associated with Android 1.1. +

                + +

                Specifically, you specify the android:minSdkVersion +attribute in a <uses-sdk> element as a child of +<manifest> in the manifest file. When set, the +attribute looks like this:

                + +
                <manifest>
                +  ...
                +  <uses-sdk minSdkVersion="2" />
                +  ...
                +</manifest>
                +
                + +

                By setting android:minSdkVersion in this way, you ensure +that users will only be able to install your application if their +devices are running the Android 1.1 platform. In turn, this ensures that +your application will function properly on their devices, especially if +it uses APIs introduced in Android 1.1.

                + +

                If your application uses APIs introduced in Android 1.1 but does not +declare <uses-sdk minSdkVersion="2" />, then it will +run properly on Android 1.1 devices but not on Android 1.0 +devices. In the latter case, the application will crash at runtime when +it tries to use the Android 1.1 APIs.

                + +

                If your application does not use any new APIs introduced in Android +1.1, you can indicate Android 1.0 compatibility by removing +minSdkVersion or setting the attribute to "1". However, +before publishing your application, you must make sure to compile your +application against the Android 1.0 system image (available in the +Android 1.0 SDK), to ensure that it builds and functions properly for +Android 1.0 devices. You should test the application against system +images corresponding to the API Levels that the application is designed +to be compatible with.

                + +

                If you are sure your application is not using Android 1.1 APIs and +has no need to use them, you might find it easier to keep working in the +Android 1.0 SDK, rather than migrating to the Android 1.1 SDK and having +to do additional testing.

                + + +

                External Libraries

                + +

                The system image includes these external libraries, which you can +access from your application by adding a +<uses-library>.

                +
                  +
                • com.google.android.maps — gives your +application access to Google Maps data. Note that, to use Google Maps +data, a Maps API Key is required.
                • +
                + +

                Device Compatibility

                + +

                The Android 1.1 system image was tested for compatability with the +Android-powered devices listed below:

                + + +

                Built-in Applications

                + +

                The system image includes these built-in applications:

                +
                  +
                • Alarm Clock
                • +
                • API Demos
                • +
                • Browser
                • +
                • Calculator
                • +
                • Camera
                • +
                • Contacts
                • +
                • Dev Tools
                • +
                • Dialer
                • +
                • Email
                • +
                • Maps (and StreetView)
                • +
                • Messaging
                • +
                • Music
                • +
                • Pictures
                • +
                • Settings
                • +
                + +

                UI Localizations

                + +

                The system image provides localized UI strings for the languages +listed below.

                +
                  +
                • English, US (en_US)
                • +
                • German (de)
                • +
                + +

                Localized UI strings match the locales that are displayable in +the emulator, accessible through the device Settings application.

                + +

                Resolved Issues

                +
                  +
                • AlarmClock alert now plays audio/vibe directly, rather than through +AlarmManager. AlarmClock alert starts playing audio/vibe in its +IntentReceiver, rather than on activity start. These changes should +prevent alarms from being blocked by modal dialogs.
                • +
                • Fixes to device sleep.
                • +
                • Single tap no longer opens the in-call dialpad; users now need to +touch and drag it.
                • +
                • Fixes a bug causing approximately 1 in 25 outbound messages to +freeze up the IMAP connection (to a Gmail based server) when transferred +to the Sent folder.
                • +
                • Removes automatic account setup entries that were broken or not +testable. Adds minor fixes to a few of the remaining entries. Makes +improvements to warning dialogs used for a few special cases.
                • +
                • Changes default mail checking interval to every 15 minutes (instead +of defaulting to "never").
                • +
                • Fixes password-quoting bugs in IMAP, so that users can include +special characters in passwords (e.g. spaces).
                • +
                • Fixes various errors in auto and manual account setup
                • +
                • Improves reporting for various connection errors, making it easier +for the user to diagnose failed account setups.
                • +
                • Fixes new-mail notifications for POP3 accounts.
                • +
                • Ensures proper auto-checking of accounts marked as "never +check".
                • +
                • Now displays date and time using user preference (e.g. 24 hr vs. +AM/PM).
                • +
                • Now shows cc: in message view.
                • +
                • Improves recovery from POP3 connection failures.
                • +
                • POP3 parser rules loosened, so the application can work with +non-compliant email servers.
                • +
                + +

                New Features

                + +
                  +
                • Maps: Adds details and reviews when a user does a search on Maps and +clicks on a business to view its details.
                • +
                • Dialer: In-call screen timeout default is now longer when using the +speakerphone.
                • +
                • Dialer: Adds a "Show dialpad" / "Hide dialpad" item to the in-call +menu, to make it easier to discover the DTMF dialpad.
                • +
                • Adds support for saving attachments from MMS
                • +
                • Adds support for marquee in layouts.
                • +
                + +

                API Changes

                + +

                Overview

                + +
                  +
                • Adds annotations for test systems, no actual (non-test) API +changes.
                • +
                • Adds a method to allow a process to easily determine its UID. +
                • Adds support for marquee in layouts.
                • +
                • Adds new methods for determining padding in views. Useful if you are +writing your own +subclasses of {@link android.view.View View}.
                • +
                • Adds new permissions that allow an application to broadcast an SMS +or WAP Push message.
                • +
                • API cleanup: removes protected constructor from +SDK-bound system images.
                • +
                + +

                API Change Details

                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                Module or FeatureChange Description
                Annotations for test systems
                Added {@link android.test.suitebuilder.annotation.LargeTest LargeTest} annotation.
                Added {@link android.test.suitebuilder.annotation.MediumTest MediumTest} annotation.
                Added {@link android.test.suitebuilder.annotation.SmallTest SmallTest} annotation.
                Allow a process to easily know its UID.
                Added public method {@link android.os.Process#myUid} to class {@link android.os.Process android.os.Process}
                Padding in views
                Added public method {@link android.view.View#getBottomPaddingOffset} to class {@link android.view.View android.view.View}.
                Added public method {@link android.view.View#getLeftPaddingOffset} to class {@link android.view.View android.view.View}.
                Added public method {@link android.view.View#getRightPaddingOffset} to class {@link android.view.View android.view.View}.
                Added public method {@link android.view.View#getTopPaddingOffset} to class {@link android.view.View android.view.View}.
                Added public method {@link android.view.View#isPaddingOffsetRequired} to class {@link android.view.View android.view.View}.
                Marquee support
                Added public method {@link android.widget.TextView#setMarqueeRepeatLimit} to class {@link android.widget.TextView}
                Added public field {@link android.R.attr#marqueeRepeatLimit android.R.attr.marqueeRepeatLimit}
                New permissions
                Added public field {@link android.Manifest.permission#BROADCAST_SMS android.Manifest.permission.BROADCAST_SMS}
                Added public field {@link android.Manifest.permission#BROADCAST_WAP_PUSH android.Manifest.permission.BROADCAST_WAP_PUSH}
                API cleanup
                Removed protected constructor java.net.ServerSocket.ServerSocket(java.net.SocketImpl).
                + + + + + + diff --git a/docs/html/sdk/download.jd b/docs/html/sdk/download.jd new file mode 100644 index 0000000000000000000000000000000000000000..3c4f06b5685845a7c9eddd74a08ff3ef3e3df2be --- /dev/null +++ b/docs/html/sdk/download.jd @@ -0,0 +1,86 @@ +page.title=Download the Android SDK +hide_license_footer=true + +@jd:body + + + +
                +

                Please carefully review the Android SDK License Agreement before downloading the SDK. +The License Agreement constitutes a contract between you and Google with respect to your use of the SDK.

                + + + +

                + + +

                +

                + +

                +

                + +

                +
                + + + + + + + + + + + + + diff --git a/docs/html/sdk/index.html b/docs/html/sdk/index.html deleted file mode 100644 index c5468ddc2bf489660db0ac9ee3e9ce86bda4b511..0000000000000000000000000000000000000000 --- a/docs/html/sdk/index.html +++ /dev/null @@ -1,6 +0,0 @@ - - -Redirecting... - - - \ No newline at end of file diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd new file mode 100644 index 0000000000000000000000000000000000000000..38db6f80de08c4a709b1b4092b27b63b158df345 --- /dev/null +++ b/docs/html/sdk/index.jd @@ -0,0 +1,5 @@ +sdk.redirect=1.1_r1 +@jd:body + + + diff --git a/docs/html/sdk/sdk_toc.cs b/docs/html/sdk/sdk_toc.cs index 11d3086d6ff258c69d54dde8915f88227340c1db..76c1c84ea07ba9eed00abf82a324935ff730c043 100644 --- a/docs/html/sdk/sdk_toc.cs +++ b/docs/html/sdk/sdk_toc.cs @@ -1,37 +1,42 @@ -
                  -
                • Android 1.0

                  + + \ No newline at end of file diff --git a/docs/html/sdk/terms.jd b/docs/html/sdk/terms.jd index 5599fa691a8988b4989c078b037929b66cae0fd3..4638850421a29274108d9a99a2ea9489f2f6fd40 100644 --- a/docs/html/sdk/terms.jd +++ b/docs/html/sdk/terms.jd @@ -1,4 +1,5 @@ page.title=Terms and Conditions +hide_license_footer=true @jd:body

                  This is the Android Software Development Kit License Agreement.

                  diff --git a/docs/html/sdk/terms_body.html b/docs/html/sdk/terms_body.html new file mode 100644 index 0000000000000000000000000000000000000000..e8fdc3cff7619748058dabce7c315a893e2ad665 --- /dev/null +++ b/docs/html/sdk/terms_body.html @@ -0,0 +1,216 @@ + +

                  This is the Android Software Development Kit License Agreement.

                  + +

                  + 1. Introduction +

                  +

                  + 1.1 The Android Software Development Kit (referred to in this License Agreement as the "SDK" and specifically including the Android system files and packaged APIs) is licensed to you subject to the terms of this License Agreement. This License Agreement forms a legally binding contract between you and Google in relation to your use of the SDK. +

                  +

                  + 1.2 "Google" means Google Inc., a Delaware corporation with principal place of business at 1600 Amphitheatre Parkway, Mountain View, CA 94043, United States. +

                  +

                  + 2. Accepting this License Agreement +

                  +

                  + 2.1 In order to use the SDK, you must first agree to this License Agreement. You may not use the SDK if you do not accept this License Agreement. +

                  +

                  + 2.2 You can accept this License Agreement by: +

                  +

                  + (A) clicking to accept or agree to this License Agreement, where this option is made available to you; or +

                  +

                  + (B) by actually using the SDK. In this case, you agree that use of the SDK constitutes acceptance of the Licensing Agreement from that point onwards. +

                  +

                  + 2.3 You may not use the SDK and may not accept the Licensing Agreement if you are a person barred from receiving the SDK under the laws of the United States or other countries including the country in which you are resident or from which you use the SDK. +

                  +

                  + 2.4 If you are agreeing to be bound by this License Agreement on behalf of your employer or other entity, you represent and warrant that you have full legal authority to bind your employer or such entity to this License Agreement. If you do not have the requisite authority, you may not accept the Licensing Agreement or use the SDK on behalf of your employer or other entity. +

                  +

                  + 3. SDK License from Google +

                  +

                  + 3.1 Subject to the terms of this License Agreement, Google grants you a limited, worldwide, royalty-free, non- assignable and non-exclusive license to use the SDK solely to develop applications to run on the Android platform. +

                  +

                  + 3.2 You agree that Google or third parties own all legal right, title and interest in and to the SDK, including any Intellectual Property Rights that subsist in the SDK. "Intellectual Property Rights" means any and all rights under patent law, copyright law, trade secret law, trademark law, and any and all other proprietary rights. The Android Open Source Project +

                  +

                  + 3.3 Except to the extent required by applicable third party licenses, you may not copy (except for backup purposes), modify, adapt, redistribute, decompile, reverse engineer, disassemble, or create derivative works of the SDK or any part of the SDK. Except to the extent required by applicable third party licenses, you may not load any part of the SDK onto a mobile handset or any other hardware device except a personal computer, combine any part of the SDK with other software, or distribute any software or device incorporating a part of the SDK. +

                  +

                  + 3.4 Use, reproduction and distribution of components of the SDK licensed under an open source software license are governed solely by the terms of that open source software license and not this License Agreement. +

                  +

                  + 3.5 You agree that the form and nature of the SDK that Google provides may change without prior notice to you and that future versions of the SDK may be incompatible with applications developed on previous versions of the SDK. You agree that Google may stop (permanently or temporarily) providing the SDK (or any features within the SDK) to you or to users generally at Google's sole discretion, without prior notice to you. +

                  +

                  + 3.6 Nothing in this License Agreement gives you a right to use any of Google's trade names, trademarks, service marks, logos, domain names, or other distinctive brand features. +

                  +

                  + 3.7 You agree that you will not remove, obscure, or alter any proprietary rights notices (including copyright and trademark notices) that may be affixed to or contained within the SDK. +

                  +

                  + 4. Use of the SDK by You +

                  +

                  + 4.1 Google agrees that it obtains no right, title or interest from you (or your licensors) under this License Agreement in or to any software applications that you develop using the SDK, including any intellectual property rights which subsist in those applications. +

                  +

                  + 4.2 You agree to use the SDK and write applications only for purposes that are permitted by (a) this License Agreement and (b) any applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions (including any laws regarding the export of data or software to and from the United States or other relevant countries). +

                  +

                  + 4.3 You agree that if you use the SDK to develop applications for general public users, you will protect the privacy and legal rights of those users. If the users provide you with user names, passwords, or other login information or personal information, your must make the users aware that the information will be available to your application, and you must provide legally adequate privacy notice and protection for those users. If your application stores personal or sensitive information provided by users, it must do so securely. If the user provides your application with Google Account information, your application may only use that information to access the user's Google Account when, and for the limited purposes for which, the user has given you permission to do so. +

                  +

                  + 4.4 You agree that you will not engage in any activity with the SDK, including the development or distribution of an application, that interferes with, disrupts, damages, or accesses in an unauthorized manner the servers, networks, or other properties or services of any third party including, but not limited to, Google or any mobile communications carrier. +

                  +

                  + 4.5 You agree that you are solely responsible for (and that Google has no responsibility to you or to any third party for) any data, content, or resources that you create, transmit or display through the Android platform and/or applications for the Android platform, and for the consequences of your actions (including any loss or damage which Google may suffer) by doing so. +

                  +

                  + 4.6 You agree that you are solely responsible for (and that Google has no responsibility to you or to any third party for) any breach of your obligations under this License Agreement, any applicable third party contract or Terms of Service, or any applicable law or regulation, and for the consequences (including any loss or damage which Google or any third party may suffer) of any such breach. +

                  +

                  + 5. Your Developer Credentials +

                  +

                  + 5.1 You agree that you are responsible for maintaining the confidentiality of any developer credentials that may be issued to you by Google or which you may choose yourself and that you will be solely responsible for all applications that are developed under your developer credentials. +

                  +

                  + 6. Privacy and Information +

                  +

                  + 6.1 In order to continually innovate and improve the SDK, Google may collect certain usage statistics from the software including but not limited to a unique identifier, associated IP address, version number of the software, and information on which tools and/or services in the SDK are being used and how they are being used. Before any of this information is collected, the SDK will notify you and seek your consent. If you withhold consent, the information will not be collected. +

                  +

                  + 6.2 The data collected is examined in the aggregate to improve the SDK and is maintained in accordance with Google's Privacy Policy. +

                  +

                  + 7. Third Party Applications for the Android Platform +

                  +

                  + 7.1 If you use the SDK to run applications developed by a third party or that access data, content or resources provided by a third party, you agree that Google is not responsible for those applications, data, content, or resources. You understand that all data, content or resources which you may access through such third party applications are the sole responsibility of the person from which they originated and that Google is not liable for any loss or damage that you may experience as a result of the use or access of any of those third party applications, data, content, or resources. +

                  +

                  + 7.2 You should be aware the data, content, and resources presented to you through such a third party application may be protected by intellectual property rights which are owned by the providers (or by other persons or companies on their behalf). You may not modify, rent, lease, loan, sell, distribute or create derivative works based on these data, content, or resources (either in whole or in part) unless you have been specifically given permission to do so by the relevant owners. +

                  +

                  + 7.3 You acknowledge that your use of such third party applications, data, content, or resources may be subject to separate terms between you and the relevant third party. In that case, this License Agreement does not affect your legal relationship with these third parties. +

                  +

                  + 8. Using Android APIs +

                  +

                  + 8.1 Android Maps API +

                  +

                  + 8.1.1 If you use the Android Maps API (described in the SDK by the Package names "com.google.android.maps" and "com.android.location.Geocoder"), the terms of your binding legal agreement with Google include this License Agreement, the Google Maps API Terms of Service and the Google Maps Terms of Service. You must read and agree to those Terms of Service before you use the Android Maps API. +

                  +

                  + 8.1.2 If you use the Android Maps API to retrieve map or satellite image data from Google, you must include the following copyright notice in your application or service in a manner that is reasonably available to users: +

                  +

                  + "Copyright Notice: Data: (c)2007 TeleAtlas, AND, Europa Technologies, Kingway, Map Data Sciences Pty Ltd, PSMA, ZENRIN, Geocentre, MapLink/TeleAtlas; Imagery: (c)2007 DigitalGlobe, EarthSat, Sanborn, NYGIS, Scankort, TerraMetrics, MassGIS Commonwealth of Massachusetts, Digital Earth Technology." +

                  +

                  + 8.2 Google Data APIs +

                  +

                  + 8.2.1 If you use any API to retrieve data from Google, you acknowledge that the data may be protected by intellectual property rights which are owned by those who provide that data (or by other persons or companies on their behalf). You may not modify, rent, lease, loan, sell, distribute or create derivative works based on this data (either in whole or in part) unless you have been specifically given permission to do so by the owners of that data. +

                  +

                  + 8.2.2 If you use any API to retrieve a user's data from Google, you acknowledge and agree that you shall retrieve data only with the user's explicit consent and only when, and for the limited purposes for which, the user has given you permission to do so. +

                  +

                  + 9. Terminating this License Agreement +

                  +

                  + 9.1 This License Agreement will continue to apply until terminated by either you or Google as set out below. +

                  +

                  + 9.2 If you want to terminate this License Agreement, you may do so by ceasing your use of the SDK and any relevant developer credentials. +

                  +

                  + 9.3 Google may at any time, terminate this License Agreement with you if: +

                  +

                  + (A) you have breached any provision of this License Agreement; or +

                  +

                  + (B) Google is required to do so by law; or +

                  +

                  + (C) the partner with whom Google offered certain parts of SDK (such as APIs) to you has terminated its relationship with Google or ceased to offer certain parts of the SDK to you; or +

                  +

                  + (D) Google decides to no longer providing the SDK or certain parts of the SDK to users in the country in which you are resident or from which you use the service, or the provision of the SDK or certain SDK services to you by Google is, in Google's sole discretion, no longer commercially viable. +

                  +

                  + 9.4 When this License Agreement comes to an end, all of the legal rights, obligations and liabilities that you and Google have benefited from, been subject to (or which have accrued over time whilst this License Agreement has been in force) or which are expressed to continue indefinitely, shall be unaffected by this cessation, and the provisions of paragraph 14.7 shall continue to apply to such rights, obligations and liabilities indefinitely. +

                  +

                  + 10. DISCLAIMER OF WARRANTIES +

                  +

                  + 10.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE SDK IS AT YOUR SOLE RISK AND THAT THE SDK IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OF ANY KIND FROM GOOGLE. +

                  +

                  + 10.2 YOUR USE OF THE SDK AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE OF THE SDK IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. +

                  +

                  + 10.3 GOOGLE FURTHER EXPRESSLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. +

                  +

                  + 11. LIMITATION OF LIABILITY +

                  +

                  + 11.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT GOOGLE, ITS SUBSIDIARIES AND AFFILIATES, AND ITS LICENSORS SHALL NOT BE LIABLE TO YOU UNDER ANY THEORY OF LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL CONSEQUENTIAL OR EXEMPLARY DAMAGES THAT MAY BE INCURRED BY YOU, INCLUDING ANY LOSS OF DATA, WHETHER OR NOT GOOGLE OR ITS REPRESENTATIVES HAVE BEEN ADVISED OF OR SHOULD HAVE BEEN AWARE OF THE POSSIBILITY OF ANY SUCH LOSSES ARISING. +

                  +

                  + 12. Indemnification +

                  +

                  + 12.1 To the maximum extent permitted by law, you agree to defend, indemnify and hold harmless Google, its affiliates and their respective directors, officers, employees and agents from and against any and all claims, actions, suits or proceedings, as well as any and all losses, liabilities, damages, costs and expenses (including reasonable attorneys fees) arising out of or accruing from (a) your use of the SDK, (b) any application you develop on the SDK that infringes any copyright, trademark, trade secret, trade dress, patent or other intellectual property right of any person or defames any person or violates their rights of publicity or privacy, and (c) any non-compliance by you with this License Agreement. +

                  +

                  + 13. Changes to the License Agreement +

                  +

                  + 13.1 Google may make changes to the License Agreement as it distributes new versions of the SDK. When these changes are made, Google will make a new version of the License Agreement available on the website where the SDK is made available and with the SDK downloadable. +

                  +

                  + 13.2 You agree that your use of a specific version of the SDK is governed by the License Agreement included with that version of the SDK. +

                  +

                  + 14. General Legal Terms +

                  +

                  + 14.1 This License Agreement constitute the whole legal agreement between you and Google and govern your use of the SDK (excluding any services which Google may provide to you under a separate written agreement), and completely replace any prior agreements between you and Google in relation to the SDK. +

                  +

                  + 14.2 You agree that if Google does not exercise or enforce any legal right or remedy which is contained in this License Agreement (or which Google has the benefit of under any applicable law), this will not be taken to be a formal waiver of Google's rights and that those rights or remedies will still be available to Google. +

                  +

                  + 14.3 If any court of law, having the jurisdiction to decide on this matter, rules that any provision of this License Agreement is invalid, then that provision will be removed from this License Agreement without affecting the rest of this License Agreement. The remaining provisions of this License Agreement will continue to be valid and enforceable. +

                  +

                  + 14.4 You acknowledge and agree that each member of the group of companies of which Google is the parent shall be third party beneficiaries to this License Agreement and that such other companies shall be entitled to directly enforce, and rely upon, any provision of this License Agreement that confers a benefit on (or rights in favor of) them. Other than this, no other person or company shall be third party beneficiaries to this License Agreement. +

                  +

                  + 14.5 EXPORT RESTRICTIONS. THE SDK IS SUBJECT TO UNITED STATES EXPORT LAWS AND REGULATIONS. YOU MUST COMPLY WITH ALL DOMESTIC AND INTERNATIONAL EXPORT LAWS AND REGULATIONS THAT APPLY TO THE SDK. THESE LAWS INCLUDE RESTRICTIONS ON DESTINATIONS, END USERS AND END USE. +

                  +

                  + 14.6 The rights granted in this License Agreement may not be assigned or transferred by either you or Google without the prior written approval of the other party. Neither you nor Google shall be permitted to delegate their responsibilities or obligations under this License Agreement without the prior written approval of the other party. +

                  +

                  + 14.7 This License Agreement, and your relationship with Google under this License Agreement, shall be governed by the laws of the State of California without regard to its conflict of laws provisions. You and Google agree to submit to the exclusive jurisdiction of the courts located within the county of Santa Clara, California to resolve any legal matter arising from this License Agreement. Notwithstanding this, you agree that Google shall still be allowed to apply for injunctive remedies (or an equivalent type of urgent legal relief) in any jurisdiction. +

                  +

                  + August 18, 2008 +

                  diff --git a/docs/html/search.jd b/docs/html/search.jd old mode 100755 new mode 100644 index 9269d2c66ed1abe43db846f8d86635b54e9a3108..0a802a6bfcbe76107b55efd7293e66175751f0e3 --- a/docs/html/search.jd +++ b/docs/html/search.jd @@ -1,77 +1,101 @@ page.title=Search Results @jd:body - + +

                  search results

                  diff --git a/docs/html/sitemap.txt b/docs/html/sitemap.txt new file mode 100644 index 0000000000000000000000000000000000000000..a8221bf52f6b2e75a89baeecd7b6a75945b1ebf3 --- /dev/null +++ b/docs/html/sitemap.txt @@ -0,0 +1,5444 @@ +http://developer.android.com/index.html +http://developer.android.com/sdk/1.1_r1/index.html +http://developer.android.com/guide/index.html +http://developer.android.com/reference/packages.html +http://developer.android.com/community/index.html +http://developer.android.com/sdk/index.html +http://developer.android.com/license.html +http://developer.android.com/sdk/terms.html +http://developer.android.com/guide/developing/tools/index.html +http://developer.android.com/reference/com/google/android/maps/package-summary.html +http://developer.android.com/reference/classes.html +http://developer.android.com/reference/android/package-summary.html +http://developer.android.com/reference/android/app/package-summary.html +http://developer.android.com/reference/android/content/package-summary.html +http://developer.android.com/reference/android/content/pm/package-summary.html +http://developer.android.com/reference/android/content/res/package-summary.html +http://developer.android.com/reference/android/database/package-summary.html +http://developer.android.com/reference/android/database/sqlite/package-summary.html +http://developer.android.com/reference/android/graphics/package-summary.html +http://developer.android.com/reference/android/graphics/drawable/package-summary.html +http://developer.android.com/reference/android/graphics/drawable/shapes/package-summary.html +http://developer.android.com/reference/android/hardware/package-summary.html +http://developer.android.com/reference/android/location/package-summary.html +http://developer.android.com/reference/android/media/package-summary.html +http://developer.android.com/reference/android/net/package-summary.html + +http://developer.android.com/reference/android/net/http/package-summary.html +http://developer.android.com/reference/android/net/wifi/package-summary.html + +http://developer.android.com/reference/android/opengl/package-summary.html +http://developer.android.com/reference/android/os/package-summary.html + +http://developer.android.com/reference/android/preference/package-summary.html +http://developer.android.com/reference/android/provider/package-summary.html + +http://developer.android.com/reference/android/sax/package-summary.html +http://developer.android.com/reference/android/telephony/package-summary.html + +http://developer.android.com/reference/android/telephony/gsm/package-summary.html +http://developer.android.com/reference/android/test/package-summary.html + +http://developer.android.com/reference/android/test/mock/package-summary.html +http://developer.android.com/reference/android/test/suitebuilder/package-summary.html + +http://developer.android.com/reference/android/text/package-summary.html +http://developer.android.com/reference/android/text/method/package-summary.html + +http://developer.android.com/reference/android/text/style/package-summary.html +http://developer.android.com/reference/android/text/util/package-summary.html + +http://developer.android.com/reference/android/util/package-summary.html +http://developer.android.com/reference/android/view/package-summary.html + +http://developer.android.com/reference/android/view/animation/package-summary.html +http://developer.android.com/reference/android/webkit/package-summary.html + +http://developer.android.com/reference/android/widget/package-summary.html +http://developer.android.com/reference/dalvik/bytecode/package-summary.html + +http://developer.android.com/reference/dalvik/system/package-summary.html +http://developer.android.com/reference/java/awt/font/package-summary.html + +http://developer.android.com/reference/java/io/package-summary.html +http://developer.android.com/reference/java/lang/package-summary.html + +http://developer.android.com/reference/java/lang/annotation/package-summary.html +http://developer.android.com/reference/java/lang/ref/package-summary.html + +http://developer.android.com/reference/java/lang/reflect/package-summary.html +http://developer.android.com/reference/java/math/package-summary.html + +http://developer.android.com/reference/java/net/package-summary.html +http://developer.android.com/reference/java/nio/package-summary.html + +http://developer.android.com/reference/java/nio/channels/package-summary.html +http://developer.android.com/reference/java/nio/channels/spi/package-summary.html + +http://developer.android.com/reference/java/nio/charset/package-summary.html +http://developer.android.com/reference/java/nio/charset/spi/package-summary.html + +http://developer.android.com/reference/java/security/package-summary.html +http://developer.android.com/reference/java/security/acl/package-summary.html + +http://developer.android.com/reference/java/security/cert/package-summary.html +http://developer.android.com/reference/java/security/interfaces/package-summary.html + +http://developer.android.com/reference/java/security/spec/package-summary.html +http://developer.android.com/reference/java/sql/package-summary.html + +http://developer.android.com/reference/java/text/package-summary.html +http://developer.android.com/reference/java/util/package-summary.html + +http://developer.android.com/reference/java/util/concurrent/package-summary.html +http://developer.android.com/reference/java/util/concurrent/atomic/package-summary.html + +http://developer.android.com/reference/java/util/concurrent/locks/package-summary.html +http://developer.android.com/reference/java/util/jar/package-summary.html + +http://developer.android.com/reference/java/util/logging/package-summary.html +http://developer.android.com/reference/java/util/prefs/package-summary.html + +http://developer.android.com/reference/java/util/regex/package-summary.html +http://developer.android.com/reference/java/util/zip/package-summary.html + +http://developer.android.com/reference/javax/crypto/package-summary.html +http://developer.android.com/reference/javax/crypto/interfaces/package-summary.html + +http://developer.android.com/reference/javax/crypto/spec/package-summary.html +http://developer.android.com/reference/javax/microedition/khronos/egl/package-summary.html + +http://developer.android.com/reference/javax/microedition/khronos/opengles/package-summary.html + +http://developer.android.com/reference/javax/net/package-summary.html +http://developer.android.com/reference/javax/net/ssl/package-summary.html + +http://developer.android.com/reference/javax/security/auth/package-summary.html +http://developer.android.com/reference/javax/security/auth/callback/package-summary.html + +http://developer.android.com/reference/javax/security/auth/login/package-summary.html +http://developer.android.com/reference/javax/security/auth/x500/package-summary.html + +http://developer.android.com/reference/javax/security/cert/package-summary.html +http://developer.android.com/reference/javax/sql/package-summary.html + +http://developer.android.com/reference/javax/xml/package-summary.html +http://developer.android.com/reference/javax/xml/parsers/package-summary.html + +http://developer.android.com/reference/junit/framework/package-summary.html +http://developer.android.com/reference/junit/runner/package-summary.html + +http://developer.android.com/reference/org/apache/http/package-summary.html +http://developer.android.com/reference/org/apache/http/auth/package-summary.html + +http://developer.android.com/reference/org/apache/http/auth/params/package-summary.html +http://developer.android.com/reference/org/apache/http/client/package-summary.html + +http://developer.android.com/reference/org/apache/http/client/entity/package-summary.html +http://developer.android.com/reference/org/apache/http/client/methods/package-summary.html + +http://developer.android.com/reference/org/apache/http/client/params/package-summary.html +http://developer.android.com/reference/org/apache/http/client/protocol/package-summary.html + +http://developer.android.com/reference/org/apache/http/client/utils/package-summary.html +http://developer.android.com/reference/org/apache/http/conn/package-summary.html + +http://developer.android.com/reference/org/apache/http/conn/params/package-summary.html +http://developer.android.com/reference/org/apache/http/conn/routing/package-summary.html + +http://developer.android.com/reference/org/apache/http/conn/scheme/package-summary.html +http://developer.android.com/reference/org/apache/http/conn/ssl/package-summary.html + +http://developer.android.com/reference/org/apache/http/conn/util/package-summary.html +http://developer.android.com/reference/org/apache/http/cookie/package-summary.html + +http://developer.android.com/reference/org/apache/http/cookie/params/package-summary.html +http://developer.android.com/reference/org/apache/http/entity/package-summary.html + +http://developer.android.com/reference/org/apache/http/impl/package-summary.html +http://developer.android.com/reference/org/apache/http/impl/auth/package-summary.html + +http://developer.android.com/reference/org/apache/http/impl/client/package-summary.html +http://developer.android.com/reference/org/apache/http/impl/conn/package-summary.html + +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/package-summary.html +http://developer.android.com/reference/org/apache/http/impl/cookie/package-summary.html + +http://developer.android.com/reference/org/apache/http/impl/entity/package-summary.html +http://developer.android.com/reference/org/apache/http/impl/io/package-summary.html + +http://developer.android.com/reference/org/apache/http/io/package-summary.html +http://developer.android.com/reference/org/apache/http/message/package-summary.html + +http://developer.android.com/reference/org/apache/http/params/package-summary.html +http://developer.android.com/reference/org/apache/http/protocol/package-summary.html + +http://developer.android.com/reference/org/apache/http/util/package-summary.html +http://developer.android.com/reference/org/json/package-summary.html + +http://developer.android.com/reference/org/w3c/dom/package-summary.html +http://developer.android.com/reference/org/xml/sax/package-summary.html + +http://developer.android.com/reference/org/xml/sax/ext/package-summary.html +http://developer.android.com/reference/org/xml/sax/helpers/package-summary.html + +http://developer.android.com/reference/org/xmlpull/v1/package-summary.html +http://developer.android.com/reference/org/xmlpull/v1/sax2/package-summary.html + +http://developer.android.com/reference/org/apache/http/message/AbstractHttpMessage.html +http://developer.android.com/guide/basics/what-is-android.html + +http://developer.android.com/guide/topics/fundamentals.html +http://developer.android.com/guide/topics/ui/index.html + +http://developer.android.com/guide/topics/ui/declaring-layout.html +http://developer.android.com/guide/topics/ui/menus.html + +http://developer.android.com/guide/topics/ui/layout-objects.html +http://developer.android.com/guide/topics/ui/binding.html + +http://developer.android.com/guide/topics/ui/ui-events.html +http://developer.android.com/guide/topics/ui/themes.html + +http://developer.android.com/guide/topics/ui/custom-components.html +http://developer.android.com/guide/topics/ui/how-android-draws.html + +http://developer.android.com/guide/topics/resources/index.html +http://developer.android.com/guide/topics/resources/resources-i18n.html + +http://developer.android.com/guide/topics/resources/available-resources.html +http://developer.android.com/guide/topics/intents/intents-filters.html + +http://developer.android.com/guide/topics/data/data-storage.html +http://developer.android.com/guide/topics/providers/content-providers.html + +http://developer.android.com/guide/topics/security/security.html +http://developer.android.com/guide/topics/manifest/manifest-intro.html + +http://developer.android.com/guide/topics/manifest/action-element.html +http://developer.android.com/guide/topics/manifest/activity-element.html + +http://developer.android.com/guide/topics/manifest/activity-alias-element.html +http://developer.android.com/guide/topics/manifest/application-element.html + +http://developer.android.com/guide/topics/manifest/category-element.html +http://developer.android.com/guide/topics/manifest/data-element.html + +http://developer.android.com/guide/topics/manifest/grant-uri-permission-element.html +http://developer.android.com/guide/topics/manifest/instrumentation-element.html + +http://developer.android.com/guide/topics/manifest/intent-filter-element.html +http://developer.android.com/guide/topics/manifest/manifest-element.html + +http://developer.android.com/guide/topics/manifest/meta-data-element.html +http://developer.android.com/guide/topics/manifest/permission-element.html + +http://developer.android.com/guide/topics/manifest/permission-group-element.html +http://developer.android.com/guide/topics/manifest/permission-tree-element.html + +http://developer.android.com/guide/topics/manifest/provider-element.html +http://developer.android.com/guide/topics/manifest/receiver-element.html + +http://developer.android.com/guide/topics/manifest/service-element.html +http://developer.android.com/guide/topics/manifest/uses-library-element.html + +http://developer.android.com/guide/topics/manifest/uses-permission-element.html +http://developer.android.com/guide/topics/manifest/uses-sdk-element.html + +http://developer.android.com/guide/topics/graphics/index.html +http://developer.android.com/guide/topics/graphics/2d-graphics.html + +http://developer.android.com/guide/topics/graphics/opengl.html +http://developer.android.com/guide/topics/media/index.html + +http://developer.android.com/guide/topics/location/index.html +http://developer.android.com/guide/developing/eclipse-adt.html + +http://developer.android.com/guide/developing/other-ide.html +http://developer.android.com/guide/developing/device.html + +http://developer.android.com/guide/developing/debug-tasks.html +http://developer.android.com/guide/developing/tools/aapt.html + +http://developer.android.com/guide/developing/tools/adb.html +http://developer.android.com/guide/developing/tools/othertools.html + +http://developer.android.com/guide/developing/tools/aidl.html +http://developer.android.com/guide/developing/tools/ddms.html + +http://developer.android.com/guide/developing/tools/draw9patch.html +http://developer.android.com/guide/developing/tools/emulator.html + +http://developer.android.com/guide/developing/tools/hierarchy-viewer.html +http://developer.android.com/guide/developing/tools/monkey.html + +http://developer.android.com/guide/developing/tools/traceview.html +http://developer.android.com/guide/publishing/app-signing.html + +http://developer.android.com/guide/publishing/versioning.html +http://developer.android.com/guide/publishing/preparing.html + +http://developer.android.com/guide/publishing/publishing.html +http://developer.android.com/guide/practices/design/performance.html + +http://developer.android.com/guide/practices/design/responsiveness.html +http://developer.android.com/guide/practices/design/seamlessness.html + +http://developer.android.com/guide/tutorials/hello-world.html +http://developer.android.com/guide/tutorials/views/index.html + +http://developer.android.com/guide/tutorials/notepad/index.html +http://developer.android.com/guide/samples/ApiDemos/index.html + +http://developer.android.com/guide/samples/LunarLander/index.html +http://developer.android.com/guide/samples/NotePad/index.html + +http://developer.android.com/guide/appendix/media-formats.html +http://developer.android.com/guide/appendix/g-app-intents.html + +http://developer.android.com/guide/appendix/glossary.html +http://developer.android.com/guide/appendix/faq/commontasks.html + +http://developer.android.com/guide/appendix/faq/framework.html +http://developer.android.com/guide/appendix/faq/troubleshooting.html + +http://developer.android.com/guide/appendix/faq/licensingandoss.html +http://developer.android.com/guide/appendix/faq/security.html + +http://developer.android.com/reference/org/apache/http/impl/client/AbstractAuthenticationHandler.html + +http://developer.android.com/reference/org/apache/http/impl/client/AbstractHttpClient.html +http://developer.android.com/reference/org/apache/http/impl/client/BasicCookieStore.html + +http://developer.android.com/reference/org/apache/http/impl/client/BasicCredentialsProvider.html + +http://developer.android.com/reference/org/apache/http/impl/client/BasicResponseHandler.html +http://developer.android.com/reference/org/apache/http/impl/client/ClientParamsStack.html + +http://developer.android.com/reference/org/apache/http/impl/client/DefaultConnectionKeepAliveStrategy.html + +http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html +http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpRequestRetryHandler.html + +http://developer.android.com/reference/org/apache/http/impl/client/DefaultProxyAuthenticationHandler.html + +http://developer.android.com/reference/org/apache/http/impl/client/DefaultRedirectHandler.html + +http://developer.android.com/reference/org/apache/http/impl/client/DefaultRequestDirector.html + +http://developer.android.com/reference/org/apache/http/impl/client/DefaultTargetAuthenticationHandler.html + +http://developer.android.com/reference/org/apache/http/impl/client/DefaultUserTokenHandler.html + +http://developer.android.com/reference/org/apache/http/impl/client/EntityEnclosingRequestWrapper.html + +http://developer.android.com/reference/org/apache/http/impl/client/RedirectLocations.html +http://developer.android.com/reference/org/apache/http/impl/client/RequestWrapper.html + +http://developer.android.com/reference/org/apache/http/impl/client/RoutedRequest.html +http://developer.android.com/reference/org/apache/http/impl/client/TunnelRefusedException.html + +http://developer.android.com/reference/org/apache/http/client/CookieStore.html +http://developer.android.com/reference/org/apache/http/client/CredentialsProvider.html + +http://developer.android.com/reference/org/apache/http/client/ResponseHandler.html +http://developer.android.com/reference/org/apache/http/client/HttpRequestRetryHandler.html + +http://developer.android.com/reference/org/apache/http/client/RedirectHandler.html +http://developer.android.com/reference/org/apache/http/client/RequestDirector.html + +http://developer.android.com/reference/org/apache/http/HttpEntityEnclosingRequest.html +http://developer.android.com/reference/org/apache/http/HttpRequest.html + +http://developer.android.com/reference/android/Manifest.html +http://developer.android.com/reference/android/Manifest.permission.html + +http://developer.android.com/reference/android/Manifest.permission_group.html +http://developer.android.com/reference/android/R.html + +http://developer.android.com/reference/android/R.anim.html +http://developer.android.com/reference/android/R.array.html + +http://developer.android.com/reference/android/R.attr.html +http://developer.android.com/reference/android/R.color.html + +http://developer.android.com/reference/android/R.dimen.html +http://developer.android.com/reference/android/R.drawable.html + +http://developer.android.com/reference/android/R.id.html +http://developer.android.com/reference/android/R.layout.html + +http://developer.android.com/reference/android/R.plurals.html +http://developer.android.com/reference/android/R.raw.html + +http://developer.android.com/reference/android/R.string.html +http://developer.android.com/reference/android/R.style.html + +http://developer.android.com/reference/android/R.styleable.html +http://developer.android.com/reference/android/R.xml.html + +http://developer.android.com/reference/android/package-descr.html +http://developer.android.com/reference/android/os/Debug.html + +http://developer.android.com/reference/java/security/acl/Acl.html +http://developer.android.com/reference/java/security/acl/AclEntry.html + +http://developer.android.com/reference/java/security/acl/Group.html +http://developer.android.com/reference/java/security/acl/Owner.html + +http://developer.android.com/reference/java/security/acl/Permission.html +http://developer.android.com/reference/java/security/acl/AclNotFoundException.html + +http://developer.android.com/reference/java/security/acl/LastOwnerException.html +http://developer.android.com/reference/java/security/acl/NotOwnerException.html + +http://developer.android.com/reference/java/security/acl/package-descr.html +http://developer.android.com/reference/java/text/AttributedCharacterIterator.html + +http://developer.android.com/reference/java/text/CharacterIterator.html +http://developer.android.com/reference/java/text/Annotation.html + +http://developer.android.com/reference/java/text/AttributedCharacterIterator.Attribute.html +http://developer.android.com/reference/java/text/AttributedString.html + +http://developer.android.com/reference/java/text/Bidi.html +http://developer.android.com/reference/java/text/BreakIterator.html + +http://developer.android.com/reference/java/text/ChoiceFormat.html +http://developer.android.com/reference/java/text/CollationElementIterator.html + +http://developer.android.com/reference/java/text/CollationKey.html +http://developer.android.com/reference/java/text/Collator.html + +http://developer.android.com/reference/java/text/DateFormat.html +http://developer.android.com/reference/java/text/DateFormat.Field.html + +http://developer.android.com/reference/java/text/DateFormatSymbols.html +http://developer.android.com/reference/java/text/DecimalFormat.html + +http://developer.android.com/reference/java/text/DecimalFormatSymbols.html +http://developer.android.com/reference/java/text/FieldPosition.html + +http://developer.android.com/reference/java/text/Format.html +http://developer.android.com/reference/java/text/Format.Field.html + +http://developer.android.com/reference/java/text/MessageFormat.html +http://developer.android.com/reference/java/text/MessageFormat.Field.html + +http://developer.android.com/reference/java/text/NumberFormat.html +http://developer.android.com/reference/java/text/NumberFormat.Field.html + +http://developer.android.com/reference/java/text/ParsePosition.html +http://developer.android.com/reference/java/text/RuleBasedCollator.html + +http://developer.android.com/reference/java/text/SimpleDateFormat.html +http://developer.android.com/reference/java/text/StringCharacterIterator.html + +http://developer.android.com/reference/java/text/ParseException.html +http://developer.android.com/reference/java/text/package-descr.html + +http://developer.android.com/reference/android/view/Menu.html +http://developer.android.com/reference/android/view/ContextMenu.html + +http://developer.android.com/reference/android/view/SubMenu.html +http://developer.android.com/reference/android/app/Activity.html + +http://developer.android.com/reference/android/view/MenuItem.html +http://developer.android.com/reference/android/widget/ListView.html + +http://developer.android.com/reference/android/view/View.html +http://developer.android.com/reference/android/view/ContextMenu.ContextMenuInfo.html + +http://developer.android.com/reference/android/widget/AdapterView.AdapterContextMenuInfo.html + +http://developer.android.com/reference/android/app/ListActivity.html +http://developer.android.com/reference/android/view/MenuInflater.html + +http://developer.android.com/reference/android/preference/PreferenceActivity.html +http://developer.android.com/reference/android/media/MediaPlayer.html + +http://developer.android.com/reference/android/media/MediaRecorder.html +http://developer.android.com/reference/android/content/ContentValues.html + +http://developer.android.com/reference/android/content/ContentResolver.html +http://developer.android.com/reference/android/test/PerformanceTestCase.html + +http://developer.android.com/reference/android/test/PerformanceTestCase.Intermediates.html +http://developer.android.com/reference/android/test/TestSuiteProvider.html + +http://developer.android.com/reference/android/test/ActivityInstrumentationTestCase.html +http://developer.android.com/reference/android/test/ActivityTestCase.html + +http://developer.android.com/reference/android/test/ActivityUnitTestCase.html +http://developer.android.com/reference/android/test/AndroidTestCase.html + +http://developer.android.com/reference/android/test/AndroidTestRunner.html +http://developer.android.com/reference/android/test/ApplicationTestCase.html + +http://developer.android.com/reference/android/app/Application.html +http://developer.android.com/reference/android/test/InstrumentationTestCase.html + +http://developer.android.com/reference/android/test/InstrumentationTestRunner.html +http://developer.android.com/reference/android/test/InstrumentationTestSuite.html + +http://developer.android.com/reference/android/test/IsolatedContext.html +http://developer.android.com/reference/android/test/MoreAsserts.html + +http://developer.android.com/reference/android/test/ProviderTestCase.html +http://developer.android.com/reference/android/content/ContentProvider.html + +http://developer.android.com/reference/android/test/RenamingDelegatingContext.html +http://developer.android.com/reference/android/test/ServiceTestCase.html + +http://developer.android.com/reference/android/app/Service.html +http://developer.android.com/reference/android/test/SingleLaunchActivityTestCase.html + +http://developer.android.com/reference/android/test/SyncBaseInstrumentation.html +http://developer.android.com/reference/android/test/TouchUtils.html + +http://developer.android.com/reference/android/test/ViewAsserts.html +http://developer.android.com/reference/android/test/AssertionFailedError.html + +http://developer.android.com/reference/android/test/ComparisonFailure.html +http://developer.android.com/reference/android/app/Instrumentation.html + +http://developer.android.com/reference/junit/framework/TestCase.html +http://developer.android.com/reference/junit/framework/TestSuite.html + +http://developer.android.com/reference/android/content/Intent.html +http://developer.android.com/reference/android/content/Context.html + +http://developer.android.com/reference/android/os/Bundle.html +http://developer.android.com/reference/android/view/ViewGroup.html + +http://developer.android.com/reference/android/widget/Button.html +http://developer.android.com/reference/android/widget/TextView.html + +http://developer.android.com/reference/android/widget/EditText.html +http://developer.android.com/reference/android/widget/CheckBox.html + +http://developer.android.com/reference/android/widget/RadioButton.html +http://developer.android.com/reference/android/widget/Gallery.html + +http://developer.android.com/reference/android/widget/Spinner.html +http://developer.android.com/reference/android/widget/AutoCompleteTextView.html + +http://developer.android.com/reference/android/widget/ImageSwitcher.html +http://developer.android.com/reference/android/widget/TextSwitcher.html + +http://developer.android.com/reference/android/widget/LinearLayout.html +http://developer.android.com/reference/android/widget/FrameLayout.html + +http://developer.android.com/reference/android/widget/AbsoluteLayout.html +http://developer.android.com/reference/android/graphics/Canvas.html + +http://developer.android.com/reference/android/view/SurfaceView.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LabelView.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/custom_view_1.html +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/NoteEditor.html + +http://developer.android.com/reference/java/net/ContentHandlerFactory.html +http://developer.android.com/reference/java/net/DatagramSocketImplFactory.html + +http://developer.android.com/reference/java/net/FileNameMap.html +http://developer.android.com/reference/java/net/SocketImplFactory.html + +http://developer.android.com/reference/java/net/SocketOptions.html +http://developer.android.com/reference/java/net/URLStreamHandlerFactory.html + +http://developer.android.com/reference/java/net/Authenticator.html +http://developer.android.com/reference/java/net/CacheRequest.html + +http://developer.android.com/reference/java/net/CacheResponse.html +http://developer.android.com/reference/java/net/ContentHandler.html + +http://developer.android.com/reference/java/net/CookieHandler.html +http://developer.android.com/reference/java/net/DatagramPacket.html + +http://developer.android.com/reference/java/net/DatagramSocket.html +http://developer.android.com/reference/java/net/DatagramSocketImpl.html + +http://developer.android.com/reference/java/net/HttpURLConnection.html +http://developer.android.com/reference/java/net/Inet4Address.html + +http://developer.android.com/reference/java/net/Inet6Address.html +http://developer.android.com/reference/java/net/InetAddress.html + +http://developer.android.com/reference/java/net/InetSocketAddress.html +http://developer.android.com/reference/java/net/JarURLConnection.html + +http://developer.android.com/reference/java/net/MulticastSocket.html +http://developer.android.com/reference/java/net/NetPermission.html + +http://developer.android.com/reference/java/net/NetworkInterface.html +http://developer.android.com/reference/java/net/PasswordAuthentication.html + +http://developer.android.com/reference/java/net/Proxy.html +http://developer.android.com/reference/java/net/ProxySelector.html + +http://developer.android.com/reference/java/net/ResponseCache.html +http://developer.android.com/reference/java/net/SecureCacheResponse.html + +http://developer.android.com/reference/java/net/ServerSocket.html +http://developer.android.com/reference/java/net/Socket.html + +http://developer.android.com/reference/java/net/SocketAddress.html +http://developer.android.com/reference/java/net/SocketImpl.html + +http://developer.android.com/reference/java/net/SocketPermission.html +http://developer.android.com/reference/java/net/URI.html + +http://developer.android.com/reference/java/net/URL.html +http://developer.android.com/reference/java/net/URLClassLoader.html + +http://developer.android.com/reference/java/net/URLConnection.html +http://developer.android.com/reference/java/net/URLDecoder.html + +http://developer.android.com/reference/java/net/URLEncoder.html +http://developer.android.com/reference/java/net/URLStreamHandler.html + +http://developer.android.com/reference/java/net/Authenticator.RequestorType.html +http://developer.android.com/reference/java/net/Proxy.Type.html + +http://developer.android.com/reference/java/net/BindException.html +http://developer.android.com/reference/java/net/ConnectException.html + +http://developer.android.com/reference/java/net/HttpRetryException.html +http://developer.android.com/reference/java/net/MalformedURLException.html + +http://developer.android.com/reference/java/net/NoRouteToHostException.html +http://developer.android.com/reference/java/net/PortUnreachableException.html + +http://developer.android.com/reference/java/net/ProtocolException.html +http://developer.android.com/reference/java/net/SocketException.html + +http://developer.android.com/reference/java/net/SocketTimeoutException.html +http://developer.android.com/reference/java/net/UnknownHostException.html + +http://developer.android.com/reference/java/net/UnknownServiceException.html +http://developer.android.com/reference/java/net/URISyntaxException.html + +http://developer.android.com/reference/java/net/package-descr.html +http://developer.android.com/reference/android/graphics/drawable/Drawable.html + +http://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html +http://developer.android.com/reference/android/graphics/drawable/ShapeDrawable.html + +http://developer.android.com/reference/android/graphics/drawable/PictureDrawable.html +http://developer.android.com/reference/android/graphics/drawable/LayerDrawable.html + +http://developer.android.com/reference/android/widget/ImageView.html +http://developer.android.com/reference/android/content/res/Resources.html + +http://developer.android.com/reference/android/graphics/drawable/shapes/OvalShape.html +http://developer.android.com/reference/android/graphics/drawable/NinePatchDrawable.html + +http://developer.android.com/reference/android/view/animation/AnimationSet.html +http://developer.android.com/reference/android/view/animation/Animation.html + +http://developer.android.com/reference/android/view/animation/Interpolator.html +http://developer.android.com/reference/android/view/animation/AccelerateInterpolator.html + +http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html +http://developer.android.com/reference/java/util/logging/Filter.html + +http://developer.android.com/reference/java/util/logging/LoggingMXBean.html +http://developer.android.com/reference/java/util/logging/ConsoleHandler.html + +http://developer.android.com/reference/java/util/logging/ErrorManager.html +http://developer.android.com/reference/java/util/logging/FileHandler.html + +http://developer.android.com/reference/java/util/logging/Formatter.html +http://developer.android.com/reference/java/util/logging/Handler.html + +http://developer.android.com/reference/java/util/logging/Level.html +http://developer.android.com/reference/java/util/logging/Logger.html + +http://developer.android.com/reference/java/util/logging/LoggingPermission.html +http://developer.android.com/reference/java/util/logging/LogManager.html + +http://developer.android.com/reference/java/util/logging/LogRecord.html +http://developer.android.com/reference/java/util/logging/MemoryHandler.html + +http://developer.android.com/reference/java/util/logging/SimpleFormatter.html +http://developer.android.com/reference/java/util/logging/SocketHandler.html + +http://developer.android.com/reference/java/util/logging/StreamHandler.html +http://developer.android.com/reference/java/util/logging/XMLFormatter.html + +http://developer.android.com/reference/java/util/logging/package-descr.html +http://developer.android.com/reference/android/test/suitebuilder/annotation/LargeTest.html +http://developer.android.com/reference/android/test/suitebuilder/annotation/MediumTest.html + +http://developer.android.com/reference/android/test/suitebuilder/annotation/SmallTest.html +http://developer.android.com/reference/android/os/Process.html + +http://developer.android.com/reference/android/graphics/AvoidXfermode.html +http://developer.android.com/reference/android/graphics/Bitmap.html + +http://developer.android.com/reference/android/graphics/BitmapFactory.html +http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html + +http://developer.android.com/reference/android/graphics/BitmapShader.html +http://developer.android.com/reference/android/graphics/BlurMaskFilter.html + +http://developer.android.com/reference/android/graphics/Camera.html +http://developer.android.com/reference/android/graphics/Color.html + +http://developer.android.com/reference/android/graphics/ColorFilter.html +http://developer.android.com/reference/android/graphics/ColorMatrix.html + +http://developer.android.com/reference/android/graphics/ColorMatrixColorFilter.html +http://developer.android.com/reference/android/graphics/ComposePathEffect.html + +http://developer.android.com/reference/android/graphics/ComposeShader.html +http://developer.android.com/reference/android/graphics/CornerPathEffect.html + +http://developer.android.com/reference/android/graphics/DashPathEffect.html +http://developer.android.com/reference/android/graphics/DiscretePathEffect.html + +http://developer.android.com/reference/android/graphics/DrawFilter.html +http://developer.android.com/reference/android/graphics/EmbossMaskFilter.html + +http://developer.android.com/reference/android/graphics/Interpolator.html +http://developer.android.com/reference/android/graphics/LayerRasterizer.html + +http://developer.android.com/reference/android/graphics/LightingColorFilter.html +http://developer.android.com/reference/android/graphics/LinearGradient.html + +http://developer.android.com/reference/android/graphics/MaskFilter.html +http://developer.android.com/reference/android/graphics/Matrix.html + +http://developer.android.com/reference/android/graphics/Movie.html +http://developer.android.com/reference/android/graphics/NinePatch.html + +http://developer.android.com/reference/android/graphics/Paint.html +http://developer.android.com/reference/android/graphics/Paint.FontMetrics.html + +http://developer.android.com/reference/android/graphics/Paint.FontMetricsInt.html +http://developer.android.com/reference/android/graphics/PaintFlagsDrawFilter.html + +http://developer.android.com/reference/android/graphics/Path.html +http://developer.android.com/reference/android/graphics/PathDashPathEffect.html + +http://developer.android.com/reference/android/graphics/PathEffect.html +http://developer.android.com/reference/android/graphics/PathMeasure.html + +http://developer.android.com/reference/android/graphics/Picture.html +http://developer.android.com/reference/android/graphics/PixelFormat.html + +http://developer.android.com/reference/android/graphics/PixelXorXfermode.html +http://developer.android.com/reference/android/graphics/Point.html + +http://developer.android.com/reference/android/graphics/PointF.html +http://developer.android.com/reference/android/graphics/PorterDuff.html + +http://developer.android.com/reference/android/graphics/PorterDuffColorFilter.html +http://developer.android.com/reference/android/graphics/PorterDuffXfermode.html + +http://developer.android.com/reference/android/graphics/RadialGradient.html +http://developer.android.com/reference/android/graphics/Rasterizer.html + +http://developer.android.com/reference/android/graphics/Rect.html +http://developer.android.com/reference/android/graphics/RectF.html + +http://developer.android.com/reference/android/graphics/Region.html +http://developer.android.com/reference/android/graphics/RegionIterator.html + +http://developer.android.com/reference/android/graphics/Shader.html +http://developer.android.com/reference/android/graphics/SumPathEffect.html + +http://developer.android.com/reference/android/graphics/SweepGradient.html +http://developer.android.com/reference/android/graphics/Typeface.html + +http://developer.android.com/reference/android/graphics/Xfermode.html +http://developer.android.com/reference/android/graphics/AvoidXfermode.Mode.html + +http://developer.android.com/reference/android/graphics/Bitmap.CompressFormat.html +http://developer.android.com/reference/android/graphics/Bitmap.Config.html + +http://developer.android.com/reference/android/graphics/BlurMaskFilter.Blur.html +http://developer.android.com/reference/android/graphics/Canvas.EdgeType.html + +http://developer.android.com/reference/android/graphics/Canvas.VertexMode.html +http://developer.android.com/reference/android/graphics/Interpolator.Result.html + +http://developer.android.com/reference/android/graphics/Matrix.ScaleToFit.html +http://developer.android.com/reference/android/graphics/Paint.Align.html + +http://developer.android.com/reference/android/graphics/Paint.Cap.html +http://developer.android.com/reference/android/graphics/Paint.Join.html + +http://developer.android.com/reference/android/graphics/Paint.Style.html +http://developer.android.com/reference/android/graphics/Path.Direction.html + +http://developer.android.com/reference/android/graphics/Path.FillType.html +http://developer.android.com/reference/android/graphics/PathDashPathEffect.Style.html + +http://developer.android.com/reference/android/graphics/PorterDuff.Mode.html +http://developer.android.com/reference/android/graphics/Region.Op.html + +http://developer.android.com/reference/android/graphics/Shader.TileMode.html +http://developer.android.com/reference/android/graphics/package-descr.html + +http://developer.android.com/reference/android/content/BroadcastReceiver.html +http://developer.android.com/reference/org/apache/http/cookie/ClientCookie.html + +http://developer.android.com/reference/org/apache/http/cookie/Cookie.html +http://developer.android.com/reference/org/apache/http/cookie/CookieAttributeHandler.html + +http://developer.android.com/reference/org/apache/http/cookie/CookieSpec.html +http://developer.android.com/reference/org/apache/http/cookie/CookieSpecFactory.html + +http://developer.android.com/reference/org/apache/http/cookie/SetCookie.html +http://developer.android.com/reference/org/apache/http/cookie/SetCookie2.html + +http://developer.android.com/reference/org/apache/http/cookie/SM.html +http://developer.android.com/reference/org/apache/http/cookie/CookieIdentityComparator.html + +http://developer.android.com/reference/org/apache/http/cookie/CookieOrigin.html +http://developer.android.com/reference/org/apache/http/cookie/CookiePathComparator.html + +http://developer.android.com/reference/org/apache/http/cookie/CookieSpecRegistry.html +http://developer.android.com/reference/org/apache/http/cookie/MalformedCookieException.html + +http://developer.android.com/reference/org/apache/http/cookie/package-descr.html +http://developer.android.com/reference/java/nio/channels/spi/AbstractInterruptibleChannel.html + +http://developer.android.com/reference/java/nio/channels/spi/AbstractSelectableChannel.html +http://developer.android.com/reference/java/nio/channels/spi/AbstractSelectionKey.html + +http://developer.android.com/reference/java/nio/channels/spi/AbstractSelector.html +http://developer.android.com/reference/java/nio/channels/spi/SelectorProvider.html + +http://developer.android.com/reference/java/nio/channels/spi/package-descr.html +http://developer.android.com/reference/org/apache/http/client/AuthenticationHandler.html + +http://developer.android.com/reference/org/apache/http/client/HttpClient.html +http://developer.android.com/reference/org/apache/http/client/UserTokenHandler.html + +http://developer.android.com/reference/org/apache/http/client/CircularRedirectException.html +http://developer.android.com/reference/org/apache/http/client/ClientProtocolException.html + +http://developer.android.com/reference/org/apache/http/client/HttpResponseException.html +http://developer.android.com/reference/org/apache/http/client/NonRepeatableRequestException.html + +http://developer.android.com/reference/org/apache/http/client/RedirectException.html +http://developer.android.com/reference/org/apache/http/client/package-descr.html + +http://developer.android.com/reference/org/apache/http/HttpResponse.html +http://developer.android.com/reference/java/util/prefs/NodeChangeListener.html + +http://developer.android.com/reference/java/util/prefs/PreferenceChangeListener.html +http://developer.android.com/reference/java/util/prefs/PreferencesFactory.html + +http://developer.android.com/reference/java/util/prefs/AbstractPreferences.html +http://developer.android.com/reference/java/util/prefs/NodeChangeEvent.html + +http://developer.android.com/reference/java/util/prefs/PreferenceChangeEvent.html +http://developer.android.com/reference/java/util/prefs/Preferences.html + +http://developer.android.com/reference/java/util/prefs/BackingStoreException.html +http://developer.android.com/reference/java/util/prefs/InvalidPreferencesFormatException.html + +http://developer.android.com/reference/java/util/prefs/package-descr.html +http://developer.android.com/sdk/adt_download.html +http://developer.android.com/reference/android/provider/BaseColumns.html + +http://developer.android.com/reference/android/provider/Contacts.ContactMethodsColumns.html +http://developer.android.com/reference/android/provider/Contacts.ExtensionsColumns.html + +http://developer.android.com/reference/android/provider/Contacts.GroupsColumns.html +http://developer.android.com/reference/android/provider/Contacts.OrganizationColumns.html + +http://developer.android.com/reference/android/provider/Contacts.PeopleColumns.html +http://developer.android.com/reference/android/provider/Contacts.PhonesColumns.html + +http://developer.android.com/reference/android/provider/Contacts.PhotosColumns.html +http://developer.android.com/reference/android/provider/Contacts.PresenceColumns.html + +http://developer.android.com/reference/android/provider/Contacts.SettingsColumns.html +http://developer.android.com/reference/android/provider/MediaStore.Audio.AlbumColumns.html + +http://developer.android.com/reference/android/provider/MediaStore.Audio.ArtistColumns.html +http://developer.android.com/reference/android/provider/MediaStore.Audio.AudioColumns.html + +http://developer.android.com/reference/android/provider/MediaStore.Audio.GenresColumns.html +http://developer.android.com/reference/android/provider/MediaStore.Audio.PlaylistsColumns.html + +http://developer.android.com/reference/android/provider/MediaStore.Images.ImageColumns.html +http://developer.android.com/reference/android/provider/MediaStore.MediaColumns.html + +http://developer.android.com/reference/android/provider/MediaStore.Video.VideoColumns.html +http://developer.android.com/reference/android/provider/OpenableColumns.html + +http://developer.android.com/reference/android/provider/Browser.html +http://developer.android.com/reference/android/provider/Browser.BookmarkColumns.html + +http://developer.android.com/reference/android/provider/Browser.SearchColumns.html +http://developer.android.com/reference/android/provider/CallLog.html + +http://developer.android.com/reference/android/provider/CallLog.Calls.html +http://developer.android.com/reference/android/provider/Contacts.html + +http://developer.android.com/reference/android/provider/Contacts.ContactMethods.html +http://developer.android.com/reference/android/provider/Contacts.Extensions.html + +http://developer.android.com/reference/android/provider/Contacts.GroupMembership.html +http://developer.android.com/reference/android/provider/Contacts.Groups.html + +http://developer.android.com/reference/android/provider/Contacts.Intents.html +http://developer.android.com/reference/android/provider/Contacts.Intents.Insert.html + +http://developer.android.com/reference/android/provider/Contacts.Intents.UI.html +http://developer.android.com/reference/android/provider/Contacts.Organizations.html + +http://developer.android.com/reference/android/provider/Contacts.People.html +http://developer.android.com/reference/android/provider/Contacts.People.ContactMethods.html + +http://developer.android.com/reference/android/provider/Contacts.People.Extensions.html +http://developer.android.com/reference/android/provider/Contacts.People.Phones.html + +http://developer.android.com/reference/android/provider/Contacts.Phones.html +http://developer.android.com/reference/android/provider/Contacts.Photos.html + +http://developer.android.com/reference/android/provider/Contacts.Settings.html +http://developer.android.com/reference/android/provider/MediaStore.html + +http://developer.android.com/reference/android/provider/MediaStore.Audio.html +http://developer.android.com/reference/android/provider/MediaStore.Audio.Albums.html + +http://developer.android.com/reference/android/provider/MediaStore.Audio.Artists.html +http://developer.android.com/reference/android/provider/MediaStore.Audio.Artists.Albums.html + +http://developer.android.com/reference/android/provider/MediaStore.Audio.Genres.html +http://developer.android.com/reference/android/provider/MediaStore.Audio.Genres.Members.html + +http://developer.android.com/reference/android/provider/MediaStore.Audio.Media.html +http://developer.android.com/reference/android/provider/MediaStore.Audio.Playlists.html + +http://developer.android.com/reference/android/provider/MediaStore.Audio.Playlists.Members.html + +http://developer.android.com/reference/android/provider/MediaStore.Images.html +http://developer.android.com/reference/android/provider/MediaStore.Images.Media.html + +http://developer.android.com/reference/android/provider/MediaStore.Images.Thumbnails.html +http://developer.android.com/reference/android/provider/MediaStore.Video.html + +http://developer.android.com/reference/android/provider/MediaStore.Video.Media.html +http://developer.android.com/reference/android/provider/SearchRecentSuggestions.html + +http://developer.android.com/reference/android/provider/Settings.html +http://developer.android.com/reference/android/provider/Settings.NameValueTable.html + +http://developer.android.com/reference/android/provider/Settings.System.html +http://developer.android.com/reference/android/provider/Settings.SettingNotFoundException.html + +http://developer.android.com/reference/android/provider/package-descr.html +http://developer.android.com/reference/android/content/SearchRecentSuggestionsProvider.html + +http://developer.android.com/reference/android/net/UrlQuerySanitizer.ValueSanitizer.html +http://developer.android.com/reference/android/net/ConnectivityManager.html + +http://developer.android.com/reference/android/net/Credentials.html +http://developer.android.com/reference/android/net/DhcpInfo.html + +http://developer.android.com/reference/android/net/LocalServerSocket.html +http://developer.android.com/reference/android/net/LocalSocket.html + +http://developer.android.com/reference/android/net/LocalSocketAddress.html +http://developer.android.com/reference/android/net/MailTo.html + +http://developer.android.com/reference/android/net/NetworkInfo.html +http://developer.android.com/reference/android/net/Proxy.html + +http://developer.android.com/reference/android/net/SSLCertificateSocketFactory.html +http://developer.android.com/reference/android/net/Uri.html + +http://developer.android.com/reference/android/net/Uri.Builder.html +http://developer.android.com/reference/android/net/UrlQuerySanitizer.html + +http://developer.android.com/reference/android/net/UrlQuerySanitizer.IllegalCharacterValueSanitizer.html + +http://developer.android.com/reference/android/net/UrlQuerySanitizer.ParameterValuePair.html +http://developer.android.com/reference/android/net/LocalSocketAddress.Namespace.html + +http://developer.android.com/reference/android/net/NetworkInfo.DetailedState.html +http://developer.android.com/reference/android/net/NetworkInfo.State.html + +http://developer.android.com/reference/android/net/package-descr.html +http://developer.android.com/reference/javax/microedition/khronos/egl/EGL.html + +http://developer.android.com/reference/javax/microedition/khronos/egl/EGL10.html +http://developer.android.com/reference/javax/microedition/khronos/egl/EGL11.html + +http://developer.android.com/reference/javax/microedition/khronos/egl/EGLConfig.html +http://developer.android.com/reference/javax/microedition/khronos/egl/EGLContext.html + +http://developer.android.com/reference/javax/microedition/khronos/egl/EGLDisplay.html +http://developer.android.com/reference/javax/microedition/khronos/egl/EGLSurface.html + +http://developer.android.com/reference/android/content/pm/PackageItemInfo.html +http://developer.android.com/reference/org/apache/http/auth/params/AuthPNames.html + +http://developer.android.com/reference/org/apache/http/auth/params/AuthParamBean.html +http://developer.android.com/reference/org/apache/http/auth/params/AuthParams.html + +http://developer.android.com/reference/org/apache/http/auth/params/package-descr.html +http://developer.android.com/reference/org/apache/http/params/HttpParams.html + +http://developer.android.com/reference/java/lang/Object.html +http://developer.android.com/reference/org/apache/http/conn/ConnectionKeepAliveStrategy.html + +http://developer.android.com/reference/org/apache/http/protocol/HttpContext.html +http://developer.android.com/reference/java/lang/Class.html + +http://developer.android.com/reference/java/lang/String.html +http://developer.android.com/reference/org/apache/http/ConnectionReuseStrategy.html + +http://developer.android.com/reference/org/xml/sax/ext/Attributes2.html +http://developer.android.com/reference/org/xml/sax/ext/DeclHandler.html + +http://developer.android.com/reference/org/xml/sax/ext/EntityResolver2.html +http://developer.android.com/reference/org/xml/sax/ext/LexicalHandler.html + +http://developer.android.com/reference/org/xml/sax/ext/Locator2.html +http://developer.android.com/reference/org/xml/sax/ext/Attributes2Impl.html + +http://developer.android.com/reference/org/xml/sax/ext/DefaultHandler2.html +http://developer.android.com/reference/org/xml/sax/ext/Locator2Impl.html + +http://developer.android.com/reference/org/xml/sax/ext/package-descr.html +http://developer.android.com/reference/org/xml/sax/Attributes.html + +http://developer.android.com/reference/org/xml/sax/Locator.html +http://developer.android.com/reference/android/content/pm/PackageManager.html + +http://developer.android.com/reference/org/apache/http/HttpHost.html + +http://developer.android.com/reference/org/apache/http/HttpException.html +http://developer.android.com/reference/java/io/IOException.html + +http://developer.android.com/reference/javax/security/auth/x500/X500Principal.html +http://developer.android.com/reference/javax/security/auth/x500/package-descr.html + +http://developer.android.com/reference/java/util/Date.html +http://developer.android.com/reference/java/util/List.html + +http://developer.android.com/reference/android/sax/ElementListener.html +http://developer.android.com/reference/android/sax/EndElementListener.html + +http://developer.android.com/reference/android/sax/EndTextElementListener.html +http://developer.android.com/reference/android/sax/StartElementListener.html + +http://developer.android.com/reference/android/sax/TextElementListener.html +http://developer.android.com/reference/android/sax/Element.html + +http://developer.android.com/reference/android/sax/RootElement.html +http://developer.android.com/reference/android/sax/package-descr.html + +http://developer.android.com/reference/junit/runner/BaseTestRunner.html +http://developer.android.com/reference/junit/framework/TestListener.html + +http://developer.android.com/reference/junit/framework/TestResult.html +http://developer.android.com/reference/junit/framework/Test.html + +http://developer.android.com/reference/java/lang/Throwable.html +http://developer.android.com/reference/junit/framework/AssertionFailedError.html + +http://developer.android.com/reference/junit/runner/TestSuiteLoader.html +http://developer.android.com/reference/java/util/Properties.html + +http://developer.android.com/reference/java/lang/ClassNotFoundException.html +http://developer.android.com/reference/org/apache/http/impl/io/AbstractMessageParser.html + +http://developer.android.com/reference/org/apache/http/impl/io/AbstractMessageWriter.html +http://developer.android.com/reference/org/apache/http/impl/io/AbstractSessionInputBuffer.html + +http://developer.android.com/reference/org/apache/http/impl/io/AbstractSessionOutputBuffer.html + +http://developer.android.com/reference/org/apache/http/impl/io/ChunkedInputStream.html +http://developer.android.com/reference/org/apache/http/impl/io/ChunkedOutputStream.html + +http://developer.android.com/reference/org/apache/http/impl/io/ContentLengthInputStream.html +http://developer.android.com/reference/org/apache/http/impl/io/ContentLengthOutputStream.html + +http://developer.android.com/reference/org/apache/http/impl/io/HttpRequestParser.html +http://developer.android.com/reference/org/apache/http/impl/io/HttpRequestWriter.html + +http://developer.android.com/reference/org/apache/http/impl/io/HttpResponseParser.html +http://developer.android.com/reference/org/apache/http/impl/io/HttpResponseWriter.html + +http://developer.android.com/reference/org/apache/http/impl/io/HttpTransportMetricsImpl.html +http://developer.android.com/reference/org/apache/http/impl/io/IdentityInputStream.html + +http://developer.android.com/reference/org/apache/http/impl/io/IdentityOutputStream.html +http://developer.android.com/reference/org/apache/http/impl/io/SocketInputBuffer.html + +http://developer.android.com/reference/org/apache/http/impl/io/SocketOutputBuffer.html +http://developer.android.com/reference/org/apache/http/impl/io/package-descr.html + +http://developer.android.com/reference/java/io/InputStream.html +http://developer.android.com/reference/java/io/OutputStream.html + +http://developer.android.com/reference/org/apache/http/io/HttpTransportMetrics.html +http://developer.android.com/reference/org/apache/http/io/SessionInputBuffer.html + +http://developer.android.com/reference/junit/framework/Assert.html +http://developer.android.com/reference/java/lang/IllegalAccessException.html + +http://developer.android.com/reference/java/lang/Exception.html +http://developer.android.com/reference/java/util/jar/Pack200.Packer.html + +http://developer.android.com/reference/java/util/jar/Pack200.Unpacker.html +http://developer.android.com/reference/java/util/jar/Attributes.html + +http://developer.android.com/reference/java/util/jar/Attributes.Name.html +http://developer.android.com/reference/java/util/jar/JarEntry.html + +http://developer.android.com/reference/java/util/jar/JarFile.html +http://developer.android.com/reference/java/util/jar/JarInputStream.html + +http://developer.android.com/reference/java/util/jar/JarOutputStream.html +http://developer.android.com/reference/java/util/jar/Manifest.html + +http://developer.android.com/reference/java/util/jar/Pack200.html +http://developer.android.com/reference/java/util/jar/JarException.html + +http://developer.android.com/reference/java/util/jar/package-descr.html +http://developer.android.com/reference/android/view/View.MeasureSpec.html + +http://developer.android.com/guide/tutorials/views/hello-formstuff.html +http://developer.android.com/reference/android/view/View.OnClickListener.html + +http://developer.android.com/reference/android/view/View.OnLongClickListener.html +http://developer.android.com/reference/android/view/View.OnFocusChangeListener.html + +http://developer.android.com/reference/android/view/View.OnKeyListener.html +http://developer.android.com/reference/android/view/View.OnTouchListener.html + +http://developer.android.com/reference/android/view/View.OnCreateContextMenuListener.html +http://developer.android.com/reference/android/view/ViewParent.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteCursorDriver.html +http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.CursorFactory.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteClosable.html +http://developer.android.com/reference/android/database/sqlite/SQLiteCursor.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html +http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteProgram.html +http://developer.android.com/reference/android/database/sqlite/SQLiteQuery.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteQueryBuilder.html +http://developer.android.com/reference/android/database/sqlite/SQLiteStatement.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteAbortException.html +http://developer.android.com/reference/android/database/sqlite/SQLiteConstraintException.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteDatabaseCorruptException.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteDiskIOException.html +http://developer.android.com/reference/android/database/sqlite/SQLiteDoneException.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteException.html +http://developer.android.com/reference/android/database/sqlite/SQLiteFullException.html + +http://developer.android.com/reference/android/database/sqlite/SQLiteMisuseException.html +http://developer.android.com/reference/android/database/sqlite/package-descr.html + +http://developer.android.com/reference/android/database/Cursor.html +http://developer.android.com/reference/java/lang/StackTraceElement.html + +http://developer.android.com/reference/java/io/PrintWriter.html +http://developer.android.com/reference/java/io/PrintStream.html + +http://developer.android.com/reference/java/math/BigDecimal.html +http://developer.android.com/reference/java/math/BigInteger.html + +http://developer.android.com/reference/java/math/MathContext.html +http://developer.android.com/reference/java/math/RoundingMode.html + +http://developer.android.com/reference/java/math/package-descr.html +http://developer.android.com/reference/dalvik/system/DexFile.html + +http://developer.android.com/reference/dalvik/system/PathClassLoader.html +http://developer.android.com/reference/dalvik/system/TemporaryDirectory.html + +http://developer.android.com/reference/dalvik/system/TouchDex.html +http://developer.android.com/reference/dalvik/system/VMDebug.html + +http://developer.android.com/reference/dalvik/system/VMRuntime.html +http://developer.android.com/reference/dalvik/system/VMStack.html + +http://developer.android.com/reference/dalvik/system/Zygote.html +http://developer.android.com/reference/dalvik/system/AllocationLimitError.html + +http://developer.android.com/reference/dalvik/system/PotentialDeadlockError.html +http://developer.android.com/reference/dalvik/system/StaleDexCacheError.html + +http://developer.android.com/reference/org/apache/http/client/protocol/ClientContext.html +http://developer.android.com/reference/org/apache/http/client/protocol/ClientContextConfigurer.html + +http://developer.android.com/reference/org/apache/http/client/protocol/RequestAddCookies.html + +http://developer.android.com/reference/org/apache/http/client/protocol/RequestDefaultHeaders.html + +http://developer.android.com/reference/org/apache/http/client/protocol/RequestProxyAuthentication.html + +http://developer.android.com/reference/org/apache/http/client/protocol/RequestTargetAuthentication.html + +http://developer.android.com/reference/org/apache/http/client/protocol/ResponseProcessCookies.html + +http://developer.android.com/reference/org/apache/http/client/protocol/package-descr.html +http://developer.android.com/reference/android/graphics/drawable/Drawable.Callback.html + +http://developer.android.com/reference/android/graphics/drawable/ClipDrawable.html +http://developer.android.com/reference/android/graphics/drawable/ColorDrawable.html + +http://developer.android.com/reference/android/graphics/drawable/Drawable.ConstantState.html +http://developer.android.com/reference/android/graphics/drawable/DrawableContainer.html + +http://developer.android.com/reference/android/graphics/drawable/DrawableContainer.DrawableContainerState.html + +http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html +http://developer.android.com/reference/android/graphics/drawable/InsetDrawable.html + +http://developer.android.com/reference/android/graphics/drawable/LevelListDrawable.html +http://developer.android.com/reference/android/graphics/drawable/PaintDrawable.html + +http://developer.android.com/reference/android/graphics/drawable/RotateDrawable.html +http://developer.android.com/reference/android/graphics/drawable/ScaleDrawable.html + +http://developer.android.com/reference/android/graphics/drawable/ShapeDrawable.ShaderFactory.html + +http://developer.android.com/reference/android/graphics/drawable/StateListDrawable.html +http://developer.android.com/reference/android/graphics/drawable/TransitionDrawable.html + +http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.Orientation.html + +http://developer.android.com/reference/java/lang/Runnable.html +http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html + +http://developer.android.com/reference/android/util/AttributeSet.html +http://developer.android.com/reference/org/xmlpull/v1/XmlPullParserException.html + +http://developer.android.com/reference/java/util/EventListener.html +http://developer.android.com/reference/android/app/AliasActivity.html + +http://developer.android.com/reference/java/lang/ref/PhantomReference.html +http://developer.android.com/reference/java/lang/ref/Reference.html + +http://developer.android.com/reference/java/lang/ref/ReferenceQueue.html +http://developer.android.com/reference/java/lang/ref/SoftReference.html + +http://developer.android.com/reference/java/lang/ref/WeakReference.html +http://developer.android.com/reference/javax/xml/parsers/DocumentBuilder.html + +http://developer.android.com/reference/javax/xml/parsers/DocumentBuilderFactory.html +http://developer.android.com/reference/javax/xml/parsers/SAXParser.html + +http://developer.android.com/reference/javax/xml/parsers/SAXParserFactory.html +http://developer.android.com/reference/javax/xml/parsers/ParserConfigurationException.html + +http://developer.android.com/reference/javax/xml/parsers/FactoryConfigurationError.html +http://developer.android.com/reference/javax/xml/parsers/package-descr.html + +http://developer.android.com/reference/android/app/DatePickerDialog.OnDateSetListener.html +http://developer.android.com/reference/android/app/KeyguardManager.OnKeyguardExitResult.html + +http://developer.android.com/reference/android/app/PendingIntent.OnFinished.html +http://developer.android.com/reference/android/app/SearchManager.OnCancelListener.html + +http://developer.android.com/reference/android/app/SearchManager.OnDismissListener.html +http://developer.android.com/reference/android/app/TimePickerDialog.OnTimeSetListener.html + +http://developer.android.com/reference/android/app/ActivityGroup.html +http://developer.android.com/reference/android/app/ActivityManager.html + +http://developer.android.com/reference/android/app/ActivityManager.MemoryInfo.html +http://developer.android.com/reference/android/app/ActivityManager.ProcessErrorStateInfo.html + +http://developer.android.com/reference/android/app/ActivityManager.RecentTaskInfo.html +http://developer.android.com/reference/android/app/ActivityManager.RunningServiceInfo.html + +http://developer.android.com/reference/android/app/ActivityManager.RunningTaskInfo.html +http://developer.android.com/reference/android/app/AlarmManager.html + +http://developer.android.com/reference/android/app/AlertDialog.html +http://developer.android.com/reference/android/app/AlertDialog.Builder.html + +http://developer.android.com/reference/android/app/DatePickerDialog.html +http://developer.android.com/reference/android/app/Dialog.html + +http://developer.android.com/reference/android/app/ExpandableListActivity.html +http://developer.android.com/reference/android/app/Instrumentation.ActivityMonitor.html + +http://developer.android.com/reference/android/app/Instrumentation.ActivityResult.html +http://developer.android.com/reference/android/app/KeyguardManager.html + +http://developer.android.com/reference/android/app/KeyguardManager.KeyguardLock.html +http://developer.android.com/reference/android/app/LauncherActivity.html + +http://developer.android.com/reference/android/app/LocalActivityManager.html +http://developer.android.com/reference/android/app/Notification.html + +http://developer.android.com/reference/android/app/NotificationManager.html +http://developer.android.com/reference/android/app/PendingIntent.html + +http://developer.android.com/reference/android/app/ProgressDialog.html +http://developer.android.com/reference/android/app/SearchManager.html + +http://developer.android.com/reference/android/app/TabActivity.html +http://developer.android.com/reference/android/app/TimePickerDialog.html + +http://developer.android.com/reference/android/app/PendingIntent.CanceledException.html +http://developer.android.com/reference/android/content/ContextWrapper.html + +http://developer.android.com/reference/android/view/ContextThemeWrapper.html +http://developer.android.com/reference/android/widget/ListAdapter.html + +http://developer.android.com/reference/android/widget/SimpleAdapter.html +http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html + +http://developer.android.com/reference/android/media/AudioManager.html +http://developer.android.com/reference/android/text/ClipboardManager.html + +http://developer.android.com/reference/android/view/LayoutInflater.html +http://developer.android.com/reference/android/location/LocationManager.html + +http://developer.android.com/reference/android/os/PowerManager.html +http://developer.android.com/reference/android/hardware/SensorManager.html + +http://developer.android.com/reference/android/telephony/TelephonyManager.html +http://developer.android.com/reference/android/os/Vibrator.html + +http://developer.android.com/reference/android/net/wifi/WifiManager.html +http://developer.android.com/reference/android/view/WindowManager.html + +http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html +http://developer.android.com/reference/android/view/KeyEvent.html + +http://developer.android.com/reference/android/view/MotionEvent.html +http://developer.android.com/reference/android/content/ComponentName.html + +http://developer.android.com/reference/android/view/Window.html +http://developer.android.com/reference/android/content/SharedPreferences.html + +http://developer.android.com/reference/java/lang/CharSequence.html +http://developer.android.com/reference/android/content/res/Resources.Theme.html + +http://developer.android.com/reference/android/content/res/Configuration.html +http://developer.android.com/reference/android/view/Window.Callback.html + +http://developer.android.com/reference/android/view/LayoutInflater.Factory.html +http://developer.android.com/reference/android/view/KeyEvent.Callback.html + +http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html +http://developer.android.com/reference/android/content/ServiceConnection.html + +http://developer.android.com/reference/java/lang/SecurityException.html +http://developer.android.com/reference/android/content/res/AssetManager.html + +http://developer.android.com/reference/java/io/File.html +http://developer.android.com/reference/java/lang/ClassLoader.html + +http://developer.android.com/reference/android/os/Looper.html +http://developer.android.com/reference/java/io/FileInputStream.html + +http://developer.android.com/reference/java/io/FileOutputStream.html +http://developer.android.com/reference/android/content/IntentFilter.html + +http://developer.android.com/reference/android/os/Handler.html +http://developer.android.com/reference/java/util/Formatter.html + +http://developer.android.com/reference/android/content/res/TypedArray.html +http://developer.android.com/reference/android/content/ComponentCallbacks.html + +http://developer.android.com/reference/android/view/animation/Animation.AnimationListener.html + +http://developer.android.com/reference/android/view/animation/AccelerateDecelerateInterpolator.html + +http://developer.android.com/reference/android/view/animation/AlphaAnimation.html +http://developer.android.com/reference/android/view/animation/Animation.Description.html + +http://developer.android.com/reference/android/view/animation/AnimationUtils.html +http://developer.android.com/reference/android/view/animation/CycleInterpolator.html + +http://developer.android.com/reference/android/view/animation/DecelerateInterpolator.html +http://developer.android.com/reference/android/view/animation/GridLayoutAnimationController.html + +http://developer.android.com/reference/android/view/animation/GridLayoutAnimationController.AnimationParameters.html + +http://developer.android.com/reference/android/view/animation/LayoutAnimationController.html +http://developer.android.com/reference/android/view/animation/LayoutAnimationController.AnimationParameters.html + +http://developer.android.com/reference/android/view/animation/LinearInterpolator.html +http://developer.android.com/reference/android/view/animation/RotateAnimation.html + +http://developer.android.com/reference/android/view/animation/ScaleAnimation.html +http://developer.android.com/reference/android/view/animation/Transformation.html + +http://developer.android.com/reference/android/view/animation/TranslateAnimation.html +http://developer.android.com/reference/android/view/animation/package-descr.html + +http://developer.android.com/reference/android/os/IBinder.html +http://developer.android.com/reference/android/os/IBinder.DeathRecipient.html + +http://developer.android.com/reference/android/os/IInterface.html +http://developer.android.com/reference/android/os/MessageQueue.IdleHandler.html + +http://developer.android.com/reference/android/os/Parcelable.html +http://developer.android.com/reference/android/os/Parcelable.Creator.html + +http://developer.android.com/reference/android/os/BatteryManager.html +http://developer.android.com/reference/android/os/Binder.html + +http://developer.android.com/reference/android/os/Build.html +http://developer.android.com/reference/android/os/Build.VERSION.html + +http://developer.android.com/reference/android/os/ConditionVariable.html +http://developer.android.com/reference/android/os/CountDownTimer.html + +http://developer.android.com/reference/android/os/Debug.InstructionCount.html +http://developer.android.com/reference/android/os/Debug.MemoryInfo.html + +http://developer.android.com/reference/android/os/Environment.html +http://developer.android.com/reference/android/os/FileObserver.html + +http://developer.android.com/reference/android/os/HandlerThread.html +http://developer.android.com/reference/android/os/MemoryFile.html + +http://developer.android.com/reference/android/os/Message.html +http://developer.android.com/reference/android/os/MessageQueue.html + +http://developer.android.com/reference/android/os/Messenger.html +http://developer.android.com/reference/android/os/Parcel.html + +http://developer.android.com/reference/android/os/ParcelFileDescriptor.html +http://developer.android.com/reference/android/os/ParcelFileDescriptor.AutoCloseInputStream.html + +http://developer.android.com/reference/android/os/ParcelFileDescriptor.AutoCloseOutputStream.html + +http://developer.android.com/reference/android/os/PatternMatcher.html +http://developer.android.com/reference/android/os/PowerManager.WakeLock.html + +http://developer.android.com/reference/android/os/RemoteCallbackList.html +http://developer.android.com/reference/android/os/StatFs.html + +http://developer.android.com/reference/android/os/SystemClock.html +http://developer.android.com/reference/android/os/TokenWatcher.html + +http://developer.android.com/reference/android/os/BadParcelableException.html +http://developer.android.com/reference/android/os/DeadObjectException.html + +http://developer.android.com/reference/android/os/ParcelFormatException.html +http://developer.android.com/reference/android/os/RemoteException.html + +http://developer.android.com/reference/java/lang/Cloneable.html +http://developer.android.com/reference/java/lang/Byte.html + +http://developer.android.com/reference/java/util/ArrayList.html +http://developer.android.com/reference/java/lang/Integer.html + +http://developer.android.com/reference/java/io/Serializable.html +http://developer.android.com/reference/android/util/SparseArray.html + +http://developer.android.com/reference/java/util/Set.html +http://developer.android.com/reference/java/nio/channels/DatagramChannel.html + +http://developer.android.com/reference/java/lang/IllegalArgumentException.html +http://developer.android.com/reference/android/webkit/WebView.html + +http://developer.android.com/reference/android/hardware/Camera.html +http://developer.android.com/reference/android/text/Spannable.html + +http://developer.android.com/reference/android/util/Log.html +http://developer.android.com/reference/org/xml/sax/helpers/AttributeListImpl.html + +http://developer.android.com/reference/org/xml/sax/helpers/AttributesImpl.html +http://developer.android.com/reference/org/xml/sax/helpers/DefaultHandler.html + +http://developer.android.com/reference/org/xml/sax/helpers/LocatorImpl.html +http://developer.android.com/reference/org/xml/sax/helpers/NamespaceSupport.html + +http://developer.android.com/reference/org/xml/sax/helpers/ParserAdapter.html +http://developer.android.com/reference/org/xml/sax/helpers/ParserFactory.html + +http://developer.android.com/reference/org/xml/sax/helpers/XMLFilterImpl.html +http://developer.android.com/reference/org/xml/sax/helpers/XMLReaderAdapter.html + +http://developer.android.com/reference/org/xml/sax/helpers/XMLReaderFactory.html +http://developer.android.com/reference/org/xml/sax/helpers/package-descr.html + +http://developer.android.com/reference/org/xml/sax/AttributeList.html +http://developer.android.com/reference/org/xml/sax/Parser.html + +http://developer.android.com/reference/android/widget/AbsListView.OnScrollListener.html +http://developer.android.com/reference/android/widget/AbsListView.RecyclerListener.html + +http://developer.android.com/reference/android/widget/Adapter.html +http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html + +http://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html + +http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html + +http://developer.android.com/reference/android/widget/AutoCompleteTextView.Validator.html +http://developer.android.com/reference/android/widget/Checkable.html + +http://developer.android.com/reference/android/widget/CompoundButton.OnCheckedChangeListener.html + +http://developer.android.com/reference/android/widget/DatePicker.OnDateChangedListener.html +http://developer.android.com/reference/android/widget/ExpandableListAdapter.html + +http://developer.android.com/reference/android/widget/ExpandableListView.OnChildClickListener.html + +http://developer.android.com/reference/android/widget/ExpandableListView.OnGroupClickListener.html + +http://developer.android.com/reference/android/widget/ExpandableListView.OnGroupCollapseListener.html + +http://developer.android.com/reference/android/widget/ExpandableListView.OnGroupExpandListener.html + +http://developer.android.com/reference/android/widget/Filter.FilterListener.html +http://developer.android.com/reference/android/widget/Filterable.html + +http://developer.android.com/reference/android/widget/FilterQueryProvider.html +http://developer.android.com/reference/android/widget/MediaController.MediaPlayerControl.html + +http://developer.android.com/reference/android/widget/MultiAutoCompleteTextView.Tokenizer.html + +http://developer.android.com/reference/android/widget/RadioGroup.OnCheckedChangeListener.html + +http://developer.android.com/reference/android/widget/RatingBar.OnRatingBarChangeListener.html + +http://developer.android.com/reference/android/widget/SeekBar.OnSeekBarChangeListener.html +http://developer.android.com/reference/android/widget/SimpleAdapter.ViewBinder.html + +http://developer.android.com/reference/android/widget/SimpleCursorAdapter.CursorToStringConverter.html + +http://developer.android.com/reference/android/widget/SimpleCursorAdapter.ViewBinder.html +http://developer.android.com/reference/android/widget/SpinnerAdapter.html + +http://developer.android.com/reference/android/widget/TabHost.OnTabChangeListener.html +http://developer.android.com/reference/android/widget/TabHost.TabContentFactory.html + +http://developer.android.com/reference/android/widget/TimePicker.OnTimeChangedListener.html +http://developer.android.com/reference/android/widget/ViewSwitcher.ViewFactory.html + +http://developer.android.com/reference/android/widget/WrapperListAdapter.html +http://developer.android.com/reference/android/widget/AbsListView.html + +http://developer.android.com/reference/android/widget/AbsListView.LayoutParams.html +http://developer.android.com/reference/android/widget/AbsoluteLayout.LayoutParams.html + +http://developer.android.com/reference/android/widget/AbsSeekBar.html +http://developer.android.com/reference/android/widget/AbsSpinner.html + +http://developer.android.com/reference/android/widget/AdapterView.html +http://developer.android.com/reference/android/widget/AnalogClock.html + +http://developer.android.com/reference/android/widget/ArrayAdapter.html +http://developer.android.com/reference/android/widget/BaseAdapter.html + +http://developer.android.com/reference/android/widget/BaseExpandableListAdapter.html +http://developer.android.com/reference/android/widget/CheckedTextView.html + +http://developer.android.com/reference/android/widget/Chronometer.html +http://developer.android.com/reference/android/widget/CompoundButton.html + +http://developer.android.com/reference/android/widget/CursorAdapter.html +http://developer.android.com/reference/android/widget/CursorTreeAdapter.html + +http://developer.android.com/reference/android/widget/DatePicker.html +http://developer.android.com/reference/android/widget/DialerFilter.html + +http://developer.android.com/reference/android/widget/DigitalClock.html +http://developer.android.com/reference/android/widget/ExpandableListView.html + +http://developer.android.com/reference/android/widget/ExpandableListView.ExpandableListContextMenuInfo.html + +http://developer.android.com/reference/android/widget/Filter.html +http://developer.android.com/reference/android/widget/Filter.FilterResults.html + +http://developer.android.com/reference/android/widget/FrameLayout.LayoutParams.html +http://developer.android.com/reference/android/widget/Gallery.LayoutParams.html + +http://developer.android.com/reference/android/widget/GridView.html +http://developer.android.com/reference/android/widget/HeaderViewListAdapter.html + +http://developer.android.com/reference/android/widget/ImageButton.html +http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html + +http://developer.android.com/reference/android/widget/ListView.FixedViewInfo.html +http://developer.android.com/reference/android/widget/MediaController.html + +http://developer.android.com/reference/android/widget/MultiAutoCompleteTextView.html +http://developer.android.com/reference/android/widget/MultiAutoCompleteTextView.CommaTokenizer.html + +http://developer.android.com/reference/android/widget/PopupWindow.html +http://developer.android.com/reference/android/widget/ProgressBar.html + +http://developer.android.com/reference/android/widget/RadioGroup.html +http://developer.android.com/reference/android/widget/RadioGroup.LayoutParams.html + +http://developer.android.com/reference/android/widget/RatingBar.html +http://developer.android.com/reference/android/widget/RelativeLayout.html + +http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html +http://developer.android.com/reference/android/widget/RemoteViews.html + +http://developer.android.com/reference/android/widget/ResourceCursorAdapter.html +http://developer.android.com/reference/android/widget/ResourceCursorTreeAdapter.html + +http://developer.android.com/reference/android/widget/Scroller.html +http://developer.android.com/reference/android/widget/ScrollView.html + +http://developer.android.com/reference/android/widget/SeekBar.html +http://developer.android.com/reference/android/widget/SimpleCursorTreeAdapter.html + +http://developer.android.com/reference/android/widget/SimpleExpandableListAdapter.html +http://developer.android.com/reference/android/widget/TabHost.html + +http://developer.android.com/reference/android/widget/TabHost.TabSpec.html +http://developer.android.com/reference/android/widget/TableLayout.html + +http://developer.android.com/reference/android/widget/TableLayout.LayoutParams.html +http://developer.android.com/reference/android/widget/TableRow.html + +http://developer.android.com/reference/android/widget/TableRow.LayoutParams.html +http://developer.android.com/reference/android/widget/TabWidget.html + +http://developer.android.com/reference/android/widget/TextView.SavedState.html +http://developer.android.com/reference/android/widget/TimePicker.html + +http://developer.android.com/reference/android/widget/Toast.html +http://developer.android.com/reference/android/widget/ToggleButton.html + +http://developer.android.com/reference/android/widget/TwoLineListItem.html +http://developer.android.com/reference/android/widget/VideoView.html + +http://developer.android.com/reference/android/widget/ViewAnimator.html +http://developer.android.com/reference/android/widget/ViewFlipper.html + +http://developer.android.com/reference/android/widget/ViewSwitcher.html +http://developer.android.com/reference/android/widget/ZoomButton.html + +http://developer.android.com/reference/android/widget/ZoomControls.html +http://developer.android.com/reference/android/widget/ImageView.ScaleType.html + +http://developer.android.com/reference/android/widget/TextView.BufferType.html +http://developer.android.com/reference/android/widget/RemoteViews.ActionException.html + +http://developer.android.com/reference/java/lang/RuntimeException.html +http://developer.android.com/reference/android/view/ViewGroup.OnHierarchyChangeListener.html + +http://developer.android.com/reference/android/view/TouchDelegate.html +http://developer.android.com/reference/android/view/ViewTreeObserver.html + +http://developer.android.com/reference/android/view/ViewManager.html +http://developer.android.com/reference/android/view/Gravity.html + +http://developer.android.com/reference/javax/microedition/khronos/opengles/GL.html +http://developer.android.com/reference/java/awt/font/NumericShaper.html + +http://developer.android.com/reference/java/awt/font/TextAttribute.html +http://developer.android.com/reference/android/text/TextWatcher.html + +http://developer.android.com/reference/android/text/method/MovementMethod.html +http://developer.android.com/reference/android/text/TextUtils.TruncateAt.html + +http://developer.android.com/reference/android/text/InputFilter.html +http://developer.android.com/reference/android/content/res/ColorStateList.html + +http://developer.android.com/reference/android/text/method/KeyListener.html +http://developer.android.com/reference/android/text/Layout.html + +http://developer.android.com/reference/android/text/method/LinkMovementMethod.html +http://developer.android.com/reference/android/text/TextPaint.html + +http://developer.android.com/reference/android/text/Selection.html +http://developer.android.com/reference/android/text/method/TransformationMethod.html + +http://developer.android.com/reference/android/text/style/URLSpan.html +http://developer.android.com/reference/android/text/util/Linkify.html + +http://developer.android.com/reference/android/text/Editable.Factory.html +http://developer.android.com/reference/android/text/Spannable.Factory.html + +http://developer.android.com/reference/android/view/ViewTreeObserver.OnPreDrawListener.html +http://developer.android.com/reference/java/security/BasicPermission.html + +http://developer.android.com/reference/java/security/Guard.html +http://developer.android.com/reference/java/security/Permission.html + +http://developer.android.com/reference/java/security/PermissionCollection.html +http://developer.android.com/reference/java/util/Locale.html + +http://developer.android.com/reference/java/lang/NullPointerException.html +http://developer.android.com/reference/org/apache/http/FormattedHeader.html + +http://developer.android.com/reference/org/apache/http/Header.html +http://developer.android.com/reference/org/apache/http/HeaderElement.html + +http://developer.android.com/reference/org/apache/http/HeaderElementIterator.html +http://developer.android.com/reference/org/apache/http/HeaderIterator.html + +http://developer.android.com/reference/org/apache/http/HttpClientConnection.html +http://developer.android.com/reference/org/apache/http/HttpConnection.html + +http://developer.android.com/reference/org/apache/http/HttpConnectionMetrics.html +http://developer.android.com/reference/org/apache/http/HttpEntity.html + +http://developer.android.com/reference/org/apache/http/HttpInetConnection.html +http://developer.android.com/reference/org/apache/http/HttpMessage.html + +http://developer.android.com/reference/org/apache/http/HttpRequestFactory.html +http://developer.android.com/reference/org/apache/http/HttpRequestInterceptor.html + +http://developer.android.com/reference/org/apache/http/HttpResponseFactory.html +http://developer.android.com/reference/org/apache/http/HttpResponseInterceptor.html + +http://developer.android.com/reference/org/apache/http/HttpServerConnection.html +http://developer.android.com/reference/org/apache/http/HttpStatus.html + +http://developer.android.com/reference/org/apache/http/NameValuePair.html +http://developer.android.com/reference/org/apache/http/ReasonPhraseCatalog.html + +http://developer.android.com/reference/org/apache/http/RequestLine.html +http://developer.android.com/reference/org/apache/http/StatusLine.html + +http://developer.android.com/reference/org/apache/http/TokenIterator.html +http://developer.android.com/reference/org/apache/http/HttpVersion.html + +http://developer.android.com/reference/org/apache/http/ProtocolVersion.html +http://developer.android.com/reference/org/apache/http/ConnectionClosedException.html + +http://developer.android.com/reference/org/apache/http/MalformedChunkCodingException.html +http://developer.android.com/reference/org/apache/http/MethodNotSupportedException.html + +http://developer.android.com/reference/org/apache/http/NoHttpResponseException.html +http://developer.android.com/reference/org/apache/http/ParseException.html + +http://developer.android.com/reference/org/apache/http/ProtocolException.html +http://developer.android.com/reference/org/apache/http/UnsupportedHttpVersionException.html + +http://developer.android.com/reference/org/apache/http/impl/DefaultConnectionReuseStrategy.html + +http://developer.android.com/reference/org/apache/http/impl/NoConnectionReuseStrategy.html +http://developer.android.com/reference/java/lang/Enum.html + +http://developer.android.com/reference/java/lang/Comparable.html +http://developer.android.com/reference/javax/crypto/SecretKey.html + +http://developer.android.com/reference/javax/crypto/Cipher.html +http://developer.android.com/reference/javax/crypto/CipherInputStream.html + +http://developer.android.com/reference/javax/crypto/CipherOutputStream.html +http://developer.android.com/reference/javax/crypto/CipherSpi.html + +http://developer.android.com/reference/javax/crypto/EncryptedPrivateKeyInfo.html +http://developer.android.com/reference/javax/crypto/ExemptionMechanism.html + +http://developer.android.com/reference/javax/crypto/ExemptionMechanismSpi.html +http://developer.android.com/reference/javax/crypto/KeyAgreement.html + +http://developer.android.com/reference/javax/crypto/KeyAgreementSpi.html +http://developer.android.com/reference/javax/crypto/KeyGenerator.html + +http://developer.android.com/reference/javax/crypto/KeyGeneratorSpi.html +http://developer.android.com/reference/javax/crypto/Mac.html + +http://developer.android.com/reference/javax/crypto/MacSpi.html +http://developer.android.com/reference/javax/crypto/NullCipher.html + +http://developer.android.com/reference/javax/crypto/SealedObject.html +http://developer.android.com/reference/javax/crypto/SecretKeyFactory.html + +http://developer.android.com/reference/javax/crypto/SecretKeyFactorySpi.html +http://developer.android.com/reference/javax/crypto/BadPaddingException.html + +http://developer.android.com/reference/javax/crypto/ExemptionMechanismException.html +http://developer.android.com/reference/javax/crypto/IllegalBlockSizeException.html + +http://developer.android.com/reference/javax/crypto/NoSuchPaddingException.html +http://developer.android.com/reference/javax/crypto/ShortBufferException.html + +http://developer.android.com/reference/javax/crypto/package-descr.html +http://developer.android.com/reference/android/database/CrossProcessCursor.html + +http://developer.android.com/reference/android/database/AbstractCursor.html +http://developer.android.com/reference/android/database/AbstractCursor.SelfContentObserver.html + +http://developer.android.com/reference/android/database/AbstractWindowedCursor.html +http://developer.android.com/reference/android/database/CharArrayBuffer.html + +http://developer.android.com/reference/android/database/ContentObservable.html +http://developer.android.com/reference/android/database/ContentObserver.html + +http://developer.android.com/reference/android/database/CursorJoiner.html +http://developer.android.com/reference/android/database/CursorWindow.html + +http://developer.android.com/reference/android/database/CursorWrapper.html +http://developer.android.com/reference/android/database/DatabaseUtils.html + +http://developer.android.com/reference/android/database/DatabaseUtils.InsertHelper.html +http://developer.android.com/reference/android/database/DataSetObservable.html + +http://developer.android.com/reference/android/database/DataSetObserver.html +http://developer.android.com/reference/android/database/MatrixCursor.html + +http://developer.android.com/reference/android/database/MatrixCursor.RowBuilder.html +http://developer.android.com/reference/android/database/MergeCursor.html + +http://developer.android.com/reference/android/database/Observable.html +http://developer.android.com/reference/android/database/CursorJoiner.Result.html + +http://developer.android.com/reference/android/database/CursorIndexOutOfBoundsException.html +http://developer.android.com/reference/android/database/SQLException.html + +http://developer.android.com/reference/android/database/StaleDataException.html +http://developer.android.com/reference/android/database/package-descr.html + +http://developer.android.com/reference/org/apache/http/conn/ClientConnectionManager.html +http://developer.android.com/reference/org/apache/http/conn/ClientConnectionManagerFactory.html + +http://developer.android.com/reference/org/apache/http/conn/ClientConnectionOperator.html +http://developer.android.com/reference/org/apache/http/conn/ClientConnectionRequest.html + +http://developer.android.com/reference/org/apache/http/conn/ConnectionReleaseTrigger.html +http://developer.android.com/reference/org/apache/http/conn/EofSensorWatcher.html + +http://developer.android.com/reference/org/apache/http/conn/ManagedClientConnection.html +http://developer.android.com/reference/org/apache/http/conn/OperatedClientConnection.html + +http://developer.android.com/reference/org/apache/http/conn/BasicEofSensorWatcher.html +http://developer.android.com/reference/org/apache/http/conn/BasicManagedEntity.html + +http://developer.android.com/reference/org/apache/http/conn/EofSensorInputStream.html +http://developer.android.com/reference/org/apache/http/conn/MultihomePlainSocketFactory.html + +http://developer.android.com/reference/org/apache/http/conn/ConnectionPoolTimeoutException.html + +http://developer.android.com/reference/org/apache/http/conn/ConnectTimeoutException.html +http://developer.android.com/reference/org/apache/http/conn/HttpHostConnectException.html + +http://developer.android.com/reference/java/nio/charset/Charset.html +http://developer.android.com/reference/java/nio/charset/CharsetDecoder.html + +http://developer.android.com/reference/java/nio/charset/CharsetEncoder.html +http://developer.android.com/reference/java/nio/charset/CoderResult.html + +http://developer.android.com/reference/java/nio/charset/CodingErrorAction.html +http://developer.android.com/reference/java/nio/charset/CharacterCodingException.html + +http://developer.android.com/reference/java/nio/charset/IllegalCharsetNameException.html +http://developer.android.com/reference/java/nio/charset/MalformedInputException.html + +http://developer.android.com/reference/java/nio/charset/UnmappableCharacterException.html +http://developer.android.com/reference/java/nio/charset/UnsupportedCharsetException.html + +http://developer.android.com/reference/java/nio/charset/CoderMalfunctionError.html +http://developer.android.com/reference/java/nio/charset/package-descr.html + +http://developer.android.com/reference/com/google/android/maps/MapView.html +http://developer.android.com/reference/com/google/android/maps/MapActivity.html + +http://developer.android.com/guide/topics/location/geo/mapkey.html +http://developer.android.com/reference/com/google/android/maps/MapController.html + +http://developer.android.com/reference/com/google/android/maps/ItemizedOverlay.html +http://developer.android.com/reference/com/google/android/maps/Overlay.html + +http://developer.android.com/reference/java/lang/CloneNotSupportedException.html +http://developer.android.com/reference/java/security/AlgorithmParameters.html + +http://developer.android.com/reference/java/security/spec/PKCS8EncodedKeySpec.html +http://developer.android.com/reference/java/security/Key.html + +http://developer.android.com/reference/java/security/Provider.html +http://developer.android.com/reference/java/security/NoSuchAlgorithmException.html + +http://developer.android.com/reference/java/security/NoSuchProviderException.html +http://developer.android.com/reference/java/security/InvalidKeyException.html + +http://developer.android.com/reference/java/security/spec/InvalidKeySpecException.html +http://developer.android.com/reference/android/webkit/DownloadListener.html + +http://developer.android.com/reference/android/webkit/Plugin.PreferencesClickHandler.html +http://developer.android.com/reference/android/webkit/UrlInterceptHandler.html + +http://developer.android.com/reference/android/webkit/WebIconDatabase.IconListener.html +http://developer.android.com/reference/android/webkit/WebView.PictureListener.html + +http://developer.android.com/reference/android/webkit/CacheManager.html +http://developer.android.com/reference/android/webkit/CacheManager.CacheResult.html + +http://developer.android.com/reference/android/webkit/CookieManager.html +http://developer.android.com/reference/android/webkit/CookieSyncManager.html + +http://developer.android.com/reference/android/webkit/DateSorter.html +http://developer.android.com/reference/android/webkit/HttpAuthHandler.html + +http://developer.android.com/reference/android/webkit/JsPromptResult.html +http://developer.android.com/reference/android/webkit/JsResult.html + +http://developer.android.com/reference/android/webkit/MimeTypeMap.html +http://developer.android.com/reference/android/webkit/Plugin.html + +http://developer.android.com/reference/android/webkit/PluginList.html +http://developer.android.com/reference/android/webkit/SslErrorHandler.html + +http://developer.android.com/reference/android/webkit/UrlInterceptRegistry.html +http://developer.android.com/reference/android/webkit/URLUtil.html + +http://developer.android.com/reference/android/webkit/WebBackForwardList.html +http://developer.android.com/reference/android/webkit/WebChromeClient.html + +http://developer.android.com/reference/android/webkit/WebHistoryItem.html +http://developer.android.com/reference/android/webkit/WebIconDatabase.html + +http://developer.android.com/reference/android/webkit/WebSettings.html +http://developer.android.com/reference/android/webkit/WebView.HitTestResult.html + +http://developer.android.com/reference/android/webkit/WebView.WebViewTransport.html +http://developer.android.com/reference/android/webkit/WebViewClient.html + +http://developer.android.com/reference/android/webkit/WebViewDatabase.html +http://developer.android.com/reference/android/webkit/WebSettings.LayoutAlgorithm.html + +http://developer.android.com/reference/android/webkit/WebSettings.RenderPriority.html +http://developer.android.com/reference/android/webkit/WebSettings.TextSize.html + +http://developer.android.com/reference/android/webkit/package-descr.html +http://developer.android.com/reference/java/util/Map.html + +http://developer.android.com/reference/android/graphics/drawable/shapes/ArcShape.html +http://developer.android.com/reference/android/graphics/drawable/shapes/PathShape.html + +http://developer.android.com/reference/android/graphics/drawable/shapes/RectShape.html +http://developer.android.com/reference/android/graphics/drawable/shapes/RoundRectShape.html + +http://developer.android.com/reference/android/graphics/drawable/shapes/Shape.html +http://developer.android.com/reference/android/graphics/drawable/package-descr.html + +http://developer.android.com/reference/java/lang/IndexOutOfBoundsException.html +http://developer.android.com/reference/android/content/pm/ActivityInfo.html + +http://developer.android.com/reference/java/lang/InstantiationException.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/GLSurfaceView.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/GLSurfaceViewActivity.html + +http://developer.android.com/reference/java/util/concurrent/BlockingQueue.html +http://developer.android.com/reference/java/util/concurrent/Callable.html + +http://developer.android.com/reference/java/util/concurrent/CompletionService.html +http://developer.android.com/reference/java/util/concurrent/ConcurrentMap.html + +http://developer.android.com/reference/java/util/concurrent/Delayed.html +http://developer.android.com/reference/java/util/concurrent/Executor.html + +http://developer.android.com/reference/java/util/concurrent/ExecutorService.html +http://developer.android.com/reference/java/util/concurrent/Future.html + +http://developer.android.com/reference/java/util/concurrent/RejectedExecutionHandler.html +http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html + +http://developer.android.com/reference/java/util/concurrent/ScheduledFuture.html +http://developer.android.com/reference/java/util/concurrent/ThreadFactory.html + +http://developer.android.com/reference/java/util/concurrent/AbstractExecutorService.html +http://developer.android.com/reference/java/util/concurrent/ArrayBlockingQueue.html + +http://developer.android.com/reference/java/util/concurrent/ConcurrentHashMap.html +http://developer.android.com/reference/java/util/concurrent/ConcurrentLinkedQueue.html + +http://developer.android.com/reference/java/util/concurrent/CopyOnWriteArrayList.html +http://developer.android.com/reference/java/util/concurrent/CopyOnWriteArraySet.html + +http://developer.android.com/reference/java/util/concurrent/CountDownLatch.html +http://developer.android.com/reference/java/util/concurrent/CyclicBarrier.html + +http://developer.android.com/reference/java/util/concurrent/DelayQueue.html +http://developer.android.com/reference/java/util/concurrent/Exchanger.html + +http://developer.android.com/reference/java/util/concurrent/ExecutorCompletionService.html +http://developer.android.com/reference/java/util/concurrent/Executors.html + +http://developer.android.com/reference/java/util/concurrent/FutureTask.html +http://developer.android.com/reference/java/util/concurrent/LinkedBlockingQueue.html + +http://developer.android.com/reference/java/util/concurrent/PriorityBlockingQueue.html +http://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html + +http://developer.android.com/reference/java/util/concurrent/Semaphore.html +http://developer.android.com/reference/java/util/concurrent/SynchronousQueue.html + +http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html +http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.AbortPolicy.html + +http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.CallerRunsPolicy.html + +http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.DiscardOldestPolicy.html + +http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.DiscardPolicy.html + +http://developer.android.com/reference/java/util/concurrent/TimeUnit.html +http://developer.android.com/reference/java/util/concurrent/BrokenBarrierException.html + +http://developer.android.com/reference/java/util/concurrent/CancellationException.html +http://developer.android.com/reference/java/util/concurrent/ExecutionException.html + +http://developer.android.com/reference/java/util/concurrent/RejectedExecutionException.html +http://developer.android.com/reference/java/util/concurrent/TimeoutException.html + +http://developer.android.com/reference/java/util/concurrent/package-descr.html +http://developer.android.com/reference/java/util/Queue.html + +http://developer.android.com/reference/java/util/PriorityQueue.html +http://developer.android.com/reference/android/telephony/CellLocation.html + +http://developer.android.com/reference/android/telephony/PhoneNumberFormattingTextWatcher.html + +http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html +http://developer.android.com/reference/android/telephony/PhoneStateListener.html + +http://developer.android.com/reference/android/telephony/ServiceState.html +http://developer.android.com/reference/java/lang/Appendable.html + +http://developer.android.com/reference/java/lang/Iterable.html +http://developer.android.com/reference/java/lang/Readable.html + +http://developer.android.com/reference/java/lang/Thread.UncaughtExceptionHandler.html +http://developer.android.com/reference/java/lang/Boolean.html + +http://developer.android.com/reference/java/lang/Character.html +http://developer.android.com/reference/java/lang/Character.Subset.html + +http://developer.android.com/reference/java/lang/Character.UnicodeBlock.html +http://developer.android.com/reference/java/lang/Compiler.html + +http://developer.android.com/reference/java/lang/Double.html +http://developer.android.com/reference/java/lang/Float.html + +http://developer.android.com/reference/java/lang/InheritableThreadLocal.html +http://developer.android.com/reference/java/lang/Long.html + +http://developer.android.com/reference/java/lang/Math.html +http://developer.android.com/reference/java/lang/Number.html + +http://developer.android.com/reference/java/lang/Package.html +http://developer.android.com/reference/java/lang/Process.html + +http://developer.android.com/reference/java/lang/ProcessBuilder.html +http://developer.android.com/reference/java/lang/Runtime.html + +http://developer.android.com/reference/java/lang/RuntimePermission.html +http://developer.android.com/reference/java/lang/SecurityManager.html + +http://developer.android.com/reference/java/lang/Short.html +http://developer.android.com/reference/java/lang/StrictMath.html + +http://developer.android.com/reference/java/lang/StringBuffer.html +http://developer.android.com/reference/java/lang/StringBuilder.html + +http://developer.android.com/reference/java/lang/System.html +http://developer.android.com/reference/java/lang/Thread.html + +http://developer.android.com/reference/java/lang/ThreadGroup.html +http://developer.android.com/reference/java/lang/ThreadLocal.html + +http://developer.android.com/reference/java/lang/Void.html +http://developer.android.com/reference/java/lang/Thread.State.html + +http://developer.android.com/reference/java/lang/ArithmeticException.html +http://developer.android.com/reference/java/lang/ArrayIndexOutOfBoundsException.html + +http://developer.android.com/reference/java/lang/ArrayStoreException.html +http://developer.android.com/reference/java/lang/ClassCastException.html + +http://developer.android.com/reference/java/lang/EnumConstantNotPresentException.html +http://developer.android.com/reference/java/lang/IllegalMonitorStateException.html + +http://developer.android.com/reference/java/lang/IllegalStateException.html +http://developer.android.com/reference/java/lang/IllegalThreadStateException.html + +http://developer.android.com/reference/java/lang/InterruptedException.html +http://developer.android.com/reference/java/lang/NegativeArraySizeException.html + +http://developer.android.com/reference/java/lang/NoSuchFieldException.html +http://developer.android.com/reference/java/lang/NoSuchMethodException.html + +http://developer.android.com/reference/java/lang/NumberFormatException.html +http://developer.android.com/reference/java/lang/StringIndexOutOfBoundsException.html + +http://developer.android.com/reference/java/lang/TypeNotPresentException.html +http://developer.android.com/reference/java/lang/UnsupportedOperationException.html + +http://developer.android.com/reference/java/lang/AbstractMethodError.html +http://developer.android.com/reference/java/lang/AssertionError.html + +http://developer.android.com/reference/java/lang/ClassCircularityError.html +http://developer.android.com/reference/java/lang/ClassFormatError.html + +http://developer.android.com/reference/java/lang/Error.html +http://developer.android.com/reference/java/lang/ExceptionInInitializerError.html + +http://developer.android.com/reference/java/lang/IllegalAccessError.html +http://developer.android.com/reference/java/lang/IncompatibleClassChangeError.html + +http://developer.android.com/reference/java/lang/InstantiationError.html +http://developer.android.com/reference/java/lang/InternalError.html + +http://developer.android.com/reference/java/lang/LinkageError.html +http://developer.android.com/reference/java/lang/NoClassDefFoundError.html + +http://developer.android.com/reference/java/lang/NoSuchFieldError.html +http://developer.android.com/reference/java/lang/NoSuchMethodError.html + +http://developer.android.com/reference/java/lang/OutOfMemoryError.html +http://developer.android.com/reference/java/lang/StackOverflowError.html + +http://developer.android.com/reference/java/lang/ThreadDeath.html +http://developer.android.com/reference/java/lang/UnknownError.html + +http://developer.android.com/reference/java/lang/UnsatisfiedLinkError.html +http://developer.android.com/reference/java/lang/UnsupportedClassVersionError.html + +http://developer.android.com/reference/java/lang/VerifyError.html +http://developer.android.com/reference/java/lang/VirtualMachineError.html + +http://developer.android.com/reference/java/nio/ByteBuffer.html +http://developer.android.com/reference/java/util/Calendar.html + +http://developer.android.com/reference/java/nio/CharBuffer.html +http://developer.android.com/reference/android/preference/CheckBoxPreference.html + +http://developer.android.com/reference/java/sql/Date.html +http://developer.android.com/reference/android/preference/DialogPreference.html + +http://developer.android.com/reference/java/nio/DoubleBuffer.html +http://developer.android.com/reference/android/preference/EditTextPreference.html + +http://developer.android.com/reference/java/lang/annotation/ElementType.html +http://developer.android.com/reference/java/nio/FloatBuffer.html + +http://developer.android.com/reference/java/util/Formatter.BigDecimalLayoutForm.html +http://developer.android.com/reference/java/util/GregorianCalendar.html + +http://developer.android.com/reference/java/nio/IntBuffer.html +http://developer.android.com/reference/java/security/KeyRep.Type.html + +http://developer.android.com/reference/android/text/Layout.Alignment.html +http://developer.android.com/reference/android/preference/ListPreference.html + +http://developer.android.com/reference/java/nio/LongBuffer.html +http://developer.android.com/reference/com/google/android/maps/MapView.ReticleDrawMode.html + +http://developer.android.com/reference/java/nio/MappedByteBuffer.html +http://developer.android.com/reference/java/io/ObjectStreamField.html + +http://developer.android.com/reference/android/preference/Preference.html +http://developer.android.com/reference/android/preference/PreferenceCategory.html + +http://developer.android.com/reference/android/preference/PreferenceGroup.html +http://developer.android.com/reference/android/preference/PreferenceScreen.html + +http://developer.android.com/reference/java/lang/annotation/RetentionPolicy.html +http://developer.android.com/reference/android/preference/RingtonePreference.html + +http://developer.android.com/reference/org/apache/http/conn/routing/RouteInfo.LayerType.html +http://developer.android.com/reference/org/apache/http/conn/routing/RouteInfo.TunnelType.html + +http://developer.android.com/reference/javax/net/ssl/SSLEngineResult.HandshakeStatus.html +http://developer.android.com/reference/javax/net/ssl/SSLEngineResult.Status.html + +http://developer.android.com/reference/java/nio/ShortBuffer.html +http://developer.android.com/reference/android/telephony/gsm/SmsMessage.MessageClass.html + +http://developer.android.com/reference/android/net/wifi/SupplicantState.html +http://developer.android.com/reference/android/text/method/TextKeyListener.Capitalize.html + +http://developer.android.com/reference/java/sql/Time.html +http://developer.android.com/reference/java/sql/Timestamp.html + +http://developer.android.com/reference/java/util/UUID.html +http://developer.android.com/reference/android/view/ViewDebug.HierarchyTraceType.html + +http://developer.android.com/reference/android/view/ViewDebug.RecyclerTraceType.html +http://developer.android.com/reference/android/util/Xml.Encoding.html + +http://developer.android.com/reference/org/apache/http/impl/auth/NTLMEngine.html +http://developer.android.com/reference/org/apache/http/impl/auth/AuthSchemeBase.html + +http://developer.android.com/reference/org/apache/http/impl/auth/BasicScheme.html +http://developer.android.com/reference/org/apache/http/impl/auth/BasicSchemeFactory.html + +http://developer.android.com/reference/org/apache/http/impl/auth/DigestScheme.html +http://developer.android.com/reference/org/apache/http/impl/auth/DigestSchemeFactory.html + +http://developer.android.com/reference/org/apache/http/impl/auth/NTLMScheme.html +http://developer.android.com/reference/org/apache/http/impl/auth/RFC2617Scheme.html + +http://developer.android.com/reference/org/apache/http/impl/auth/NTLMEngineException.html +http://developer.android.com/reference/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.html + +http://developer.android.com/reference/android/preference/Preference.OnPreferenceChangeListener.html + +http://developer.android.com/reference/android/preference/Preference.OnPreferenceClickListener.html + +http://developer.android.com/reference/android/preference/PreferenceManager.OnActivityDestroyListener.html + +http://developer.android.com/reference/android/preference/PreferenceManager.OnActivityResultListener.html + +http://developer.android.com/reference/android/preference/PreferenceManager.OnActivityStopListener.html + +http://developer.android.com/reference/android/preference/Preference.BaseSavedState.html +http://developer.android.com/reference/android/preference/PreferenceManager.html + +http://developer.android.com/reference/android/util/Printer.html +http://developer.android.com/reference/android/util/Config.html + +http://developer.android.com/reference/android/util/DebugUtils.html +http://developer.android.com/reference/android/util/DisplayMetrics.html + +http://developer.android.com/reference/android/util/EventLogTags.html +http://developer.android.com/reference/android/util/EventLogTags.Description.html + +http://developer.android.com/reference/android/util/FloatMath.html +http://developer.android.com/reference/android/util/LogPrinter.html + +http://developer.android.com/reference/android/util/MonthDisplayHelper.html +http://developer.android.com/reference/android/util/PrintWriterPrinter.html + +http://developer.android.com/reference/android/util/SparseBooleanArray.html +http://developer.android.com/reference/android/util/SparseIntArray.html + +http://developer.android.com/reference/android/util/StateSet.html +http://developer.android.com/reference/android/util/StringBuilderPrinter.html + +http://developer.android.com/reference/android/util/TimeUtils.html +http://developer.android.com/reference/android/util/TimingLogger.html + +http://developer.android.com/reference/android/util/TypedValue.html +http://developer.android.com/reference/android/util/Xml.html + +http://developer.android.com/reference/android/util/AndroidException.html +http://developer.android.com/reference/android/util/AndroidRuntimeException.html + +http://developer.android.com/reference/android/util/TimeFormatException.html +http://developer.android.com/reference/android/content/res/XmlResourceParser.html + +http://developer.android.com/reference/javax/net/ssl/SSLSocketFactory.html +http://developer.android.com/reference/javax/net/SocketFactory.html + +http://developer.android.com/reference/java/security/KeyManagementException.html +http://developer.android.com/reference/org/apache/http/message/BasicHeader.html + +http://developer.android.com/reference/org/apache/http/message/BufferedHeader.html +http://developer.android.com/reference/android/view/GestureDetector.OnGestureListener.html + +http://developer.android.com/reference/android/view/LayoutInflater.Filter.html +http://developer.android.com/reference/android/view/MenuItem.OnMenuItemClickListener.html + +http://developer.android.com/reference/android/view/SurfaceHolder.html +http://developer.android.com/reference/android/view/SurfaceHolder.Callback.html + +http://developer.android.com/reference/android/view/ViewStub.OnInflateListener.html +http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalFocusChangeListener.html + +http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html + +http://developer.android.com/reference/android/view/ViewTreeObserver.OnTouchModeChangeListener.html + +http://developer.android.com/reference/android/view/AbsSavedState.html +http://developer.android.com/reference/android/view/Display.html + +http://developer.android.com/reference/android/view/FocusFinder.html +http://developer.android.com/reference/android/view/GestureDetector.html + +http://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener.html + +http://developer.android.com/reference/android/view/KeyCharacterMap.html +http://developer.android.com/reference/android/view/KeyCharacterMap.KeyData.html + +http://developer.android.com/reference/android/view/OrientationListener.html +http://developer.android.com/reference/android/view/SoundEffectConstants.html + +http://developer.android.com/reference/android/view/Surface.html +http://developer.android.com/reference/android/view/VelocityTracker.html + +http://developer.android.com/reference/android/view/View.BaseSavedState.html +http://developer.android.com/reference/android/view/ViewConfiguration.html + +http://developer.android.com/reference/android/view/ViewDebug.html +http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html + +http://developer.android.com/reference/android/view/ViewStub.html +http://developer.android.com/reference/android/view/InflateException.html + +http://developer.android.com/reference/android/view/Surface.OutOfResourcesException.html +http://developer.android.com/reference/android/view/SurfaceHolder.BadSurfaceTypeException.html + +http://developer.android.com/reference/android/view/WindowManager.BadTokenException.html +http://developer.android.com/reference/org/apache/http/entity/AbstractHttpEntity.html + +http://developer.android.com/reference/org/apache/http/entity/BasicHttpEntity.html +http://developer.android.com/reference/org/apache/http/entity/BufferedHttpEntity.html + +http://developer.android.com/reference/org/apache/http/entity/ByteArrayEntity.html +http://developer.android.com/reference/org/apache/http/entity/EntityTemplate.html + +http://developer.android.com/reference/org/apache/http/entity/FileEntity.html +http://developer.android.com/reference/org/apache/http/entity/HttpEntityWrapper.html + +http://developer.android.com/reference/org/apache/http/entity/InputStreamEntity.html +http://developer.android.com/reference/org/apache/http/entity/SerializableEntity.html + +http://developer.android.com/reference/org/apache/http/entity/StringEntity.html +http://developer.android.com/reference/org/apache/http/client/entity/UrlEncodedFormEntity.html + +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicInteger.html +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicLong.html + +http://developer.android.com/reference/java/util/Collection.html +http://developer.android.com/reference/java/util/Comparator.html + +http://developer.android.com/reference/java/util/Enumeration.html +http://developer.android.com/reference/java/util/Formattable.html + +http://developer.android.com/reference/java/util/Iterator.html +http://developer.android.com/reference/java/util/ListIterator.html + +http://developer.android.com/reference/java/util/Map.Entry.html +http://developer.android.com/reference/java/util/Observer.html + +http://developer.android.com/reference/java/util/RandomAccess.html +http://developer.android.com/reference/java/util/SortedMap.html + +http://developer.android.com/reference/java/util/SortedSet.html +http://developer.android.com/reference/java/util/AbstractCollection.html + +http://developer.android.com/reference/java/util/AbstractList.html +http://developer.android.com/reference/java/util/AbstractMap.html + +http://developer.android.com/reference/java/util/AbstractQueue.html +http://developer.android.com/reference/java/util/AbstractSequentialList.html + +http://developer.android.com/reference/java/util/AbstractSet.html +http://developer.android.com/reference/java/util/Arrays.html + +http://developer.android.com/reference/java/util/BitSet.html +http://developer.android.com/reference/java/util/Collections.html + +http://developer.android.com/reference/java/util/Currency.html +http://developer.android.com/reference/java/util/Dictionary.html + +http://developer.android.com/reference/java/util/EnumMap.html +http://developer.android.com/reference/java/util/EnumSet.html + +http://developer.android.com/reference/java/util/EventListenerProxy.html +http://developer.android.com/reference/java/util/EventObject.html + +http://developer.android.com/reference/java/util/FormattableFlags.html +http://developer.android.com/reference/java/util/HashMap.html + +http://developer.android.com/reference/java/util/HashSet.html +http://developer.android.com/reference/java/util/Hashtable.html + +http://developer.android.com/reference/java/util/IdentityHashMap.html +http://developer.android.com/reference/java/util/LinkedHashMap.html + +http://developer.android.com/reference/java/util/LinkedHashSet.html +http://developer.android.com/reference/java/util/LinkedList.html + +http://developer.android.com/reference/java/util/ListResourceBundle.html +http://developer.android.com/reference/java/util/Observable.html + +http://developer.android.com/reference/java/util/PropertyPermission.html +http://developer.android.com/reference/java/util/PropertyResourceBundle.html + +http://developer.android.com/reference/java/util/Random.html +http://developer.android.com/reference/java/util/ResourceBundle.html + +http://developer.android.com/reference/java/util/Scanner.html +http://developer.android.com/reference/java/util/SimpleTimeZone.html + +http://developer.android.com/reference/java/util/Stack.html +http://developer.android.com/reference/java/util/StringTokenizer.html + +http://developer.android.com/reference/java/util/Timer.html +http://developer.android.com/reference/java/util/TimerTask.html + +http://developer.android.com/reference/java/util/TimeZone.html +http://developer.android.com/reference/java/util/TreeMap.html + +http://developer.android.com/reference/java/util/TreeSet.html +http://developer.android.com/reference/java/util/Vector.html + +http://developer.android.com/reference/java/util/WeakHashMap.html +http://developer.android.com/reference/java/util/ConcurrentModificationException.html + +http://developer.android.com/reference/java/util/DuplicateFormatFlagsException.html +http://developer.android.com/reference/java/util/EmptyStackException.html + +http://developer.android.com/reference/java/util/FormatFlagsConversionMismatchException.html +http://developer.android.com/reference/java/util/FormatterClosedException.html + +http://developer.android.com/reference/java/util/IllegalFormatCodePointException.html +http://developer.android.com/reference/java/util/IllegalFormatConversionException.html + +http://developer.android.com/reference/java/util/IllegalFormatException.html +http://developer.android.com/reference/java/util/IllegalFormatFlagsException.html + +http://developer.android.com/reference/java/util/IllegalFormatPrecisionException.html +http://developer.android.com/reference/java/util/IllegalFormatWidthException.html + +http://developer.android.com/reference/java/util/InputMismatchException.html +http://developer.android.com/reference/java/util/InvalidPropertiesFormatException.html + +http://developer.android.com/reference/java/util/MissingFormatArgumentException.html +http://developer.android.com/reference/java/util/MissingFormatWidthException.html + +http://developer.android.com/reference/java/util/MissingResourceException.html +http://developer.android.com/reference/java/util/NoSuchElementException.html + +http://developer.android.com/reference/java/util/TooManyListenersException.html +http://developer.android.com/reference/java/util/UnknownFormatConversionException.html + +http://developer.android.com/reference/java/util/UnknownFormatFlagsException.html +http://developer.android.com/reference/org/apache/http/impl/EnglishReasonPhraseCatalog.html + +http://developer.android.com/reference/org/apache/http/params/CoreConnectionPNames.html +http://developer.android.com/reference/org/apache/http/params/CoreProtocolPNames.html + +http://developer.android.com/reference/org/apache/http/params/AbstractHttpParams.html +http://developer.android.com/reference/org/apache/http/params/BasicHttpParams.html + +http://developer.android.com/reference/org/apache/http/params/DefaultedHttpParams.html +http://developer.android.com/reference/org/apache/http/params/HttpAbstractParamBean.html + +http://developer.android.com/reference/org/apache/http/params/HttpConnectionParamBean.html +http://developer.android.com/reference/org/apache/http/params/HttpConnectionParams.html + +http://developer.android.com/reference/org/apache/http/params/HttpProtocolParamBean.html +http://developer.android.com/reference/org/apache/http/params/HttpProtocolParams.html + +http://developer.android.com/reference/org/apache/http/params/package-descr.html +http://developer.android.com/reference/org/apache/http/io/SessionOutputBuffer.html + +http://developer.android.com/reference/org/apache/http/util/CharArrayBuffer.html +http://developer.android.com/reference/android/content/res/AssetFileDescriptor.html + +http://developer.android.com/reference/android/content/res/AssetManager.AssetInputStream.html + +http://developer.android.com/reference/android/content/res/Resources.NotFoundException.html +http://developer.android.com/reference/java/util/zip/ZipEntry.html + +http://developer.android.com/reference/java/security/cert/Certificate.html +http://developer.android.com/reference/java/security/CodeSigner.html + +http://developer.android.com/reference/org/apache/http/auth/AuthSchemeFactory.html +http://developer.android.com/reference/org/apache/http/auth/AuthScheme.html + +http://developer.android.com/reference/android/content/SharedPreferences.Editor.html +http://developer.android.com/reference/android/media/RingtoneManager.html + +http://developer.android.com/reference/android/content/DialogInterface.html +http://developer.android.com/reference/android/content/DialogInterface.OnClickListener.html + +http://developer.android.com/reference/android/content/DialogInterface.OnDismissListener.html + +http://developer.android.com/reference/org/apache/http/conn/routing/HttpRouteDirector.html +http://developer.android.com/reference/org/apache/http/conn/routing/HttpRoutePlanner.html + +http://developer.android.com/reference/org/apache/http/conn/routing/RouteInfo.html +http://developer.android.com/reference/org/apache/http/conn/routing/BasicRouteDirector.html + +http://developer.android.com/reference/org/apache/http/conn/routing/HttpRoute.html +http://developer.android.com/reference/org/apache/http/conn/routing/RouteTracker.html + +http://developer.android.com/reference/org/apache/http/impl/conn/DefaultClientConnectionOperator.html + +http://developer.android.com/reference/org/apache/http/conn/scheme/SocketFactory.html +http://developer.android.com/reference/java/nio/channels/Channel.html + +http://developer.android.com/reference/org/apache/http/message/LineParser.html +http://developer.android.com/reference/org/apache/http/io/HttpMessageParser.html + +http://developer.android.com/reference/java/security/AuthProvider.html +http://developer.android.com/reference/org/apache/http/impl/cookie/BasicClientCookie.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/BasicClientCookie2.html +http://developer.android.com/reference/org/apache/http/message/BasicHeaderElement.html + +http://developer.android.com/reference/org/apache/http/protocol/BasicHttpProcessor.html +http://developer.android.com/reference/org/apache/http/message/BasicNameValuePair.html + +http://developer.android.com/reference/org/apache/http/message/BasicRequestLine.html +http://developer.android.com/reference/org/apache/http/message/BasicStatusLine.html + +http://developer.android.com/reference/java/security/cert/CRLSelector.html +http://developer.android.com/reference/java/security/cert/CertPathBuilderResult.html + +http://developer.android.com/reference/java/security/cert/CertPathParameters.html +http://developer.android.com/reference/java/security/cert/CertPathValidatorResult.html + +http://developer.android.com/reference/java/security/cert/CertSelector.html +http://developer.android.com/reference/java/security/cert/CertStoreParameters.html + +http://developer.android.com/reference/java/security/cert/CollectionCertStoreParameters.html +http://developer.android.com/reference/org/apache/http/message/HeaderGroup.html + +http://developer.android.com/reference/org/apache/http/client/methods/HttpDelete.html +http://developer.android.com/reference/org/apache/http/client/methods/HttpEntityEnclosingRequestBase.html + +http://developer.android.com/reference/org/apache/http/client/methods/HttpGet.html +http://developer.android.com/reference/org/apache/http/client/methods/HttpHead.html + +http://developer.android.com/reference/org/apache/http/client/methods/HttpOptions.html +http://developer.android.com/reference/org/apache/http/client/methods/HttpPost.html + +http://developer.android.com/reference/org/apache/http/client/methods/HttpPut.html +http://developer.android.com/reference/org/apache/http/client/methods/HttpRequestBase.html + +http://developer.android.com/reference/org/apache/http/client/methods/HttpTrace.html +http://developer.android.com/reference/java/security/cert/LDAPCertStoreParameters.html + +http://developer.android.com/reference/java/security/cert/PKIXBuilderParameters.html +http://developer.android.com/reference/java/security/cert/PKIXCertPathBuilderResult.html + +http://developer.android.com/reference/java/security/cert/PKIXCertPathChecker.html +http://developer.android.com/reference/java/security/cert/PKIXCertPathValidatorResult.html + +http://developer.android.com/reference/java/security/cert/PKIXParameters.html +http://developer.android.com/reference/java/security/cert/X509CRLSelector.html + +http://developer.android.com/reference/java/security/cert/X509CertSelector.html +http://developer.android.com/reference/android/text/Editable.html +http://developer.android.com/reference/java/security/spec/AlgorithmParameterSpec.html + +http://developer.android.com/reference/java/security/SecureRandom.html +http://developer.android.com/reference/javax/net/ssl/HandshakeCompletedListener.html + +http://developer.android.com/reference/javax/net/ssl/HostnameVerifier.html +http://developer.android.com/reference/javax/net/ssl/KeyManager.html + +http://developer.android.com/reference/javax/net/ssl/ManagerFactoryParameters.html +http://developer.android.com/reference/javax/net/ssl/SSLSession.html + +http://developer.android.com/reference/javax/net/ssl/SSLSessionBindingListener.html +http://developer.android.com/reference/javax/net/ssl/SSLSessionContext.html + +http://developer.android.com/reference/javax/net/ssl/TrustManager.html +http://developer.android.com/reference/javax/net/ssl/X509KeyManager.html + +http://developer.android.com/reference/javax/net/ssl/X509TrustManager.html +http://developer.android.com/reference/javax/net/ssl/CertPathTrustManagerParameters.html + +http://developer.android.com/reference/javax/net/ssl/HandshakeCompletedEvent.html +http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html + +http://developer.android.com/reference/javax/net/ssl/KeyManagerFactory.html +http://developer.android.com/reference/javax/net/ssl/KeyManagerFactorySpi.html + +http://developer.android.com/reference/javax/net/ssl/KeyStoreBuilderParameters.html +http://developer.android.com/reference/javax/net/ssl/SSLContext.html + +http://developer.android.com/reference/javax/net/ssl/SSLContextSpi.html +http://developer.android.com/reference/javax/net/ssl/SSLEngine.html + +http://developer.android.com/reference/javax/net/ssl/SSLEngineResult.html +http://developer.android.com/reference/javax/net/ssl/SSLPermission.html + +http://developer.android.com/reference/javax/net/ssl/SSLServerSocket.html +http://developer.android.com/reference/javax/net/ssl/SSLServerSocketFactory.html + +http://developer.android.com/reference/javax/net/ssl/SSLSessionBindingEvent.html +http://developer.android.com/reference/javax/net/ssl/SSLSocket.html + +http://developer.android.com/reference/javax/net/ssl/TrustManagerFactory.html +http://developer.android.com/reference/javax/net/ssl/TrustManagerFactorySpi.html + +http://developer.android.com/reference/javax/net/ssl/X509ExtendedKeyManager.html +http://developer.android.com/reference/javax/net/ssl/SSLException.html + +http://developer.android.com/reference/javax/net/ssl/SSLHandshakeException.html +http://developer.android.com/reference/javax/net/ssl/SSLKeyException.html + +http://developer.android.com/reference/javax/net/ssl/SSLPeerUnverifiedException.html +http://developer.android.com/reference/javax/net/ssl/SSLProtocolException.html + +http://developer.android.com/reference/javax/crypto/spec/DESedeKeySpec.html +http://developer.android.com/reference/javax/crypto/spec/DESKeySpec.html + +http://developer.android.com/reference/javax/crypto/spec/DHGenParameterSpec.html +http://developer.android.com/reference/javax/crypto/spec/DHParameterSpec.html + +http://developer.android.com/reference/javax/crypto/spec/DHPrivateKeySpec.html +http://developer.android.com/reference/javax/crypto/spec/DHPublicKeySpec.html + +http://developer.android.com/reference/javax/crypto/spec/IvParameterSpec.html +http://developer.android.com/reference/javax/crypto/spec/OAEPParameterSpec.html + +http://developer.android.com/reference/javax/crypto/spec/PBEKeySpec.html +http://developer.android.com/reference/javax/crypto/spec/PBEParameterSpec.html + +http://developer.android.com/reference/javax/crypto/spec/PSource.html +http://developer.android.com/reference/javax/crypto/spec/PSource.PSpecified.html + +http://developer.android.com/reference/javax/crypto/spec/RC2ParameterSpec.html +http://developer.android.com/reference/javax/crypto/spec/RC5ParameterSpec.html + +http://developer.android.com/reference/javax/crypto/spec/SecretKeySpec.html +http://developer.android.com/reference/javax/crypto/spec/package-descr.html + +http://developer.android.com/reference/android/text/method/ArrowKeyMovementMethod.html +http://developer.android.com/reference/android/text/method/BaseKeyListener.html + +http://developer.android.com/reference/android/text/method/CharacterPickerDialog.html +http://developer.android.com/reference/android/text/method/DateKeyListener.html + +http://developer.android.com/reference/android/text/method/DateTimeKeyListener.html +http://developer.android.com/reference/android/text/method/DialerKeyListener.html + +http://developer.android.com/reference/android/text/method/DigitsKeyListener.html +http://developer.android.com/reference/android/text/method/HideReturnsTransformationMethod.html + +http://developer.android.com/reference/android/text/method/MetaKeyKeyListener.html +http://developer.android.com/reference/android/text/method/MultiTapKeyListener.html + +http://developer.android.com/reference/android/text/method/NumberKeyListener.html +http://developer.android.com/reference/android/text/method/PasswordTransformationMethod.html + +http://developer.android.com/reference/android/text/method/QwertyKeyListener.html +http://developer.android.com/reference/android/text/method/ReplacementTransformationMethod.html + +http://developer.android.com/reference/android/text/method/ScrollingMovementMethod.html +http://developer.android.com/reference/android/text/method/SingleLineTransformationMethod.html + +http://developer.android.com/reference/android/text/method/TextKeyListener.html +http://developer.android.com/reference/android/text/method/TimeKeyListener.html + +http://developer.android.com/reference/android/text/method/Touch.html +http://developer.android.com/reference/android/location/Address.html + +http://developer.android.com/reference/android/content/pm/ApplicationInfo.html +http://developer.android.com/reference/android/location/Criteria.html + +http://developer.android.com/reference/android/content/pm/InstrumentationInfo.html +http://developer.android.com/reference/android/content/Intent.ShortcutIconResource.html + +http://developer.android.com/reference/android/location/Location.html +http://developer.android.com/reference/android/content/pm/PackageInfo.html + +http://developer.android.com/reference/android/content/pm/PackageStats.html +http://developer.android.com/reference/android/content/pm/PermissionGroupInfo.html + +http://developer.android.com/reference/android/content/pm/PermissionInfo.html +http://developer.android.com/reference/android/content/pm/ProviderInfo.html + +http://developer.android.com/reference/android/content/pm/ResolveInfo.html +http://developer.android.com/reference/android/net/wifi/ScanResult.html + +http://developer.android.com/reference/android/content/pm/ServiceInfo.html +http://developer.android.com/reference/android/content/pm/Signature.html + +http://developer.android.com/reference/android/net/wifi/WifiConfiguration.html +http://developer.android.com/reference/android/net/wifi/WifiInfo.html + +http://developer.android.com/reference/java/io/FileDescriptor.html +http://developer.android.com/reference/java/security/SecureClassLoader.html + +http://developer.android.com/reference/java/security/ProtectionDomain.html +http://developer.android.com/reference/java/io/Closeable.html + +http://developer.android.com/reference/java/io/DataInput.html +http://developer.android.com/reference/java/io/DataOutput.html + +http://developer.android.com/reference/java/io/Externalizable.html +http://developer.android.com/reference/java/io/FileFilter.html + +http://developer.android.com/reference/java/io/FilenameFilter.html +http://developer.android.com/reference/java/io/Flushable.html + +http://developer.android.com/reference/java/io/ObjectInput.html +http://developer.android.com/reference/java/io/ObjectInputValidation.html + +http://developer.android.com/reference/java/io/ObjectOutput.html +http://developer.android.com/reference/java/io/ObjectStreamConstants.html + +http://developer.android.com/reference/java/io/BufferedInputStream.html +http://developer.android.com/reference/java/io/BufferedOutputStream.html + +http://developer.android.com/reference/java/io/BufferedReader.html +http://developer.android.com/reference/java/io/BufferedWriter.html + +http://developer.android.com/reference/java/io/ByteArrayInputStream.html +http://developer.android.com/reference/java/io/ByteArrayOutputStream.html + +http://developer.android.com/reference/java/io/CharArrayReader.html +http://developer.android.com/reference/java/io/CharArrayWriter.html + +http://developer.android.com/reference/java/io/DataInputStream.html +http://developer.android.com/reference/java/io/DataOutputStream.html + +http://developer.android.com/reference/java/io/FilePermission.html +http://developer.android.com/reference/java/io/FileReader.html + +http://developer.android.com/reference/java/io/FileWriter.html +http://developer.android.com/reference/java/io/FilterInputStream.html + +http://developer.android.com/reference/java/io/FilterOutputStream.html +http://developer.android.com/reference/java/io/FilterReader.html + +http://developer.android.com/reference/java/io/FilterWriter.html +http://developer.android.com/reference/java/io/InputStreamReader.html + +http://developer.android.com/reference/java/io/LineNumberInputStream.html +http://developer.android.com/reference/java/io/LineNumberReader.html + +http://developer.android.com/reference/java/io/ObjectInputStream.html +http://developer.android.com/reference/java/io/ObjectInputStream.GetField.html + +http://developer.android.com/reference/java/io/ObjectOutputStream.html +http://developer.android.com/reference/java/io/ObjectOutputStream.PutField.html + +http://developer.android.com/reference/java/io/ObjectStreamClass.html +http://developer.android.com/reference/java/io/OutputStreamWriter.html + +http://developer.android.com/reference/java/io/PipedInputStream.html +http://developer.android.com/reference/java/io/PipedOutputStream.html + +http://developer.android.com/reference/java/io/PipedReader.html +http://developer.android.com/reference/java/io/PipedWriter.html + +http://developer.android.com/reference/java/io/PushbackInputStream.html +http://developer.android.com/reference/java/io/PushbackReader.html + +http://developer.android.com/reference/java/io/RandomAccessFile.html +http://developer.android.com/reference/java/io/Reader.html + +http://developer.android.com/reference/java/io/SequenceInputStream.html +http://developer.android.com/reference/java/io/SerializablePermission.html + +http://developer.android.com/reference/java/io/StreamTokenizer.html +http://developer.android.com/reference/java/io/StringBufferInputStream.html + +http://developer.android.com/reference/java/io/StringReader.html +http://developer.android.com/reference/java/io/StringWriter.html + +http://developer.android.com/reference/java/io/Writer.html +http://developer.android.com/reference/java/io/CharConversionException.html + +http://developer.android.com/reference/java/io/EOFException.html +http://developer.android.com/reference/java/io/FileNotFoundException.html + +http://developer.android.com/reference/java/io/InterruptedIOException.html +http://developer.android.com/reference/java/io/InvalidClassException.html + +http://developer.android.com/reference/java/io/InvalidObjectException.html +http://developer.android.com/reference/java/io/NotActiveException.html + +http://developer.android.com/reference/java/io/NotSerializableException.html +http://developer.android.com/reference/java/io/ObjectStreamException.html + +http://developer.android.com/reference/java/io/OptionalDataException.html +http://developer.android.com/reference/java/io/StreamCorruptedException.html + +http://developer.android.com/reference/java/io/SyncFailedException.html +http://developer.android.com/reference/java/io/UnsupportedEncodingException.html + +http://developer.android.com/reference/java/io/UTFDataFormatException.html +http://developer.android.com/reference/java/io/WriteAbortedException.html + +http://developer.android.com/reference/org/apache/http/entity/ContentLengthStrategy.html +http://developer.android.com/reference/org/apache/http/entity/ContentProducer.html + +http://developer.android.com/reference/java/security/Certificate.html +http://developer.android.com/reference/java/security/DomainCombiner.html + +http://developer.android.com/reference/java/security/KeyStore.Entry.html +http://developer.android.com/reference/java/security/KeyStore.LoadStoreParameter.html + +http://developer.android.com/reference/java/security/KeyStore.ProtectionParameter.html +http://developer.android.com/reference/java/security/Principal.html + +http://developer.android.com/reference/java/security/PrivateKey.html +http://developer.android.com/reference/java/security/PrivilegedAction.html + +http://developer.android.com/reference/java/security/PrivilegedExceptionAction.html +http://developer.android.com/reference/java/security/PublicKey.html + +http://developer.android.com/reference/java/security/AccessControlContext.html +http://developer.android.com/reference/java/security/AccessController.html + +http://developer.android.com/reference/java/security/AlgorithmParameterGenerator.html +http://developer.android.com/reference/java/security/AlgorithmParameterGeneratorSpi.html + +http://developer.android.com/reference/java/security/AlgorithmParametersSpi.html +http://developer.android.com/reference/java/security/AllPermission.html + +http://developer.android.com/reference/java/security/CodeSource.html +http://developer.android.com/reference/java/security/DigestInputStream.html + +http://developer.android.com/reference/java/security/DigestOutputStream.html +http://developer.android.com/reference/java/security/GuardedObject.html + +http://developer.android.com/reference/java/security/Identity.html +http://developer.android.com/reference/java/security/IdentityScope.html + +http://developer.android.com/reference/java/security/KeyFactory.html +http://developer.android.com/reference/java/security/KeyFactorySpi.html + +http://developer.android.com/reference/java/security/KeyPair.html +http://developer.android.com/reference/java/security/KeyPairGenerator.html + +http://developer.android.com/reference/java/security/KeyPairGeneratorSpi.html +http://developer.android.com/reference/java/security/KeyRep.html + +http://developer.android.com/reference/java/security/KeyStore.html +http://developer.android.com/reference/java/security/KeyStore.Builder.html + +http://developer.android.com/reference/java/security/KeyStore.CallbackHandlerProtection.html +http://developer.android.com/reference/java/security/KeyStore.PasswordProtection.html + +http://developer.android.com/reference/java/security/KeyStore.PrivateKeyEntry.html +http://developer.android.com/reference/java/security/KeyStore.SecretKeyEntry.html + +http://developer.android.com/reference/java/security/KeyStore.TrustedCertificateEntry.html +http://developer.android.com/reference/java/security/KeyStoreSpi.html + +http://developer.android.com/reference/java/security/MessageDigest.html +http://developer.android.com/reference/java/security/MessageDigestSpi.html + +http://developer.android.com/reference/java/security/Permissions.html +http://developer.android.com/reference/java/security/Policy.html + +http://developer.android.com/reference/java/security/Provider.Service.html +http://developer.android.com/reference/java/security/SecureRandomSpi.html + +http://developer.android.com/reference/java/security/Security.html +http://developer.android.com/reference/java/security/SecurityPermission.html + +http://developer.android.com/reference/java/security/Signature.html +http://developer.android.com/reference/java/security/SignatureSpi.html + +http://developer.android.com/reference/java/security/SignedObject.html +http://developer.android.com/reference/java/security/Signer.html + +http://developer.android.com/reference/java/security/Timestamp.html +http://developer.android.com/reference/java/security/UnresolvedPermission.html + +http://developer.android.com/reference/java/security/AccessControlException.html +http://developer.android.com/reference/java/security/DigestException.html + +http://developer.android.com/reference/java/security/GeneralSecurityException.html +http://developer.android.com/reference/java/security/InvalidAlgorithmParameterException.html + +http://developer.android.com/reference/java/security/InvalidParameterException.html +http://developer.android.com/reference/java/security/KeyException.html + +http://developer.android.com/reference/java/security/KeyStoreException.html +http://developer.android.com/reference/java/security/PrivilegedActionException.html + +http://developer.android.com/reference/java/security/ProviderException.html +http://developer.android.com/reference/java/security/SignatureException.html + +http://developer.android.com/reference/java/security/UnrecoverableEntryException.html +http://developer.android.com/reference/java/security/UnrecoverableKeyException.html + +http://developer.android.com/reference/java/nio/Buffer.html +http://developer.android.com/reference/java/nio/ByteOrder.html + +http://developer.android.com/reference/java/nio/BufferOverflowException.html +http://developer.android.com/reference/java/nio/BufferUnderflowException.html + +http://developer.android.com/reference/java/nio/InvalidMarkException.html +http://developer.android.com/reference/java/nio/ReadOnlyBufferException.html + +http://developer.android.com/reference/org/apache/http/client/methods/AbortableHttpRequest.html + +http://developer.android.com/reference/org/apache/http/client/methods/HttpUriRequest.html +http://developer.android.com/reference/org/apache/http/conn/package-descr.html + +http://developer.android.com/reference/java/security/cert/PolicyNode.html +http://developer.android.com/reference/java/security/cert/X509Extension.html + +http://developer.android.com/reference/java/security/cert/Certificate.CertificateRep.html +http://developer.android.com/reference/java/security/cert/CertificateFactory.html + +http://developer.android.com/reference/java/security/cert/CertificateFactorySpi.html +http://developer.android.com/reference/java/security/cert/CertPath.html + +http://developer.android.com/reference/java/security/cert/CertPath.CertPathRep.html +http://developer.android.com/reference/java/security/cert/CertPathBuilder.html + +http://developer.android.com/reference/java/security/cert/CertPathBuilderSpi.html +http://developer.android.com/reference/java/security/cert/CertPathValidator.html + +http://developer.android.com/reference/java/security/cert/CertPathValidatorSpi.html +http://developer.android.com/reference/java/security/cert/CertStore.html + +http://developer.android.com/reference/java/security/cert/CertStoreSpi.html +http://developer.android.com/reference/java/security/cert/CRL.html + +http://developer.android.com/reference/java/security/cert/PolicyQualifierInfo.html +http://developer.android.com/reference/java/security/cert/TrustAnchor.html + +http://developer.android.com/reference/java/security/cert/X509Certificate.html +http://developer.android.com/reference/java/security/cert/X509CRL.html + +http://developer.android.com/reference/java/security/cert/X509CRLEntry.html +http://developer.android.com/reference/java/security/cert/CertificateEncodingException.html + +http://developer.android.com/reference/java/security/cert/CertificateException.html +http://developer.android.com/reference/java/security/cert/CertificateExpiredException.html + +http://developer.android.com/reference/java/security/cert/CertificateNotYetValidException.html + +http://developer.android.com/reference/java/security/cert/CertificateParsingException.html +http://developer.android.com/reference/java/security/cert/CertPathBuilderException.html + +http://developer.android.com/reference/java/security/cert/CertPathValidatorException.html +http://developer.android.com/reference/java/security/cert/CertStoreException.html + +http://developer.android.com/reference/java/security/cert/CRLException.html +http://developer.android.com/reference/com/google/android/maps/ItemizedOverlay.OnFocusChangeListener.html + +http://developer.android.com/reference/com/google/android/maps/Projection.html +http://developer.android.com/reference/com/google/android/maps/GeoPoint.html + +http://developer.android.com/reference/com/google/android/maps/OverlayItem.html +http://developer.android.com/reference/com/google/android/maps/MapView.LayoutParams.html + +http://developer.android.com/reference/com/google/android/maps/MyLocationOverlay.html +http://developer.android.com/reference/com/google/android/maps/TrackballGestureDetector.html + +http://developer.android.com/reference/java/sql/Array.html +http://developer.android.com/reference/java/sql/Blob.html + +http://developer.android.com/reference/java/sql/CallableStatement.html +http://developer.android.com/reference/java/sql/Clob.html + +http://developer.android.com/reference/java/sql/Connection.html +http://developer.android.com/reference/java/sql/DatabaseMetaData.html + +http://developer.android.com/reference/java/sql/Driver.html +http://developer.android.com/reference/java/sql/ParameterMetaData.html + +http://developer.android.com/reference/java/sql/PreparedStatement.html +http://developer.android.com/reference/java/sql/Ref.html + +http://developer.android.com/reference/java/sql/ResultSet.html +http://developer.android.com/reference/java/sql/ResultSetMetaData.html + +http://developer.android.com/reference/java/sql/Savepoint.html +http://developer.android.com/reference/java/sql/SQLData.html + +http://developer.android.com/reference/java/sql/SQLInput.html +http://developer.android.com/reference/java/sql/SQLOutput.html + +http://developer.android.com/reference/java/sql/Statement.html +http://developer.android.com/reference/java/sql/Struct.html + +http://developer.android.com/reference/java/sql/DriverManager.html +http://developer.android.com/reference/java/sql/DriverPropertyInfo.html + +http://developer.android.com/reference/java/sql/SQLPermission.html +http://developer.android.com/reference/java/sql/Types.html + +http://developer.android.com/reference/java/sql/BatchUpdateException.html +http://developer.android.com/reference/java/sql/DataTruncation.html + +http://developer.android.com/reference/java/sql/SQLException.html +http://developer.android.com/reference/java/sql/SQLWarning.html + +http://developer.android.com/reference/org/apache/http/message/BasicTokenIterator.html +http://developer.android.com/reference/java/security/package-descr.html + +http://developer.android.com/reference/java/security/spec/KeySpec.html +http://developer.android.com/reference/android/text/GetChars.html + +http://developer.android.com/reference/android/text/Html.ImageGetter.html +http://developer.android.com/reference/android/text/Html.TagHandler.html + +http://developer.android.com/reference/android/text/Spanned.html +http://developer.android.com/reference/android/text/SpanWatcher.html + +http://developer.android.com/reference/android/text/TextUtils.EllipsizeCallback.html +http://developer.android.com/reference/android/text/TextUtils.StringSplitter.html + +http://developer.android.com/reference/android/text/AlteredCharSequence.html +http://developer.android.com/reference/android/text/AndroidCharacter.html + +http://developer.android.com/reference/android/text/Annotation.html +http://developer.android.com/reference/android/text/AutoText.html + +http://developer.android.com/reference/android/text/BoringLayout.html +http://developer.android.com/reference/android/text/BoringLayout.Metrics.html + +http://developer.android.com/reference/android/text/DynamicLayout.html +http://developer.android.com/reference/android/text/Html.html + +http://developer.android.com/reference/android/text/InputFilter.AllCaps.html +http://developer.android.com/reference/android/text/InputFilter.LengthFilter.html + +http://developer.android.com/reference/android/text/Layout.Directions.html +http://developer.android.com/reference/android/text/LoginFilter.html + +http://developer.android.com/reference/android/text/LoginFilter.PasswordFilterGMail.html +http://developer.android.com/reference/android/text/LoginFilter.UsernameFilterGeneric.html + +http://developer.android.com/reference/android/text/LoginFilter.UsernameFilterGMail.html +http://developer.android.com/reference/android/text/SpannableString.html + +http://developer.android.com/reference/android/text/SpannableStringBuilder.html +http://developer.android.com/reference/android/text/SpannedString.html + +http://developer.android.com/reference/android/text/StaticLayout.html +http://developer.android.com/reference/android/text/TextUtils.html + +http://developer.android.com/reference/android/text/TextUtils.SimpleStringSplitter.html +http://developer.android.com/reference/javax/security/auth/Subject.html + +http://developer.android.com/reference/javax/security/auth/callback/CallbackHandler.html +http://developer.android.com/reference/javax/security/auth/login/LoginException.html + +http://developer.android.com/reference/java/nio/package-descr.html + +http://developer.android.com/reference/java/util/zip/ZipFile.html +http://developer.android.com/reference/android/widget/RemoteViews.RemoteView.html + +http://developer.android.com/reference/javax/security/auth/Destroyable.html +http://developer.android.com/reference/javax/security/auth/AuthPermission.html + +http://developer.android.com/reference/javax/security/auth/PrivateCredentialPermission.html +http://developer.android.com/reference/javax/security/auth/SubjectDomainCombiner.html + +http://developer.android.com/reference/javax/security/auth/DestroyFailedException.html +http://developer.android.com/reference/javax/security/auth/package-descr.html + +http://developer.android.com/guide/tutorials/views/hello-linearlayout.html +http://developer.android.com/guide/tutorials/views/hello-tablelayout.html + +http://developer.android.com/guide/tutorials/views/hello-relativelayout.html +http://developer.android.com/reference/android/view/ViewDebug.ExportedProperty.html + +http://developer.android.com/reference/android/view/ViewDebug.IntToString.html +http://developer.android.com/reference/android/content/DialogInterface.OnCancelListener.html + +http://developer.android.com/reference/android/content/DialogInterface.OnKeyListener.html +http://developer.android.com/reference/android/content/DialogInterface.OnMultiChoiceClickListener.html + +http://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener.html + +http://developer.android.com/reference/android/content/AsyncQueryHandler.html +http://developer.android.com/reference/android/content/AsyncQueryHandler.WorkerArgs.html + +http://developer.android.com/reference/android/content/AsyncQueryHandler.WorkerHandler.html +http://developer.android.com/reference/android/content/ContentQueryMap.html + +http://developer.android.com/reference/android/content/ContentUris.html +http://developer.android.com/reference/android/content/Intent.FilterComparison.html + +http://developer.android.com/reference/android/content/IntentFilter.AuthorityEntry.html +http://developer.android.com/reference/android/content/MutableContextWrapper.html + +http://developer.android.com/reference/android/content/UriMatcher.html +http://developer.android.com/reference/android/content/ActivityNotFoundException.html + +http://developer.android.com/reference/android/content/IntentFilter.MalformedMimeTypeException.html + +http://developer.android.com/reference/android/content/ReceiverCallNotAllowedException.html +http://developer.android.com/reference/android/test/mock/MockContext.html + +http://developer.android.com/reference/android/test/mock/MockApplication.html +http://developer.android.com/reference/android/content/pm/PackageManager.NameNotFoundException.html + +http://developer.android.com/reference/org/xml/sax/ContentHandler.html +http://developer.android.com/reference/org/xml/sax/DocumentHandler.html + +http://developer.android.com/reference/org/xml/sax/DTDHandler.html +http://developer.android.com/reference/org/xml/sax/EntityResolver.html + +http://developer.android.com/reference/org/xml/sax/ErrorHandler.html +http://developer.android.com/reference/org/xml/sax/XMLFilter.html + +http://developer.android.com/reference/org/xml/sax/XMLReader.html +http://developer.android.com/reference/org/xml/sax/HandlerBase.html + +http://developer.android.com/reference/org/xml/sax/InputSource.html +http://developer.android.com/reference/org/xml/sax/SAXException.html + +http://developer.android.com/reference/org/xml/sax/SAXNotRecognizedException.html +http://developer.android.com/reference/org/xml/sax/SAXNotSupportedException.html + +http://developer.android.com/reference/org/xml/sax/SAXParseException.html +http://developer.android.com/reference/org/xml/sax/package-descr.html + +http://developer.android.com/reference/javax/sql/RowSet.html +http://developer.android.com/reference/android/content/pm/IPackageInstallObserver.html + +http://developer.android.com/reference/android/content/pm/ApplicationInfo.DisplayNameComparator.html + +http://developer.android.com/reference/android/content/pm/ComponentInfo.html +http://developer.android.com/reference/android/content/pm/IPackageInstallObserver.Stub.html + +http://developer.android.com/reference/android/content/pm/PackageItemInfo.DisplayNameComparator.html + +http://developer.android.com/reference/android/content/pm/ResolveInfo.DisplayNameComparator.html + +http://developer.android.com/guide/samples/NotePad/res/index.html +http://developer.android.com/guide/samples/NotePad/src/index.html + +http://developer.android.com/guide/samples/NotePad/tests/index.html +http://developer.android.com/guide/samples/NotePad/AndroidManifest.html + +http://developer.android.com/guide/samples/NotePad/sample_note.html +http://developer.android.com/guide/samples/NotePad/sample_notepad.html + +http://developer.android.com/reference/android/telephony/gsm/GsmCellLocation.html + +http://developer.android.com/reference/java/nio/channels/ServerSocketChannel.html +http://developer.android.com/reference/javax/xml/XMLConstants.html + +http://developer.android.com/reference/org/apache/http/impl/conn/DefaultResponseParser.html +http://developer.android.com/reference/java/nio/channels/ByteChannel.html + +http://developer.android.com/reference/java/nio/channels/GatheringByteChannel.html +http://developer.android.com/reference/java/nio/channels/InterruptibleChannel.html + +http://developer.android.com/reference/java/nio/channels/ReadableByteChannel.html +http://developer.android.com/reference/java/nio/channels/ScatteringByteChannel.html + +http://developer.android.com/reference/java/nio/channels/WritableByteChannel.html +http://developer.android.com/reference/java/nio/channels/Channels.html + +http://developer.android.com/reference/java/nio/channels/FileChannel.html +http://developer.android.com/reference/java/nio/channels/FileChannel.MapMode.html + +http://developer.android.com/reference/java/nio/channels/FileLock.html +http://developer.android.com/reference/java/nio/channels/Pipe.html + +http://developer.android.com/reference/java/nio/channels/Pipe.SinkChannel.html +http://developer.android.com/reference/java/nio/channels/Pipe.SourceChannel.html + +http://developer.android.com/reference/java/nio/channels/SelectableChannel.html +http://developer.android.com/reference/java/nio/channels/SelectionKey.html + +http://developer.android.com/reference/java/nio/channels/Selector.html +http://developer.android.com/reference/java/nio/channels/SocketChannel.html + +http://developer.android.com/reference/java/nio/channels/AlreadyConnectedException.html +http://developer.android.com/reference/java/nio/channels/AsynchronousCloseException.html + +http://developer.android.com/reference/java/nio/channels/CancelledKeyException.html +http://developer.android.com/reference/java/nio/channels/ClosedByInterruptException.html + +http://developer.android.com/reference/java/nio/channels/ClosedChannelException.html +http://developer.android.com/reference/java/nio/channels/ClosedSelectorException.html + +http://developer.android.com/reference/java/nio/channels/ConnectionPendingException.html +http://developer.android.com/reference/java/nio/channels/FileLockInterruptionException.html + +http://developer.android.com/reference/java/nio/channels/IllegalBlockingModeException.html +http://developer.android.com/reference/java/nio/channels/IllegalSelectorException.html + +http://developer.android.com/reference/java/nio/channels/NoConnectionPendingException.html +http://developer.android.com/reference/java/nio/channels/NonReadableChannelException.html + +http://developer.android.com/reference/java/nio/channels/NonWritableChannelException.html +http://developer.android.com/reference/java/nio/channels/NotYetBoundException.html + +http://developer.android.com/reference/java/nio/channels/NotYetConnectedException.html +http://developer.android.com/reference/java/nio/channels/OverlappingFileLockException.html + +http://developer.android.com/reference/java/nio/channels/UnresolvedAddressException.html +http://developer.android.com/reference/java/nio/channels/UnsupportedAddressTypeException.html + +http://developer.android.com/reference/org/apache/http/message/BasicHeaderIterator.html +http://developer.android.com/reference/org/apache/http/message/BasicListHeaderIterator.html + +http://developer.android.com/reference/org/apache/http/impl/conn/AbstractClientConnAdapter.html + +http://developer.android.com/reference/org/apache/http/impl/conn/AbstractPooledConnAdapter.html + +http://developer.android.com/reference/org/apache/http/impl/conn/AbstractPoolEntry.html +http://developer.android.com/reference/org/apache/http/impl/conn/DefaultClientConnection.html + +http://developer.android.com/reference/org/apache/http/impl/conn/DefaultHttpRoutePlanner.html + +http://developer.android.com/reference/org/apache/http/impl/conn/IdleConnectionHandler.html +http://developer.android.com/reference/org/apache/http/impl/conn/LoggingSessionInputBuffer.html + +http://developer.android.com/reference/org/apache/http/impl/conn/LoggingSessionOutputBuffer.html + +http://developer.android.com/reference/org/apache/http/impl/conn/ProxySelectorRoutePlanner.html + +http://developer.android.com/reference/org/apache/http/impl/conn/SingleClientConnManager.html + +http://developer.android.com/reference/org/apache/http/impl/conn/SingleClientConnManager.ConnAdapter.html + +http://developer.android.com/reference/org/apache/http/impl/conn/SingleClientConnManager.PoolEntry.html + +http://developer.android.com/reference/org/apache/http/impl/conn/Wire.html +http://developer.android.com/reference/java/security/spec/ECField.html + +http://developer.android.com/reference/java/security/spec/DSAParameterSpec.html +http://developer.android.com/reference/java/security/spec/DSAPrivateKeySpec.html + +http://developer.android.com/reference/java/security/spec/DSAPublicKeySpec.html +http://developer.android.com/reference/java/security/spec/ECFieldF2m.html + +http://developer.android.com/reference/java/security/spec/ECFieldFp.html +http://developer.android.com/reference/java/security/spec/ECGenParameterSpec.html + +http://developer.android.com/reference/java/security/spec/ECParameterSpec.html +http://developer.android.com/reference/java/security/spec/ECPoint.html + +http://developer.android.com/reference/java/security/spec/ECPrivateKeySpec.html +http://developer.android.com/reference/java/security/spec/ECPublicKeySpec.html + +http://developer.android.com/reference/java/security/spec/EllipticCurve.html +http://developer.android.com/reference/java/security/spec/EncodedKeySpec.html + +http://developer.android.com/reference/java/security/spec/MGF1ParameterSpec.html +http://developer.android.com/reference/java/security/spec/PSSParameterSpec.html + +http://developer.android.com/reference/java/security/spec/RSAKeyGenParameterSpec.html +http://developer.android.com/reference/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.html + +http://developer.android.com/reference/java/security/spec/RSAOtherPrimeInfo.html +http://developer.android.com/reference/java/security/spec/RSAPrivateCrtKeySpec.html + +http://developer.android.com/reference/java/security/spec/RSAPrivateKeySpec.html +http://developer.android.com/reference/java/security/spec/RSAPublicKeySpec.html + +http://developer.android.com/reference/java/security/spec/X509EncodedKeySpec.html +http://developer.android.com/reference/java/security/spec/InvalidParameterSpecException.html + +http://developer.android.com/reference/org/apache/http/auth/Credentials.html +http://developer.android.com/reference/org/apache/http/auth/AUTH.html + +http://developer.android.com/reference/org/apache/http/auth/AuthSchemeRegistry.html +http://developer.android.com/reference/org/apache/http/auth/AuthScope.html + +http://developer.android.com/reference/org/apache/http/auth/AuthState.html +http://developer.android.com/reference/org/apache/http/auth/BasicUserPrincipal.html + +http://developer.android.com/reference/org/apache/http/auth/NTCredentials.html +http://developer.android.com/reference/org/apache/http/auth/NTUserPrincipal.html + +http://developer.android.com/reference/org/apache/http/auth/UsernamePasswordCredentials.html +http://developer.android.com/reference/org/apache/http/auth/AuthenticationException.html + +http://developer.android.com/reference/org/apache/http/auth/InvalidCredentialsException.html +http://developer.android.com/reference/org/apache/http/auth/MalformedChallengeException.html + +http://developer.android.com/reference/org/apache/http/auth/package-descr.html +http://developer.android.com/reference/android/net/wifi/WifiConfiguration.AuthAlgorithm.html + +http://developer.android.com/reference/android/net/wifi/WifiConfiguration.GroupCipher.html +http://developer.android.com/reference/android/net/wifi/WifiConfiguration.KeyMgmt.html + +http://developer.android.com/reference/android/net/wifi/WifiConfiguration.PairwiseCipher.html + +http://developer.android.com/reference/android/net/wifi/WifiConfiguration.Protocol.html +http://developer.android.com/reference/android/net/wifi/WifiConfiguration.Status.html + +http://developer.android.com/reference/android/net/wifi/WifiManager.WifiLock.html +http://developer.android.com/reference/org/apache/http/protocol/HTTP.html + +http://developer.android.com/reference/java/util/zip/ZipInputStream.html +http://developer.android.com/reference/java/util/zip/InflaterInputStream.html + +http://developer.android.com/reference/java/util/zip/Inflater.html +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/PoolEntryRequest.html +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/RefQueueHandler.html + +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/AbstractConnPool.html +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/BasicPooledConnAdapter.html + +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/BasicPoolEntry.html +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/BasicPoolEntryRef.html + +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/ConnPoolByRoute.html +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/RefQueueWorker.html + +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/RouteSpecificPool.html + +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager.html + +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/WaitingThread.html +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/WaitingThreadAborter.html + +http://developer.android.com/reference/org/apache/http/impl/conn/tsccm/package-descr.html +http://developer.android.com/reference/java/util/regex/PatternSyntaxException.html + +http://developer.android.com/reference/org/xmlpull/v1/sax2/Driver.html +http://developer.android.com/guide/tutorials/views/hello-spinner.html + +http://developer.android.com/guide/tutorials/views/hello-listview.html +http://developer.android.com/guide/tutorials/views/hello-gridview.html + +http://developer.android.com/reference/android/test/mock/MockPackageManager.html + +http://developer.android.com/reference/android/text/util/Linkify.MatchFilter.html + +http://developer.android.com/reference/android/text/util/Linkify.TransformFilter.html +http://developer.android.com/reference/android/text/util/Rfc822Token.html + +http://developer.android.com/reference/android/text/util/Rfc822Tokenizer.html +http://developer.android.com/reference/java/util/regex/Pattern.html + +http://developer.android.com/reference/java/lang/reflect/ReflectPermission.html + +http://developer.android.com/reference/javax/security/auth/callback/Callback.html +http://developer.android.com/reference/javax/security/auth/callback/PasswordCallback.html + +http://developer.android.com/reference/javax/security/auth/callback/UnsupportedCallbackException.html + +http://developer.android.com/reference/javax/security/cert/Certificate.html +http://developer.android.com/reference/javax/security/cert/X509Certificate.html + +http://developer.android.com/reference/javax/security/cert/CertificateEncodingException.html +http://developer.android.com/reference/javax/security/cert/CertificateException.html + +http://developer.android.com/reference/javax/security/cert/CertificateExpiredException.html +http://developer.android.com/reference/javax/security/cert/CertificateNotYetValidException.html + +http://developer.android.com/reference/javax/security/cert/CertificateParsingException.html +http://developer.android.com/reference/javax/security/cert/package-descr.html + +http://developer.android.com/reference/org/apache/http/protocol/HttpRequestExecutor.html +http://developer.android.com/reference/org/apache/http/protocol/HttpProcessor.html + +http://developer.android.com/reference/org/apache/http/impl/DefaultHttpRequestFactory.html +http://developer.android.com/reference/javax/crypto/interfaces/PBEKey.html + +http://developer.android.com/reference/java/lang/annotation/Annotation.html +http://developer.android.com/reference/java/lang/annotation/AnnotationTypeMismatchException.html + +http://developer.android.com/reference/java/lang/annotation/IncompleteAnnotationException.html + +http://developer.android.com/reference/java/lang/annotation/AnnotationFormatError.html +http://developer.android.com/reference/java/lang/annotation/package-descr.html + +http://developer.android.com/reference/android/app/package-descr.html +http://developer.android.com/reference/java/lang/reflect/Method.html + +http://developer.android.com/reference/org/apache/http/message/BasicHttpEntityEnclosingRequest.html + +http://developer.android.com/reference/org/apache/http/message/BasicHttpRequest.html +http://developer.android.com/reference/org/apache/http/message/BasicHttpResponse.html + +http://developer.android.com/guide/samples/NotePad/src/com/index.html +http://developer.android.com/reference/org/apache/http/io/HttpMessageWriter.html + +http://developer.android.com/reference/org/apache/http/io/package-descr.html +http://developer.android.com/reference/android/location/LocationListener.html + +http://developer.android.com/reference/android/location/Geocoder.html +http://developer.android.com/reference/android/location/LocationProvider.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/AbstractCookieAttributeHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/AbstractCookieSpec.html +http://developer.android.com/reference/org/apache/http/impl/cookie/BasicCommentHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/BasicDomainHandler.html +http://developer.android.com/reference/org/apache/http/impl/cookie/BasicExpiresHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/BasicMaxAgeHandler.html +http://developer.android.com/reference/org/apache/http/impl/cookie/BasicPathHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/BasicSecureHandler.html +http://developer.android.com/reference/org/apache/http/impl/cookie/BestMatchSpec.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/BestMatchSpecFactory.html +http://developer.android.com/reference/org/apache/http/impl/cookie/BrowserCompatSpec.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/BrowserCompatSpecFactory.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/CookieSpecBase.html +http://developer.android.com/reference/org/apache/http/impl/cookie/DateUtils.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/NetscapeDomainHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/NetscapeDraftHeaderParser.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/NetscapeDraftSpec.html +http://developer.android.com/reference/org/apache/http/impl/cookie/NetscapeDraftSpecFactory.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2109DomainHandler.html +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2109Spec.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2109SpecFactory.html +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2109VersionHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2965CommentUrlAttributeHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2965DiscardAttributeHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2965DomainAttributeHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2965PortAttributeHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2965Spec.html +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2965SpecFactory.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/RFC2965VersionAttributeHandler.html + +http://developer.android.com/reference/org/apache/http/impl/cookie/DateParseException.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LabelView.java + +http://developer.android.com/reference/android/net/http/SslCertificate.html +http://developer.android.com/reference/android/net/http/SslCertificate.DName.html + +http://developer.android.com/reference/android/test/mock/MockContentResolver.html +http://developer.android.com/reference/android/test/mock/MockDialogInterface.html + +http://developer.android.com/reference/android/test/mock/MockResources.html +http://developer.android.com/reference/android/test/mock/package-descr.html + +http://developer.android.com/reference/junit/framework/Protectable.html +http://developer.android.com/reference/junit/framework/TestFailure.html + +http://developer.android.com/reference/junit/framework/ComparisonFailure.html +http://developer.android.com/reference/android/test/suitebuilder/TestSuiteBuilder.FailedToCreateTests.html + +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicBoolean.html + +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicIntegerArray.html +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.html + +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicLongArray.html +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicLongFieldUpdater.html + +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicMarkableReference.html + +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicReference.html +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicReferenceArray.html + +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.html + +http://developer.android.com/reference/java/util/concurrent/atomic/AtomicStampedReference.html + +http://developer.android.com/reference/java/util/concurrent/atomic/package-descr.html +http://developer.android.com/reference/org/apache/http/impl/AbstractHttpClientConnection.html + +http://developer.android.com/reference/org/apache/http/impl/AbstractHttpServerConnection.html + +http://developer.android.com/reference/java/util/concurrent/locks/AbstractQueuedSynchronizer.html + +http://developer.android.com/reference/java/util/concurrent/locks/AbstractQueuedSynchronizer.ConditionObject.html + +http://developer.android.com/reference/org/apache/http/conn/ssl/AbstractVerifier.html +http://developer.android.com/reference/java/lang/reflect/AccessibleObject.html + +http://developer.android.com/reference/java/util/zip/Adler32.html +http://developer.android.com/reference/android/text/style/AlignmentSpan.Standard.html + +http://developer.android.com/reference/java/lang/reflect/Array.html +http://developer.android.com/reference/android/media/AsyncPlayer.html + +http://developer.android.com/reference/org/apache/http/client/params/AuthPolicy.html +http://developer.android.com/reference/org/apache/http/message/BasicHeaderElementIterator.html + +http://developer.android.com/reference/org/apache/http/message/BasicHeaderValueFormatter.html + +http://developer.android.com/reference/org/apache/http/message/BasicHeaderValueParser.html +http://developer.android.com/reference/org/apache/http/protocol/BasicHttpContext.html + +http://developer.android.com/reference/org/apache/http/message/BasicLineFormatter.html +http://developer.android.com/reference/org/apache/http/message/BasicLineParser.html + +http://developer.android.com/reference/android/text/style/BulletSpan.html +http://developer.android.com/reference/org/apache/http/util/ByteArrayBuffer.html + +http://developer.android.com/reference/java/util/zip/CRC32.html +http://developer.android.com/reference/android/hardware/Camera.Parameters.html + +http://developer.android.com/reference/android/hardware/Camera.Size.html +http://developer.android.com/reference/android/text/style/CharacterStyle.html + +http://developer.android.com/reference/java/nio/charset/spi/CharsetProvider.html +http://developer.android.com/reference/org/apache/http/client/utils/CloneUtils.html + +http://developer.android.com/reference/org/apache/http/conn/params/ConnManagerParams.html +http://developer.android.com/reference/org/apache/http/conn/params/ConnPerRouteBean.html + +http://developer.android.com/reference/org/apache/http/conn/params/ConnRouteParams.html +http://developer.android.com/reference/org/apache/http/client/params/CookiePolicy.html + +http://developer.android.com/reference/org/apache/http/impl/DefaultHttpResponseFactory.html +http://developer.android.com/reference/org/apache/http/protocol/DefaultedHttpContext.html + +http://developer.android.com/reference/java/util/zip/Deflater.html +http://developer.android.com/reference/android/text/style/DrawableMarginSpan.html + +http://developer.android.com/reference/org/apache/http/util/EncodingUtils.html +http://developer.android.com/reference/org/apache/http/impl/entity/EntityDeserializer.html + +http://developer.android.com/reference/org/apache/http/impl/entity/EntitySerializer.html +http://developer.android.com/reference/org/apache/http/util/EntityUtils.html + +http://developer.android.com/reference/org/apache/http/util/ExceptionUtils.html +http://developer.android.com/reference/android/media/FaceDetector.html + +http://developer.android.com/reference/android/media/FaceDetector.Face.html +http://developer.android.com/reference/android/opengl/GLDebugHelper.html + +http://developer.android.com/reference/android/opengl/GLU.html +http://developer.android.com/reference/android/opengl/GLUtils.html + +http://developer.android.com/reference/org/apache/http/client/params/HttpClientParams.html +http://developer.android.com/reference/org/apache/http/impl/HttpConnectionMetricsImpl.html + +http://developer.android.com/reference/org/apache/http/protocol/HttpDateGenerator.html +http://developer.android.com/reference/org/apache/http/protocol/HttpRequestHandlerRegistry.html + +http://developer.android.com/reference/org/apache/http/protocol/HttpService.html +http://developer.android.com/reference/android/text/style/IconMarginSpan.html + +http://developer.android.com/reference/org/apache/http/conn/util/InetAddressUtils.html +http://developer.android.com/reference/org/json/JSONArray.html + +http://developer.android.com/reference/org/json/JSONObject.html +http://developer.android.com/reference/org/json/JSONStringer.html + +http://developer.android.com/reference/org/json/JSONTokener.html +http://developer.android.com/reference/org/apache/http/util/LangUtils.html + +http://developer.android.com/reference/org/apache/http/impl/entity/LaxContentLengthStrategy.html + +http://developer.android.com/reference/android/text/style/LeadingMarginSpan.Standard.html +http://developer.android.com/reference/java/util/concurrent/locks/LockSupport.html + +http://developer.android.com/reference/java/util/regex/Matcher.html +http://developer.android.com/reference/android/opengl/Matrix.html + +http://developer.android.com/reference/android/media/MediaRecorder.AudioEncoder.html +http://developer.android.com/reference/android/media/MediaRecorder.AudioSource.html + +http://developer.android.com/reference/android/media/MediaRecorder.OutputFormat.html +http://developer.android.com/reference/android/media/MediaScannerConnection.html + +http://developer.android.com/reference/java/lang/reflect/Modifier.html +http://developer.android.com/reference/org/apache/http/message/ParserCursor.html + +http://developer.android.com/reference/org/apache/http/conn/scheme/PlainSocketFactory.html +http://developer.android.com/reference/android/text/style/QuoteSpan.html + +http://developer.android.com/reference/java/util/concurrent/locks/ReentrantLock.html +http://developer.android.com/reference/java/util/concurrent/locks/ReentrantReadWriteLock.html + +http://developer.android.com/reference/java/util/concurrent/locks/ReentrantReadWriteLock.ReadLock.html + +http://developer.android.com/reference/java/util/concurrent/locks/ReentrantReadWriteLock.WriteLock.html + +http://developer.android.com/reference/org/apache/http/protocol/RequestConnControl.html +http://developer.android.com/reference/org/apache/http/protocol/RequestContent.html + +http://developer.android.com/reference/org/apache/http/protocol/RequestDate.html +http://developer.android.com/reference/org/apache/http/protocol/RequestExpectContinue.html + +http://developer.android.com/reference/org/apache/http/protocol/RequestTargetHost.html +http://developer.android.com/reference/org/apache/http/protocol/RequestUserAgent.html + +http://developer.android.com/reference/org/apache/http/protocol/ResponseConnControl.html +http://developer.android.com/reference/org/apache/http/protocol/ResponseContent.html + +http://developer.android.com/reference/org/apache/http/protocol/ResponseDate.html +http://developer.android.com/reference/org/apache/http/protocol/ResponseServer.html + +http://developer.android.com/reference/android/media/Ringtone.html +http://developer.android.com/reference/org/apache/http/conn/ssl/SSLSocketFactory.html + +http://developer.android.com/reference/org/apache/http/conn/scheme/Scheme.html +http://developer.android.com/reference/org/apache/http/conn/scheme/SchemeRegistry.html + +http://developer.android.com/reference/javax/net/ServerSocketFactory.html +http://developer.android.com/reference/android/telephony/gsm/SmsManager.html + +http://developer.android.com/reference/android/telephony/gsm/SmsMessage.html +http://developer.android.com/reference/android/telephony/gsm/SmsMessage.SubmitPdu.html + +http://developer.android.com/reference/android/media/SoundPool.html +http://developer.android.com/reference/org/apache/http/impl/entity/StrictContentLengthStrategy.html + +http://developer.android.com/reference/android/text/style/TabStopSpan.Standard.html +http://developer.android.com/reference/android/test/suitebuilder/TestMethod.html + +http://developer.android.com/reference/android/test/suitebuilder/TestSuiteBuilder.html +http://developer.android.com/reference/android/media/ToneGenerator.html + +http://developer.android.com/reference/org/apache/http/client/utils/URIUtils.html +http://developer.android.com/reference/org/apache/http/client/utils/URLEncodedUtils.html + +http://developer.android.com/reference/org/apache/http/protocol/UriPatternMatcher.html +http://developer.android.com/reference/junit/runner/Version.html + +http://developer.android.com/reference/org/apache/http/util/VersionInfo.html +http://developer.android.com/reference/org/xmlpull/v1/XmlPullParserFactory.html + +http://developer.android.com/reference/java/util/concurrent/locks/Lock.html +http://developer.android.com/reference/org/apache/http/conn/ssl/X509HostnameVerifier.html + +http://developer.android.com/reference/java/util/concurrent/locks/ReadWriteLock.html +http://developer.android.com/reference/android/text/style/AbsoluteSizeSpan.html + +http://developer.android.com/reference/org/apache/http/conn/ssl/AllowAllHostnameVerifier.html + +http://developer.android.com/reference/android/text/style/BackgroundColorSpan.html +http://developer.android.com/reference/org/apache/http/conn/ssl/BrowserCompatHostnameVerifier.html + +http://developer.android.com/reference/java/util/zip/CheckedInputStream.html +http://developer.android.com/reference/java/util/zip/CheckedOutputStream.html + +http://developer.android.com/reference/android/text/style/ClickableSpan.html +http://developer.android.com/reference/org/apache/http/client/params/ClientParamBean.html + +http://developer.android.com/reference/org/apache/http/conn/params/ConnConnectionParamBean.html + +http://developer.android.com/reference/org/apache/http/conn/params/ConnManagerParamBean.html +http://developer.android.com/reference/org/apache/http/conn/params/ConnRouteParamBean.html + +http://developer.android.com/reference/javax/sql/ConnectionEvent.html +http://developer.android.com/reference/java/lang/reflect/Constructor.html + +http://developer.android.com/reference/org/apache/http/cookie/params/CookieSpecParamBean.html + +http://developer.android.com/reference/org/w3c/dom/DOMException.html +http://developer.android.com/reference/java/util/zip/DataFormatException.html + +http://developer.android.com/reference/org/apache/http/impl/DefaultHttpClientConnection.html +http://developer.android.com/reference/org/apache/http/impl/DefaultHttpServerConnection.html + +http://developer.android.com/reference/java/util/zip/DeflaterOutputStream.html +http://developer.android.com/reference/android/text/style/DynamicDrawableSpan.html + +http://developer.android.com/reference/java/lang/reflect/Field.html +http://developer.android.com/reference/android/text/style/ForegroundColorSpan.html + +http://developer.android.com/reference/android/opengl/GLException.html +http://developer.android.com/reference/java/util/zip/GZIPInputStream.html + +http://developer.android.com/reference/java/util/zip/GZIPOutputStream.html +http://developer.android.com/reference/java/lang/reflect/GenericSignatureFormatError.html + +http://developer.android.com/reference/android/text/style/ImageSpan.html +http://developer.android.com/reference/java/lang/reflect/InvocationTargetException.html + +http://developer.android.com/reference/org/json/JSONException.html +http://developer.android.com/reference/java/lang/reflect/MalformedParameterizedTypeException.html + +http://developer.android.com/reference/android/text/style/MaskFilterSpan.html +http://developer.android.com/reference/android/text/style/MetricAffectingSpan.html + +http://developer.android.com/reference/android/text/style/RasterizerSpan.html +http://developer.android.com/reference/android/text/style/RelativeSizeSpan.html + +http://developer.android.com/reference/android/text/style/ReplacementSpan.html +http://developer.android.com/reference/javax/sql/RowSetEvent.html + +http://developer.android.com/reference/android/text/style/ScaleXSpan.html +http://developer.android.com/reference/org/apache/http/impl/SocketHttpClientConnection.html + +http://developer.android.com/reference/org/apache/http/impl/SocketHttpServerConnection.html +http://developer.android.com/reference/org/apache/http/conn/ssl/StrictHostnameVerifier.html + +http://developer.android.com/reference/android/text/style/StrikethroughSpan.html +http://developer.android.com/reference/android/text/style/StyleSpan.html + +http://developer.android.com/reference/android/text/style/SubscriptSpan.html +http://developer.android.com/reference/android/text/style/SuperscriptSpan.html + +http://developer.android.com/reference/org/apache/http/protocol/SyncBasicHttpContext.html +http://developer.android.com/reference/android/text/style/TextAppearanceSpan.html + +http://developer.android.com/reference/android/text/style/TypefaceSpan.html +http://developer.android.com/reference/java/lang/reflect/UndeclaredThrowableException.html + +http://developer.android.com/reference/android/text/style/UnderlineSpan.html +http://developer.android.com/reference/java/util/zip/ZipException.html + +http://developer.android.com/reference/java/util/zip/ZipOutputStream.html +http://developer.android.com/reference/android/media/MediaPlayer.OnBufferingUpdateListener.html + +http://developer.android.com/reference/android/media/MediaPlayer.OnCompletionListener.html +http://developer.android.com/reference/android/media/MediaPlayer.OnErrorListener.html + +http://developer.android.com/reference/android/media/MediaPlayer.OnPreparedListener.html +http://developer.android.com/reference/android/media/MediaPlayer.OnSeekCompleteListener.html + +http://developer.android.com/reference/android/media/MediaScannerConnection.MediaScannerConnectionClient.html + +http://developer.android.com/reference/java/util/zip/Checksum.html +http://developer.android.com/guide/developing/tools/adt.html + +http://developer.android.com/reference/org/apache/http/client/params/AllClientPNames.html +http://developer.android.com/reference/org/apache/http/message/HeaderValueFormatter.html + +http://developer.android.com/reference/org/apache/http/message/HeaderValueParser.html +http://developer.android.com/reference/org/apache/http/message/LineFormatter.html + +http://developer.android.com/reference/java/lang/package-descr.html +http://developer.android.com/reference/org/apache/http/conn/params/ConnConnectionPNames.html + +http://developer.android.com/reference/org/apache/http/conn/params/ConnManagerPNames.html +http://developer.android.com/reference/org/apache/http/conn/params/ConnPerRoute.html + +http://developer.android.com/reference/org/apache/http/conn/params/ConnRoutePNames.html +http://developer.android.com/reference/org/apache/http/conn/scheme/HostNameResolver.html + +http://developer.android.com/reference/org/apache/http/conn/scheme/LayeredSocketFactory.html +http://developer.android.com/reference/android/text/style/AlignmentSpan.html + +http://developer.android.com/reference/java/lang/reflect/AnnotatedElement.html +http://developer.android.com/reference/org/w3c/dom/Attr.html + +http://developer.android.com/reference/android/hardware/Camera.AutoFocusCallback.html +http://developer.android.com/reference/android/hardware/Camera.ErrorCallback.html + +http://developer.android.com/reference/android/hardware/Camera.PictureCallback.html +http://developer.android.com/reference/android/hardware/Camera.PreviewCallback.html + +http://developer.android.com/reference/android/hardware/Camera.ShutterCallback.html +http://developer.android.com/reference/org/w3c/dom/CDATASection.html + +http://developer.android.com/reference/org/w3c/dom/CharacterData.html +http://developer.android.com/reference/org/apache/http/client/params/ClientPNames.html + +http://developer.android.com/reference/org/w3c/dom/Comment.html +http://developer.android.com/reference/java/util/concurrent/locks/Condition.html + +http://developer.android.com/reference/javax/sql/ConnectionEventListener.html +http://developer.android.com/reference/javax/sql/ConnectionPoolDataSource.html + +http://developer.android.com/reference/org/apache/http/cookie/params/CookieSpecPNames.html +http://developer.android.com/reference/javax/sql/DataSource.html + +http://developer.android.com/reference/java/lang/Deprecated.html +http://developer.android.com/reference/javax/crypto/interfaces/DHKey.html + +http://developer.android.com/reference/javax/crypto/interfaces/DHPrivateKey.html +http://developer.android.com/reference/javax/crypto/interfaces/DHPublicKey.html + +http://developer.android.com/reference/org/w3c/dom/Document.html +http://developer.android.com/reference/java/lang/annotation/Documented.html + +http://developer.android.com/reference/org/w3c/dom/DocumentFragment.html +http://developer.android.com/reference/org/w3c/dom/DocumentType.html + +http://developer.android.com/reference/org/w3c/dom/DOMImplementation.html +http://developer.android.com/reference/java/security/interfaces/DSAKey.html + +http://developer.android.com/reference/java/security/interfaces/DSAKeyPairGenerator.html +http://developer.android.com/reference/java/security/interfaces/DSAParams.html + +http://developer.android.com/reference/java/security/interfaces/DSAPrivateKey.html +http://developer.android.com/reference/java/security/interfaces/DSAPublicKey.html + +http://developer.android.com/reference/java/security/interfaces/ECKey.html +http://developer.android.com/reference/java/security/interfaces/ECPrivateKey.html + +http://developer.android.com/reference/java/security/interfaces/ECPublicKey.html +http://developer.android.com/reference/org/w3c/dom/Element.html + +http://developer.android.com/reference/org/w3c/dom/Entity.html +http://developer.android.com/reference/org/w3c/dom/EntityReference.html + +http://developer.android.com/reference/org/apache/http/protocol/ExecutionContext.html +http://developer.android.com/reference/android/test/FlakyTest.html + +http://developer.android.com/reference/java/lang/reflect/GenericArrayType.html +http://developer.android.com/reference/java/lang/reflect/GenericDeclaration.html + +http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html +http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10Ext.html + +http://developer.android.com/reference/javax/microedition/khronos/opengles/GL11.html +http://developer.android.com/reference/javax/microedition/khronos/opengles/GL11Ext.html + +http://developer.android.com/reference/javax/microedition/khronos/opengles/GL11ExtensionPack.html + +http://developer.android.com/reference/org/apache/http/protocol/HttpExpectationVerifier.html +http://developer.android.com/reference/org/apache/http/protocol/HttpRequestHandler.html + +http://developer.android.com/reference/org/apache/http/protocol/HttpRequestHandlerResolver.html + +http://developer.android.com/reference/org/apache/http/protocol/HttpRequestInterceptorList.html + +http://developer.android.com/reference/org/apache/http/protocol/HttpResponseInterceptorList.html + +http://developer.android.com/reference/java/lang/annotation/Inherited.html +http://developer.android.com/reference/java/lang/reflect/InvocationHandler.html + +http://developer.android.com/reference/android/text/style/LeadingMarginSpan.html +http://developer.android.com/reference/android/text/style/LineBackgroundSpan.html + +http://developer.android.com/reference/android/text/style/LineHeightSpan.html +http://developer.android.com/reference/java/util/regex/MatchResult.html + +http://developer.android.com/reference/java/lang/reflect/Member.html +http://developer.android.com/reference/org/w3c/dom/NamedNodeMap.html + +http://developer.android.com/reference/org/w3c/dom/Node.html +http://developer.android.com/reference/org/w3c/dom/NodeList.html + +http://developer.android.com/reference/org/w3c/dom/Notation.html +http://developer.android.com/reference/dalvik/bytecode/Opcodes.html + +http://developer.android.com/reference/java/lang/Override.html +http://developer.android.com/reference/android/text/style/ParagraphStyle.html + +http://developer.android.com/reference/java/lang/reflect/ParameterizedType.html +http://developer.android.com/reference/javax/sql/PooledConnection.html + +http://developer.android.com/reference/org/w3c/dom/ProcessingInstruction.html +http://developer.android.com/reference/java/lang/reflect/Proxy.html + +http://developer.android.com/reference/java/lang/annotation/Retention.html +http://developer.android.com/reference/javax/sql/RowSetInternal.html + +http://developer.android.com/reference/javax/sql/RowSetListener.html +http://developer.android.com/reference/javax/sql/RowSetMetaData.html + +http://developer.android.com/reference/javax/sql/RowSetReader.html +http://developer.android.com/reference/javax/sql/RowSetWriter.html + +http://developer.android.com/reference/java/security/interfaces/RSAKey.html +http://developer.android.com/reference/java/security/interfaces/RSAMultiPrimePrivateCrtKey.html + +http://developer.android.com/reference/java/security/interfaces/RSAPrivateCrtKey.html +http://developer.android.com/reference/java/security/interfaces/RSAPrivateKey.html + +http://developer.android.com/reference/java/security/interfaces/RSAPublicKey.html +http://developer.android.com/reference/android/hardware/SensorListener.html + +http://developer.android.com/reference/android/test/suitebuilder/annotation/Smoke.html +http://developer.android.com/reference/android/test/suitebuilder/annotation/Suppress.html + +http://developer.android.com/reference/java/lang/SuppressWarnings.html +http://developer.android.com/reference/android/text/style/TabStopSpan.html + +http://developer.android.com/reference/java/lang/annotation/Target.html +http://developer.android.com/reference/dalvik/annotation/TestTarget.html + +http://developer.android.com/reference/dalvik/annotation/TestTargetClass.html +http://developer.android.com/reference/org/w3c/dom/Text.html + +http://developer.android.com/reference/java/lang/reflect/Type.html +http://developer.android.com/reference/java/lang/reflect/TypeVariable.html + +http://developer.android.com/reference/android/test/UiThreadTest.html +http://developer.android.com/reference/android/text/style/UpdateLayout.html + +http://developer.android.com/reference/java/lang/reflect/WildcardType.html +http://developer.android.com/reference/android/text/style/WrapTogetherSpan.html + +http://developer.android.com/reference/org/xmlpull/v1/XmlSerializer.html + +http://developer.android.com/reference/java/util/zip/package-descr.html +http://developer.android.com/reference/javax/security/auth/login/package-descr.html + +http://developer.android.com/reference/android/text/style/package-descr.html + +http://developer.android.com/reference/java/nio/channels/package-descr.html +http://developer.android.com/reference/android/opengl/package-descr.html + +http://developer.android.com/guide/tutorials/notepad/notepad-ex1.html + +http://developer.android.com/guide/tutorials/notepad/notepad-ex2.html +http://developer.android.com/guide/tutorials/notepad/notepad-ex3.html + +http://developer.android.com/guide/tutorials/notepad/notepad-extra-credit.html +http://developer.android.com/reference/java/util/package-descr.html + +http://developer.android.com/reference/org/apache/http/client/methods/package-descr.html +http://developer.android.com/reference/android/os/package-descr.html + +http://developer.android.com/reference/org/apache/http/client/utils/package-descr.html + +http://developer.android.com/reference/org/apache/http/impl/package-descr.html + +http://developer.android.com/reference/java/io/package-descr.html +http://developer.android.com/guide/samples/NotePad/src/com/example/index.html + +http://developer.android.com/reference/java/nio/charset/spi/package-descr.html + +http://developer.android.com/reference/org/apache/http/impl/entity/package-descr.html + +http://developer.android.com/guide/samples/LunarLander/res/index.html + +http://developer.android.com/guide/samples/LunarLander/src/index.html +http://developer.android.com/guide/samples/LunarLander/tests/index.html + +http://developer.android.com/guide/samples/LunarLander/AndroidManifest.html +http://developer.android.com/guide/samples/LunarLander/sample_lunarlander.html + +http://developer.android.com/reference/javax/crypto/interfaces/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/content/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/index.html + +http://developer.android.com/guide/samples/ApiDemos/assets/index.html +http://developer.android.com/guide/samples/ApiDemos/res/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/index.html +http://developer.android.com/guide/samples/ApiDemos/tests/index.html + +http://developer.android.com/guide/samples/ApiDemos/AndroidManifest.html +http://developer.android.com/reference/android/widget/package-descr.html +http://developer.android.com/reference/org/apache/http/conn/params/package-descr.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/index.html +http://developer.android.com/guide/samples/ApiDemos/tests/AndroidManifest.html + +http://developer.android.com/reference/android/test/suitebuilder/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/content/StyledText.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/content/ResourcesSample.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/content/ReadAsset.html + +http://developer.android.com/reference/android/view/package-descr.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/HelloWorld.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SaveRestoreState.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/PersistentState.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ReceiveResult.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/Forwarding.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RedirectEnter.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/TranslucentActivity.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceController.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceBinding.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RemoteServiceController.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RemoteServiceBinding.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ServiceStartArgumentsController.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ServiceStartArguments.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AlarmController.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/OneShotAlarm.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RepeatingAlarm.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AlarmService.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AlarmService_Service.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/NotifyWithText.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessage.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SearchInvoke.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SearchQueryResults.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SearchSuggestionSampleProvider.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AdvancedPreferences.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AlertDialogSamples.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ContactsFilter.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ContactsFilterInstrumentation.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ContactsSelectInstrumentation.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/CustomDialogActivity.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/CustomTitle.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/DefaultValues.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/DialogActivity.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ForwardTarget.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessageView.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LauncherShortcuts.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LaunchingPreferences.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalSample.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalSampleInstrumentation.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/MenuInflateFromXml.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/MyPreference.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/NotifyingController.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/NotifyingService.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/PreferenceDependencies.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/PreferencesFromCode.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/PreferencesFromXml.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RedirectGetter.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RedirectMain.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SendResult.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/StatusBarNotifications.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/TranslucentBlurActivity.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/CustomDialogActivity.java + +http://developer.android.com/reference/org/w3c/dom/package-descr.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceBinding.java + +http://developer.android.com/guide/samples/ApiDemos/res/anim/index.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/index.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/index.html +http://developer.android.com/guide/samples/ApiDemos/res/menu/index.html + +http://developer.android.com/guide/samples/ApiDemos/res/raw/index.html +http://developer.android.com/guide/samples/ApiDemos/res/values/index.html + +http://developer.android.com/guide/samples/ApiDemos/res/xml/index.html +http://developer.android.com/reference/java/sql/package-descr.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RepeatingAlarm.java + +http://developer.android.com/guide/samples/LunarLander/res/drawable/index.html +http://developer.android.com/guide/samples/LunarLander/res/drawable-land/index.html + +http://developer.android.com/guide/samples/LunarLander/res/drawable-port/index.html +http://developer.android.com/guide/samples/LunarLander/res/layout/index.html + +http://developer.android.com/guide/samples/LunarLander/res/values/index.html +http://developer.android.com/reference/android/util/package-descr.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalSampleInstrumentation.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RedirectMain.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/Forwarding.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ContactsFilterInstrumentation.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SearchSuggestionSampleProvider.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LaunchingPreferences.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SearchInvoke.java + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/index.html + +http://developer.android.com/reference/android/content/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ShapeDrawable1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/PolyToPoly.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/DrawPoints.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/PathEffects.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/SurfaceViewOverlay.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TouchPaint.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/AlphaBitmap.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/AnimateDrawable.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/AnimateDrawables.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Arcs.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/BitmapDecode.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/BitmapMesh.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Clipping.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ColorMatrixSample.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ColorPickerDialog.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Compass.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/CreateBitmap.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Cube.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/CubeRenderer.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/FingerPaint.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/GradientDrawable1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/GraphicsActivity.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Layers.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/MeasureText.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/PathFillTypes.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Patterns.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/PictureLayout.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Pictures.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ProxyDrawable.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Regions.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/RoundRects.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ScaleToFit.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/SensorTest.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Sweep.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TextAlign.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TranslucentGLSurfaceViewActivity.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TriangleActivity.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TriangleRenderer.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Typefaces.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/UnicodeChart.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Vertices.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Xfermodes.html + +http://developer.android.com/guide/samples/NotePad/tests/src/index.html +http://developer.android.com/guide/samples/NotePad/tests/AndroidManifest.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ShapeDrawable1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/AnimateDrawable.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Typefaces.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ServiceStartArgumentsController.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessage.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/RoundRects.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SaveRestoreState.java + +http://developer.android.com/reference/org/apache/http/client/params/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ForwardTarget.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AlertDialogSamples.java + +http://developer.android.com/reference/java/security/spec/package-descr.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/FingerPaint.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TouchPaint.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SearchQueryResults.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/NotifyingController.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ScaleToFit.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/NotifyingService.java + +http://developer.android.com/guide/samples/LunarLander/res/drawable-land/earthrise.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RedirectEnter.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ContactsFilter.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/AnimateDrawables.java + +http://developer.android.com/reference/org/apache/http/conn/ssl/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Arcs.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/CubeRenderer.java + +http://developer.android.com/reference/org/apache/http/message/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TriangleRenderer.java + +http://developer.android.com/guide/samples/ApiDemos/assets/fonts/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/TranslucentBlurActivity.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/Grid.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/LabelMaker.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/MatrixGrabber.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/MatrixStack.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/MatrixTrackingGL.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/NumericSprite.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/Projector.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/SpriteTextActivity.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/SpriteTextRenderer.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/GradientDrawable1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/DialogActivity.java + +http://developer.android.com/reference/android/text/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/BitmapDecode.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/content/ResourcesSample.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TranslucentGLSurfaceViewActivity.java + +http://developer.android.com/reference/org/apache/http/conn/routing/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Vertices.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/PersistentState.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ReceiveResult.java + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/index.html + +http://developer.android.com/reference/com/google/android/maps/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LauncherShortcuts.java + +http://developer.android.com/guide/samples/NotePad/tests/src/com/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/BitmapMesh.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/SurfaceViewOverlay.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/CreateBitmap.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/CustomTitle.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AdvancedPreferences.java + +http://developer.android.com/ +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/GraphicsActivity.java + +http://developer.android.com/guide/samples/ApiDemos/res/xml/advanced_preferences.html + +http://developer.android.com/guide/samples/ApiDemos/res/xml/default_values.html +http://developer.android.com/guide/samples/ApiDemos/res/xml/preference_dependencies.html + +http://developer.android.com/guide/samples/ApiDemos/res/xml/preferences.html +http://developer.android.com/guide/samples/ApiDemos/res/xml/searchable.html + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/NotePad.html + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/NotePadProvider.html + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/NotesList.html + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/TitleEditor.html + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/TitleEditor.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Layers.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RemoteServiceBinding.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Compass.java + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/NotesList.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/DefaultValues.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AlarmService.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/OneShotAlarm.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AlarmController.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/MatrixTrackingGL.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ProxyDrawable.java + +http://developer.android.com/guide/samples/ApiDemos/res/layout/alarm_controller.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/alarm_service.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/alert_dialog.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/alert_dialog_text_entry.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/animation_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/animation_2.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/animations_main_screen.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/autocomplete_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/autocomplete_2.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/autocomplete_3.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/autocomplete_4.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/autocomplete_5.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/autocomplete_6.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_2.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_3.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_4.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_6.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_7.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_nested_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_nested_2.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/baseline_nested_3.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/buttons_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/chronometer.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/contacts_filter.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/controls_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/custom_dialog_activity.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/custom_title.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/custom_title_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/date_widgets_example_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/date_widgets_example_2.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/dialog_activity.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/focus_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/focus_2.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/focus_3.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/forward_target.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/forwarding.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/gallery_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/gallery_2.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/google_login.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/grid_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/grid_2.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/hello_world.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/image_button_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/image_switcher_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/image_view_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/incoming_message.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/incoming_message_info.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/incoming_message_panel.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/incoming_message_view.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/launcher_shortcuts.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/layout_animation_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/layout_animation_3.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/layout_animation_4.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/layout_animation_5.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/layout_animation_6.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/layout_animation_7.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_10.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_2.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_3.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_4.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_5.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_6.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_7.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_8.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/linear_layout_9.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/link.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/list_12.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/list_13.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/list_7.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/list_8.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/list_item_checkbox.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/list_item_icon_text.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/list_position.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/local_sample.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/local_service_binding.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/local_service_controller.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/log_text_box_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/mapview.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/marquee.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/mediaplayer_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/mediaplayer_2.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/morse_code.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/notify_with_text.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/notifying_controller.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/preference_widget_mypreference.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/progressbar_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/progressbar_2.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/progressbar_3.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/progressbar_4.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/radio_group_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/ratingbar_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/read_asset.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/receive_result.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/redirect_enter.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/redirect_getter.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/redirect_main.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/relative_layout_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/relative_layout_2.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/remote_service_binding.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/remote_service_controller.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/resources.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/save_restore_state.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/scroll_view_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/scroll_view_2.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/scrollbar1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/scrollbar2.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/scrollbar3.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/search_invoke.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/search_query_results.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/seekbar_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/select_dialog.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/send_result.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/service_start_arguments_controller.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/shape_drawable_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/spinner_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/status_bar_balloon.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/status_bar_notifications.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/styled_text.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/surface_view_overlay.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_10.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_11.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_12.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_2.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_3.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_4.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_5.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_6.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_7.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_8.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/table_layout_9.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/tabs1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/text_switcher_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/translucent_background.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/videoview.html + +http://developer.android.com/guide/samples/ApiDemos/res/layout/visibility_1.html +http://developer.android.com/guide/samples/ApiDemos/res/layout/webview_1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/NumericSprite.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/TranslucentActivity.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceController.java + +http://developer.android.com/guide/samples/ApiDemos/res/menu/category_order.html +http://developer.android.com/guide/samples/ApiDemos/res/menu/checkable.html + +http://developer.android.com/guide/samples/ApiDemos/res/menu/disabled.html +http://developer.android.com/guide/samples/ApiDemos/res/menu/groups.html + +http://developer.android.com/guide/samples/ApiDemos/res/menu/order.html +http://developer.android.com/guide/samples/ApiDemos/res/menu/shortcuts.html + +http://developer.android.com/guide/samples/ApiDemos/res/menu/submenu.html +http://developer.android.com/guide/samples/ApiDemos/res/menu/title_icon.html + +http://developer.android.com/guide/samples/ApiDemos/res/menu/title_only.html +http://developer.android.com/guide/samples/ApiDemos/res/menu/visible.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Clipping.java + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/alert_dialog_icon.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/animated_gif.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/app_sample_code.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/arrow_down_float.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/arrow_up_float.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/balloons.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/beach.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/black_box.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/black_opaque_box.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/box.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/button.9.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/circular_progress.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/filled_box.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/frog.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_background_1.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_photo_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_photo_2.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_photo_3.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_photo_4.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_photo_5.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_photo_6.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_photo_7.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/gallery_photo_8.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/ic_popup_reminder.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/icon48x48_1.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/icon48x48_2.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/line.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/photo1.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/photo2.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/photo3.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/photo4.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/photo5.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/photo6.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/picture_frame.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/progress_circular_background.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/progress_particle.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/robot.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_0.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_2.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_3.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_4.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_5.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_6.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_7.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_thumb_0.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_thumb_1.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_thumb_2.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_thumb_3.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_thumb_4.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_thumb_5.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_thumb_6.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/sample_thumb_7.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/scrollbar_state2.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/scrollbar_vertical_thumb.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/scrollbar_vertical_track.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/shape_1.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/shape_2.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/shape_3.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/shape_4.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/shape_5.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/star_big_on.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/stat_happy.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/stat_neutral.html + +http://developer.android.com/guide/samples/ApiDemos/res/drawable/stat_sad.html +http://developer.android.com/guide/samples/ApiDemos/res/drawable/stat_sample.html + +http://developer.android.com/guide/samples/LunarLander/res/layout/lunar_layout.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Cube.java + +http://developer.android.com/reference/android/hardware/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/GLSurfaceViewActivity.java + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/NotePadProvider.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RemoteServiceController.java + +http://developer.android.com/reference/junit/runner/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TextAlign.java + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/NotePad.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/Projector.java + +http://developer.android.com/guide/samples/LunarLander/tests/src/index.html +http://developer.android.com/guide/samples/LunarLander/tests/AndroidManifest.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ColorMatrixSample.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/PreferencesFromXml.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/MeasureText.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/ColorPickerDialog.java + +http://developer.android.com/guide/samples/LunarLander/res/drawable/app_lunar_lander.html +http://developer.android.com/guide/samples/LunarLander/res/drawable/lander_crashed.html + +http://developer.android.com/guide/samples/LunarLander/res/drawable/lander_firing.html +http://developer.android.com/guide/samples/LunarLander/res/drawable/lander_plain.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/content/StyledText.java + +http://developer.android.com/reference/org/apache/http/package-descr.html +http://developer.android.com/reference/javax/net/ssl/package-descr.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/RedirectGetter.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/DrawPoints.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/MyPreference.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/PathEffects.java + +http://developer.android.com/guide/samples/LunarLander/res/values/strings.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/cycle_7.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/fade.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/hyperspace_in.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/hyperspace_out.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/layout_animation_row_left_slide.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/layout_animation_row_right_slide.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/layout_animation_table.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/layout_bottom_to_top_slide.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/layout_grid_fade.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/layout_grid_inverse_fade.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/layout_random_fade.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/layout_wave_scale.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/push_left_in.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/push_left_out.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/push_up_in.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/push_up_out.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/shake.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/slide_left.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/slide_right.html +http://developer.android.com/guide/samples/ApiDemos/res/anim/slide_top_to_bottom.html + +http://developer.android.com/guide/samples/ApiDemos/res/anim/wave_scale.html + +http://developer.android.com/guide/tutorials/views/hello-datepicker.html + +http://developer.android.com/guide/tutorials/views/hello-timepicker.html +http://developer.android.com/guide/tutorials/views/hello-autocomplete.html + +http://developer.android.com/guide/tutorials/views/hello-gallery.html +http://developer.android.com/guide/tutorials/views/hello-tabwidget.html + +http://developer.android.com/guide/tutorials/views/hello-mapview.html +http://developer.android.com/guide/tutorials/views/hello-webview.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/SpriteTextActivity.java + +http://developer.android.com/guide/samples/NotePad/src/com/example/android/notepad/NoteEditor.java + +http://developer.android.com/reference/java/util/concurrent/locks/package-descr.html +http://developer.android.com/guide/samples/NotePad/tests/src/com/example/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/PictureLayout.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/MatrixGrabber.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/RelativeLayout1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/RelativeLayout2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout4.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout5.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout6.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout7.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout8.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout9.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollView1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollView2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout4.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout5.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout6.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout7.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout8.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout9.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout10.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout11.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout12.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline4.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline6.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline7.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/BaselineNested1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/BaselineNested2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/BaselineNested3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/RadioGroup1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollBar1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollBar2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Visibility1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List4.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List5.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List6.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List7.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List8.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/CustomView1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ImageButton1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/DateWidgets1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/DateWidgets2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Gallery1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Gallery2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Spinner1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Grid1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Grid2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ImageSwitcher1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TextSwitcher1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Animation1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Animation2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Controls1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Controls2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete4.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete5.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar4.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Focus1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Focus2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Focus3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete6.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Buttons1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ChronometerDemo.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ImageView1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/InternalSelectionFocus.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/InternalSelectionScroll.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/InternalSelectionView.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation4.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation5.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation6.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation7.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout10.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List10.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List11.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List12.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List13.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List14.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List9.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/MapViewCompassDemo.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/MapViewDemo.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/RatingBar1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollBar3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/SeekBar1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Tabs1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Tabs2.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Tabs3.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/WebView1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/LabelMaker.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/RelativeLayout1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/CustomView1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation7.java + +http://developer.android.com/reference/android/text/method/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/NotifyWithText.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/InternalSelectionScroll.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/RadioGroup1.java + +http://developer.android.com/reference/org/apache/http/entity/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/TriangleActivity.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Tabs3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/WebView1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List14.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout9.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline7.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout6.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/HelloWorld.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/AlphaBitmap.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Buttons1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout10.java + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout11.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Focus2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout7.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/BaselineNested2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollView2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/MatrixStack.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollBar2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout5.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollBar3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/AlarmService_Service.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete6.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List6.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/Grid.java + +http://developer.android.com/reference/org/apache/http/protocol/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Regions.java + +http://developer.android.com/guide/samples/LunarLander/src/com/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline4.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/PreferencesFromCode.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/PreferenceDependencies.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/GLSurfaceView.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalSample.java + +http://developer.android.com/guide/samples/NotePad/tests/src/com/example/android/index.html +http://developer.android.com/reference/javax/security/auth/callback/package-descr.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List5.java + +http://developer.android.com/reference/javax/sql/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List9.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List8.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/Link.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/LogTextBox.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/LogTextBox1.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/Marquee.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List7.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout10.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline6.java + +http://developer.android.com/reference/android/location/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ImageSwitcher1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ServiceStartArguments.java + +http://developer.android.com/reference/java/util/regex/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/Cube.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLColor.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLFace.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLShape.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLVertex.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLWorld.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/Kube.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/KubeRenderer.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/Layer.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/M4.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar4.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Gallery2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Focus3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Sweep.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List12.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Tabs2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Xfermodes.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/DateWidgets1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Animation2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation4.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLWorld.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/content/ReadAsset.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/BaselineNested1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Tabs1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/PolyToPoly.java + +http://developer.android.com/reference/org/apache/http/cookie/params/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout4.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/StatusBarNotifications.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/LogTextBox.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Pictures.java + +http://developer.android.com/reference/java/security/cert/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List13.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ChronometerDemo.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/KubeRenderer.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/SensorTest.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete5.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/SendResult.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout9.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Controls2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TextSwitcher1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/ContactsSelectInstrumentation.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ImageButton1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout8.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/Kube.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Controls1.java + +http://developer.android.com/reference/org/apache/http/util/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/Layer.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List10.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/BaselineNested3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List4.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollBar1.java + +http://developer.android.com/reference/java/security/interfaces/package-descr.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation5.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout5.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessageView.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Gallery1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLColor.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Visibility1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/DateWidgets2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/PathFillTypes.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout12.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/Patterns.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List3.java + +http://developer.android.com/guide/samples/LunarLander/res/drawable-port/earthrise.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Baseline2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout7.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/TableLayout1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Grid1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/RelativeLayout2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Spinner1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLVertex.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Focus1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout6.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/InternalSelectionFocus.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout4.java + +http://developer.android.com/guide/samples/LunarLander/src/com/example/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/M4.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/InternalSelectionView.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/LogTextBox1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ScrollView1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/RatingBar1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Grid2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/MenuInflateFromXml.java + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/UnicodeChart.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete3.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/Cube.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout8.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List2.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/Marquee.java + +http://developer.android.com/guide/samples/ApiDemos/res/values/arrays.html +http://developer.android.com/guide/samples/ApiDemos/res/values/attrs.html + +http://developer.android.com/guide/samples/ApiDemos/res/values/colors.html +http://developer.android.com/guide/samples/ApiDemos/res/values/ids.html + +http://developer.android.com/guide/samples/ApiDemos/res/values/strings.html +http://developer.android.com/guide/samples/ApiDemos/res/values/styles.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/app/LocalService.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/Animation1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLShape.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation6.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/MapViewCompassDemo.java + +http://developer.android.com/guide/samples/LunarLander/tests/src/com/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List11.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ImageView1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/kube/GLFace.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar3.java + +http://developer.android.com/guide/samples/LunarLander/src/com/example/android/index.html +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/LinearLayout1.java + +http://developer.android.com/guide/samples/NotePad/tests/src/com/example/android/notepad/index.html + +http://developer.android.com/guide/samples/NotePad/tests/src/com/example/android/notepad/NotePadTest.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/SeekBar1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/List1.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/spritetext/SpriteTextRenderer.java + +http://developer.android.com/guide/samples/NotePad/res/drawable/index.html +http://developer.android.com/guide/samples/NotePad/res/layout/index.html + +http://developer.android.com/guide/samples/NotePad/res/values/index.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete4.java + +http://developer.android.com/guide/samples/NotePad/res/drawable/app_notes.html +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/index.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/app/index.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/os/index.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/view/index.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/AllTests.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/ApiDemosApplicationTests.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/ApiDemosTest.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/MapViewDemo.java + +http://developer.android.com/guide/samples/NotePad/tests/src/com/example/android/notepad/NotePadTest.java + +http://developer.android.com/guide/samples/NotePad/res/values/strings.html +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/view/AutoComplete2.java + +http://developer.android.com/guide/samples/LunarLander/tests/src/com/example/index.html +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/view/Focus2ActivityTest.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/view/Focus2AndroidTest.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/ApiDemosTest.java + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/ApiDemosApplicationTests.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/index.html +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/AllTests.java + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/os/MorseCodeConverterTest.html + +http://developer.android.com/guide/samples/LunarLander/tests/src/com/example/android/index.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/app/ForwardingTest.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/app/LocalServiceTest.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/view/Focus2AndroidTest.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/text/Link.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/animation/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/os/index.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/ApiDemos.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/ApiDemosApplication.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/app/ForwardingTest.java + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/view/Focus2ActivityTest.java + +http://developer.android.com/guide/samples/LunarLander/src/com/example/android/lunarlander/index.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/os/MorseCodeConverterTest.java + +http://developer.android.com/guide/samples/NotePad/res/layout/note_editor.html +http://developer.android.com/guide/samples/NotePad/res/layout/noteslist_item.html + +http://developer.android.com/guide/samples/NotePad/res/layout/title_editor.html +http://developer.android.com/guide/samples/LunarLander/tests/src/com/example/android/lunarlander/index.html + +http://developer.android.com/guide/samples/ApiDemos/tests/src/com/example/android/apis/app/LocalServiceTest.java + +http://developer.android.com/guide/samples/LunarLander/src/com/example/android/lunarlander/LunarLander.html + +http://developer.android.com/guide/samples/LunarLander/src/com/example/android/lunarlander/LunarView.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/os/MorseCode.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/os/MorseCodeConverter.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/os/Sensors.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/ApiDemosApplication.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/MediaPlayerDemo.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/MediaPlayerDemo_Audio.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/MediaPlayerDemo_Video.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/VideoViewDemo.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/animation/Rotate3dAnimation.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/animation/Transition3d.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/ApiDemos.java + +http://developer.android.com/guide/samples/LunarLander/tests/src/com/example/android/lunarlander/LunarLanderTest.html + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/os/MorseCode.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/MediaPlayerDemo_Audio.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/os/MorseCodeConverter.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/VideoViewDemo.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/animation/Rotate3dAnimation.java + +http://developer.android.com/guide/samples/LunarLander/src/com/example/android/lunarlander/LunarView.java + +http://developer.android.com/guide/samples/LunarLander/src/com/example/android/lunarlander/LunarLander.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/MediaPlayerDemo.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/os/Sensors.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/media/MediaPlayerDemo_Video.java + +http://developer.android.com/guide/samples/LunarLander/tests/src/com/example/android/lunarlander/LunarLanderTest.java + +http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/animation/Transition3d.java \ No newline at end of file diff --git a/graphics/java/android/graphics/Bitmap.java b/graphics/java/android/graphics/Bitmap.java index dc16c39f4d7e2fdac13cc97952aed614f153a0d0..0b398bc3b965181e26cfcf3a8a93712af6dd9dd0 100644 --- a/graphics/java/android/graphics/Bitmap.java +++ b/graphics/java/android/graphics/Bitmap.java @@ -16,18 +16,25 @@ package android.graphics; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.io.OutputStream; +import android.os.Parcelable; +import android.os.Parcel; + import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ShortBuffer; import java.nio.IntBuffer; - -import android.os.Parcel; -import android.os.Parcelable; +import java.io.OutputStream; public final class Bitmap implements Parcelable { + /** + * Indicates that the bitmap was created for an unknown pixel density. + * + * @see Bitmap#getDensityScale() + * @see Bitmap#setDensityScale(float) + * + * @hide pending API council approval + */ + public static final float DENSITY_SCALE_UNKNOWN = -1.0f; // Note: mNativeBitmap is used by FaceDetector_jni.cpp // Don't change/rename without updating FaceDetector_jni.cpp @@ -41,6 +48,9 @@ public final class Bitmap implements Parcelable { private static volatile Matrix sScaleMatrix; + private float mDensityScale = DENSITY_SCALE_UNKNOWN; + private boolean mAutoScaling; + /** * @noinspection UnusedDeclaration */ @@ -59,6 +69,104 @@ public final class Bitmap implements Parcelable { mIsMutable = isMutable; mNinePatchChunk = ninePatchChunk; } + + /** + *

                  Returns the density scale for this bitmap, expressed as a factor of + * the default density (160.) For instance, a bitmap designed for + * displays with a density of 240 will have a density scale of 1.5 whereas a bitmap + * designed for a density of 160 will have a density scale of 1.0.

                  + * + *

                  The default density scale is {@link #DENSITY_SCALE_UNKNOWN}.

                  + * + * @return A scaling factor of the default density (160) or {@link #DENSITY_SCALE_UNKNOWN} + * if the scaling factor is unknown. + * + * @see #setDensityScale(float) + * @see #isAutoScalingEnabled() + * @see #setAutoScalingEnabled(boolean) + * @see android.util.DisplayMetrics#DEFAULT_DENSITY + * @see android.util.DisplayMetrics#density + * @see #DENSITY_SCALE_UNKNOWN + * + * @hide pending API council approval + */ + public float getDensityScale() { + return mDensityScale; + } + + /** + *

                  Specifies the density scale for this bitmap, expressed as a factor of + * the default density (160.) For instance, a bitmap designed for + * displays with a density of 240 will have a density scale of 1.5 whereas a bitmap + * designed for a density of 160 will have a density scale of 1.0.

                  + * + * @param densityScale The density scaling factor to use with this bitmap or + * {@link #DENSITY_SCALE_UNKNOWN} if the factor is unknown. + * + * @see #getDensityScale() + * @see #isAutoScalingEnabled() + * @see #setAutoScalingEnabled(boolean) + * @see android.util.DisplayMetrics#DEFAULT_DENSITY + * @see android.util.DisplayMetrics#density + * @see #DENSITY_SCALE_UNKNOWN + * + * @hide pending API council approval + */ + public void setDensityScale(float densityScale) { + mDensityScale = densityScale; + } + + /** + *

                  Indicates whether this bitmap will be automatically be scaled at the + * target's density at drawing time. If auto scaling is enabled, this bitmap + * will be drawn with the following scale factor:

                  + * + *
                  scale = (bitmap density scale factor) / (target density scale factor)
                  + * + *

                  Auto scaling is turned off by default. If auto scaling is enabled but the + * bitmap has an unknown density scale, then the bitmap will never be automatically + * scaled at drawing time.

                  + * + * @return True if the bitmap must be scaled at drawing time, false otherwise. + * + * @see #setAutoScalingEnabled(boolean) + * @see #getDensityScale() + * @see #setDensityScale(float) + * + * @hide pending API council approval + */ + public boolean isAutoScalingEnabled() { + return mAutoScaling; + } + + /** + *

                  Enables or disables auto scaling for this bitmap. When auto scaling is enabled, + * the bitmap will be scaled at drawing time to accomodate the drawing target's pixel + * density. The final scale factor for this bitmap is thus defined:

                  + * + *
                  scale = (bitmap density scale factor) / (target density scale factor)
                  + * + *

                  If auto scaling is enabled but the bitmap has an unknown density scale, then + * the bitmap will never be automatically scaled at drawing time.

                  + * + * @param autoScalingEnabled True to scale the bitmap at drawing time, false otherwise. + * + * @hide pending API council approval + */ + public void setAutoScalingEnabled(boolean autoScalingEnabled) { + mAutoScaling = autoScalingEnabled; + } + + /** + * Sets the nine patch chunk. + * + * @param chunk The definition of the nine patch + * + * @hide + */ + public void setNinePatchChunk(byte[] chunk) { + mNinePatchChunk = chunk; + } /** * Free up the memory associated with this bitmap's pixels, and mark the @@ -126,7 +234,7 @@ public final class Bitmap implements Parcelable { throw new IllegalArgumentException("height must be > 0"); } } - + public enum Config { // these native values must match up with the enum in SkBitmap.h ALPHA_8 (2), @@ -232,7 +340,7 @@ public final class Bitmap implements Parcelable { public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter) { - Matrix m = null; + Matrix m; synchronized (Bitmap.class) { // small pool of just 1 matrix m = sScaleMatrix; @@ -279,8 +387,7 @@ public final class Bitmap implements Parcelable { * @param width The number of pixels in each row * @param height The number of rows */ - public static Bitmap createBitmap(Bitmap source, int x, int y, - int width, int height) { + public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) { return createBitmap(source, x, y, width, height, null, false); } @@ -301,23 +408,21 @@ public final class Bitmap implements Parcelable { * @throws IllegalArgumentException if the x, y, width, height values are * outside of the dimensions of the source bitmap. */ - public static Bitmap createBitmap(Bitmap source, int x, int y, int width, - int height, Matrix m, boolean filter) { + public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, + Matrix m, boolean filter) { + checkXYSign(x, y); checkWidthHeight(width, height); if (x + width > source.getWidth()) { - throw new IllegalArgumentException( - "x + width must be <= bitmap.width()"); + throw new IllegalArgumentException("x + width must be <= bitmap.width()"); } if (y + height > source.getHeight()) { - throw new IllegalArgumentException( - "y + height must be <= bitmap.height()"); + throw new IllegalArgumentException("y + height must be <= bitmap.height()"); } // check if we can just return our argument unchanged - if (!source.isMutable() && x == 0 && y == 0 - && width == source.getWidth() && height == source.getHeight() - && (m == null || m.isIdentity())) { + if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() && + height == source.getHeight() && (m == null || m.isIdentity())) { return source; } @@ -331,8 +436,8 @@ public final class Bitmap implements Parcelable { RectF dstR = new RectF(0, 0, width, height); if (m == null || m.isIdentity()) { - bitmap = createBitmap(neww, newh, source.hasAlpha() ? - Config.ARGB_8888 : Config.RGB_565); + bitmap = createBitmap(neww, newh, + source.hasAlpha() ? Config.ARGB_8888 : Config.RGB_565); paint = null; // not needed } else { /* the dst should have alpha if the src does, or if our matrix @@ -343,8 +448,7 @@ public final class Bitmap implements Parcelable { m.mapRect(deviceR, dstR); neww = Math.round(deviceR.width()); newh = Math.round(deviceR.height()); - bitmap = createBitmap(neww, newh, hasAlpha ? - Config.ARGB_8888 : Config.RGB_565); + bitmap = createBitmap(neww, newh, hasAlpha ? Config.ARGB_8888 : Config.RGB_565); if (hasAlpha) { bitmap.eraseColor(0); } @@ -358,7 +462,12 @@ public final class Bitmap implements Parcelable { } canvas.setBitmap(bitmap); canvas.drawBitmap(source, srcR, dstR, paint); - + + // The new bitmap was created from a known bitmap source so assume that + // they use the same density scale + bitmap.setDensityScale(source.getDensityScale()); + bitmap.setAutoScalingEnabled(source.isAutoScalingEnabled()); + return bitmap; } @@ -371,8 +480,7 @@ public final class Bitmap implements Parcelable { * @throws IllegalArgumentException if the width or height are <= 0 */ public static Bitmap createBitmap(int width, int height, Config config) { - Bitmap bm = nativeCreate(null, 0, width, width, height, - config.nativeInt, true); + Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true); bm.eraseColor(0); // start with black/transparent pixels return bm; } @@ -395,16 +503,16 @@ public final class Bitmap implements Parcelable { * the color array's length is less than the number of pixels. */ public static Bitmap createBitmap(int colors[], int offset, int stride, - int width, int height, Config config) { + int width, int height, Config config) { + checkWidthHeight(width, height); if (Math.abs(stride) < width) { throw new IllegalArgumentException("abs(stride) must be >= width"); } int lastScanline = offset + (height - 1) * stride; int length = colors.length; - if (offset < 0 || (offset + width > length) - || lastScanline < 0 - || (lastScanline + width > length)) { + if (offset < 0 || (offset + width > length) || lastScanline < 0 || + (lastScanline + width > length)) { throw new ArrayIndexOutOfBoundsException(); } return nativeCreate(colors, offset, stride, width, height, @@ -425,8 +533,7 @@ public final class Bitmap implements Parcelable { * @throws IllegalArgumentException if the width or height are <= 0, or if * the color array's length is less than the number of pixels. */ - public static Bitmap createBitmap(int colors[], int width, int height, - Config config) { + public static Bitmap createBitmap(int colors[], int width, int height, Config config) { return createBitmap(colors, 0, width, width, height, config); } @@ -474,8 +581,7 @@ public final class Bitmap implements Parcelable { * @param stream The outputstream to write the compressed data. * @return true if successfully compressed to the specified stream. */ - public boolean compress(CompressFormat format, int quality, - OutputStream stream) { + public boolean compress(CompressFormat format, int quality, OutputStream stream) { checkRecycled("Can't compress a recycled bitmap"); // do explicit check before calling the native method if (stream == null) { @@ -505,6 +611,32 @@ public final class Bitmap implements Parcelable { return mHeight == -1 ? mHeight = nativeHeight(mNativeBitmap) : mHeight; } + /** + * Convenience method that returns the width of this bitmap divided + * by the density scale factor. + * + * @return The scaled width of this bitmap, according to the density scale factor. + * + * @hide pending API council approval + */ + public int getScaledWidth() { + final float scale = getDensityScale(); + return scale == DENSITY_SCALE_UNKNOWN ? getWidth() : (int) (getWidth() / scale); + } + + /** + * Convenience method that returns the height of this bitmap divided + * by the density scale factor. + * + * @return The scaled height of this bitmap, according to the density scale factor. + * + * @hide pending API council approval + */ + public int getScaledHeight() { + final float scale = getDensityScale(); + return scale == DENSITY_SCALE_UNKNOWN ? getWidth() : (int) (getHeight() / scale); + } + /** * Return the number of bytes between rows in the bitmap's pixels. Note that * this refers to the pixels as stored natively by the bitmap. If you call @@ -836,7 +968,7 @@ public final class Bitmap implements Parcelable { private static native Bitmap nativeExtractAlpha(int nativeBitmap, int nativePaint, int[] offsetXY); - + /* package */ final int ni() { return mNativeBitmap; } diff --git a/graphics/java/android/graphics/BitmapFactory.java b/graphics/java/android/graphics/BitmapFactory.java index 2c3f543a90e9dadf0c21a6120c4e2df55a4314bd..3813d8f7ca973cf6bf9b35f0cee817c19df4d6b9 100644 --- a/graphics/java/android/graphics/BitmapFactory.java +++ b/graphics/java/android/graphics/BitmapFactory.java @@ -18,26 +18,20 @@ package android.graphics; import android.content.res.AssetManager; import android.content.res.Resources; -import android.util.Log; +import android.util.TypedValue; +import android.util.DisplayMetrics; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.io.FileDescriptor; -import java.nio.ByteBuffer; -import java.nio.IntBuffer; -import java.nio.ShortBuffer; - /** * Creates Bitmap objects from various sources, including files, streams, * and byte-arrays. */ public class BitmapFactory { - private static final String TAG = "BitmapFactory"; - private static final boolean DEBUG_LOAD = false; - public static class Options { /** * Create a default Options object, which if left unchanged will give @@ -45,6 +39,8 @@ public class BitmapFactory { */ public Options() { inDither = true; + inDensity = 0; + inScaled = true; } /** @@ -53,6 +49,7 @@ public class BitmapFactory { * the bitmap without having to allocate the memory for its pixels. */ public boolean inJustDecodeBounds; + /** * If set to a value > 1, requests the decoder to subsample the original * image, returning a smaller image to save memory. The sample size is @@ -80,20 +77,45 @@ public class BitmapFactory { * image. */ public boolean inDither; - + + /** + * The desired pixel density of the bitmap. + * + * @see android.util.DisplayMetrics#DEFAULT_DENSITY + * @see android.util.DisplayMetrics#density + * + * @hide pending API council approval + */ + public int inDensity; + + /** + *

                  If the bitmap is loaded from {@link android.content.res.Resources} and + * this flag is turned on, the bitmap will be scaled to match the default + * display's pixel density.

                  + * + *

                  This flag is turned on by default and should be turned off if you need + * a non-scaled version of the bitmap. In this case, + * {@link android.graphics.Bitmap#setAutoScalingEnabled(boolean)} can be used + * to properly scale the bitmap at drawing time.

                  + * + * @hide pending API council approval + */ + public boolean inScaled; + /** * The resulting width of the bitmap, set independent of the state of * inJustDecodeBounds. However, if there is an error trying to decode, * outWidth will be set to -1. */ public int outWidth; + /** * The resulting height of the bitmap, set independent of the state of * inJustDecodeBounds. However, if there is an error trying to decode, * outHeight will be set to -1. */ public int outHeight; - + /** * If known, this string is set to the mimetype of the decoded image. * If not know, or there is an error, it is set to null. @@ -103,7 +125,7 @@ public class BitmapFactory { /** * Temp storage to use for decoding. Suggest 16K or so. */ - public byte [] inTempStorage; + public byte[] inTempStorage; private native void requestCancel(); @@ -174,6 +196,58 @@ public class BitmapFactory { return decodeFile(pathName, null); } + /** + * Decode a new Bitmap from an InputStream. This InputStream was obtained from + * resources, which we pass to be able to scale the bitmap accordingly. + * + * @hide + */ + public static Bitmap decodeStream(Resources res, TypedValue value, InputStream is, + Rect pad, Options opts) { + + if (opts == null) { + opts = new Options(); + } + + Bitmap bm = decodeStream(is, pad, opts); + + if (bm != null && res != null && value != null) { + byte[] np = bm.getNinePatchChunk(); + final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np); + + final int density = value.density; + if (opts.inDensity == 0) { + opts.inDensity = density == TypedValue.DENSITY_DEFAULT ? + DisplayMetrics.DEFAULT_DENSITY : density; + } + float scale = opts.inDensity / (float) DisplayMetrics.DEFAULT_DENSITY; + + if (opts.inScaled || isNinePatch) { + bm.setDensityScale(1.0f); + bm.setAutoScalingEnabled(false); + // Assume we are going to prescale for the screen + scale = res.getDisplayMetrics().density / scale; + if (scale != 1.0f) { + // TODO: This is very inefficient and should be done in native by Skia + final Bitmap oldBitmap = bm; + bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f), + (int) (bm.getHeight() * scale + 0.5f), true); + oldBitmap.recycle(); + + if (isNinePatch) { + np = nativeScaleNinePatch(np, scale, pad); + bm.setNinePatchChunk(np); + } + } + } else { + bm.setDensityScale(scale); + bm.setAutoScalingEnabled(true); + } + } + + return bm; + } + /** * Decode an image referenced by a resource ID. * @@ -189,11 +263,12 @@ public class BitmapFactory { Bitmap bm = null; try { - InputStream is = res.openRawResource(id); - bm = decodeStream(is, null, opts); + final TypedValue value = new TypedValue(); + final InputStream is = res.openRawResource(id, value); + + bm = decodeStream(res, value, is, null, opts); is.close(); - } - catch (java.io.IOException e) { + } catch (java.io.IOException e) { /* do nothing. If the exception happened on open, bm will be null. If it happened on close, bm is still valid. @@ -226,8 +301,7 @@ public class BitmapFactory { * decoded, or, if opts is non-null, if opts requested only the * size be returned (in opts.outWidth and opts.outHeight) */ - public static Bitmap decodeByteArray(byte[] data, int offset, int length, - Options opts) { + public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) { if ((offset | length) < 0 || data.length < offset + length) { throw new ArrayIndexOutOfBoundsException(); } @@ -265,8 +339,7 @@ public class BitmapFactory { * decoded, or, if opts is non-null, if opts requested only the * size be returned (in opts.outWidth and opts.outHeight) */ - public static Bitmap decodeStream(InputStream is, Rect outPadding, - Options opts) { + public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) { // we don't throw in this case, thus allowing the caller to only check // the cache, and not force the image to be decoded. if (is == null) { @@ -287,11 +360,9 @@ public class BitmapFactory { Bitmap bm; if (is instanceof AssetManager.AssetInputStream) { - bm = nativeDecodeAsset( - ((AssetManager.AssetInputStream)is).getAssetInt(), outPadding, - opts); - } - else { + bm = nativeDecodeAsset(((AssetManager.AssetInputStream) is).getAssetInt(), + outPadding, opts); + } else { // pass some temp storage down to the native code. 1024 is made up, // but should be large enough to avoid too many small calls back // into is.read(...) This number is not related to the value passed @@ -337,8 +408,7 @@ public class BitmapFactory { * image should be completely decoded, or just is size returned. * @return the decoded bitmap, or null */ - public static Bitmap decodeFileDescriptor(FileDescriptor fd, - Rect outPadding, Options opts) { + public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) { return nativeDecodeFileDescriptor(fd, outPadding, opts); } @@ -354,13 +424,13 @@ public class BitmapFactory { return nativeDecodeFileDescriptor(fd, null, null); } - private static native Bitmap nativeDecodeStream(InputStream is, - byte[] storage, Rect padding, Options opts); + private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage, + Rect padding, Options opts); private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd, - Rect padding, Options opts); - private static native Bitmap nativeDecodeAsset(int asset, Rect padding, - Options opts); + Rect padding, Options opts); + private static native Bitmap nativeDecodeAsset(int asset, Rect padding, Options opts); private static native Bitmap nativeDecodeByteArray(byte[] data, int offset, - int length, Options opts); + int length, Options opts); + private static native byte[] nativeScaleNinePatch(byte[] chunk, float scale, Rect pad); } diff --git a/graphics/java/android/graphics/Canvas.java b/graphics/java/android/graphics/Canvas.java index b57f42854a0d9612e8b1ad0a243ecb5a9a1d8541..32ecd9fa49aabb8dbcc90ce7a5d405be6becfa48 100644 --- a/graphics/java/android/graphics/Canvas.java +++ b/graphics/java/android/graphics/Canvas.java @@ -50,6 +50,8 @@ public class Canvas { // Used by native code @SuppressWarnings({"UnusedDeclaration"}) private int mSurfaceFormat; + @SuppressWarnings({"UnusedDeclaration"}) + private float mDensityScale = 1.0f; /** * Construct an empty raster canvas. Use setBitmap() to specify a bitmap to @@ -74,6 +76,8 @@ public class Canvas { throwIfRecycled(bitmap); mNativeCanvas = initRaster(bitmap.ni()); mBitmap = bitmap; + mDensityScale = bitmap.getDensityScale(); + if (mDensityScale == Bitmap.DENSITY_SCALE_UNKNOWN) mDensityScale = 1.0f; } /*package*/ Canvas(int nativeCanvas) { @@ -126,6 +130,8 @@ public class Canvas { native_setBitmap(mNativeCanvas, bitmap.ni()); mBitmap = bitmap; + mDensityScale = bitmap.getDensityScale(); + if (mDensityScale == Bitmap.DENSITY_SCALE_UNKNOWN) mDensityScale = 1.0f; } /** @@ -163,6 +169,51 @@ public class Canvas { */ public native int getHeight(); + /** + *

                  Returns the density scale for this Canvas' backing bitmap, expressed as a + * factor of the default density (160dpi.) For instance, a bitmap designed for + * 240dpi displays will have a density scale of 1.5 whereas a bitmap + * designed for 160dpi will have a density scale of 1.0.

                  + * + *

                  The default density scale is {@link Bitmap#DENSITY_SCALE_UNKNOWN}.

                  + * + * @return A scaling factor of the default density (160dpi) or + * {@link Bitmap#DENSITY_SCALE_UNKNOWN} if the scaling factor is unknown. + * + * @see #setDensityScale(float) + * @see Bitmap#getDensityScale() + * + * @hide pending API council approval + */ + public float getDensityScale() { + if (mBitmap != null) { + return mBitmap.getDensityScale(); + } + return mDensityScale; + } + + /** + *

                  Specifies the density scale for this Canvas' backing bitmap, expressed as a + * factor of the default density (160dpi.) For instance, a bitmap designed for + * 240dpi displays will have a density scale of 1.5 whereas a bitmap + * designed for 160dpi will have a density scale of 1.0.

                  + * + * @param densityScale The density scaling factor to use with this bitmap or + * {@link Bitmap#DENSITY_SCALE_UNKNOWN} if the factor is unknown. + * + * @see #getDensityScale() + * @see Bitmap#setDensityScale(float) + * + * @hide pending API council approval + */ + public void setDensityScale(float densityScale) { + if (mBitmap != null) { + mBitmap.setDensityScale(densityScale); + } + mDensityScale = densityScale; + if (mDensityScale == Bitmap.DENSITY_SCALE_UNKNOWN) mDensityScale = 1.0f; + } + // the SAVE_FLAG constants must match their native equivalents /** restore the current matrix when restore() is called */ @@ -910,7 +961,8 @@ public class Canvas { public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) { throwIfRecycled(bitmap); native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top, - paint != null ? paint.mNativePaint : 0); + paint != null ? paint.mNativePaint : 0, bitmap.isAutoScalingEnabled(), + bitmap.getDensityScale()); } /** @@ -982,8 +1034,8 @@ public class Canvas { * be 0xFF for every pixel). * @param paint May be null. The paint used to draw the bitmap */ - public void drawBitmap(int[] colors, int offset, int stride, int x, int y, - int width, int height, boolean hasAlpha, + public void drawBitmap(int[] colors, int offset, int stride, float x, + float y, int width, int height, boolean hasAlpha, Paint paint) { // check for valid input if (width < 0) { @@ -1006,11 +1058,20 @@ public class Canvas { return; } // punch down to native for the actual draw - native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, - width, height, hasAlpha, - paint != null ? paint.mNativePaint : 0); + native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha, + paint != null ? paint.mNativePaint : 0); } + /** Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y + */ + public void drawBitmap(int[] colors, int offset, int stride, int x, int y, + int width, int height, boolean hasAlpha, + Paint paint) { + // call through to the common float version + drawBitmap(colors, offset, stride, (float)x, (float)y, width, height, + hasAlpha, paint); + } + /** * Draw the bitmap using the specified matrix. * @@ -1020,7 +1081,7 @@ public class Canvas { */ public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) { nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(), - paint != null ? paint.mNativePaint : 0); + paint != null ? paint.mNativePaint : 0); } private static void checkRange(int length, int offset, int count) { @@ -1416,25 +1477,27 @@ public class Canvas { float ry, int paint); private static native void native_drawPath(int nativeCanvas, int path, int paint); - private static native void native_drawBitmap(int nativeCanvas, int bitmap, + private native void native_drawBitmap(int nativeCanvas, int bitmap, float left, float top, - int nativePaintOrZero); - private static native void native_drawBitmap(int nativeCanvas, int bitmap, + int nativePaintOrZero, boolean autoScale, + float densityScale); + private native void native_drawBitmap(int nativeCanvas, int bitmap, Rect src, RectF dst, int nativePaintOrZero); private static native void native_drawBitmap(int nativeCanvas, int bitmap, Rect src, Rect dst, int nativePaintOrZero); private static native void native_drawBitmap(int nativeCanvas, int[] colors, - int offset, int stride, int x, - int y, int width, int height, + int offset, int stride, float x, + float y, int width, int height, boolean hasAlpha, int nativePaintOrZero); private static native void nativeDrawBitmapMatrix(int nCanvas, int nBitmap, int nMatrix, int nPaint); private static native void nativeDrawBitmapMesh(int nCanvas, int nBitmap, - int meshWidth, int meshHeight, float[] verts, int vertOffset, - int[] colors, int colorOffset, int nPaint); + int meshWidth, int meshHeight, + float[] verts, int vertOffset, + int[] colors, int colorOffset, int nPaint); private static native void nativeDrawVertices(int nCanvas, int mode, int n, float[] verts, int vertOffset, float[] texs, int texOffset, int[] colors, int colorOffset, short[] indices, diff --git a/graphics/java/android/graphics/NinePatch.java b/graphics/java/android/graphics/NinePatch.java index cabd84805f54998d74f28f91aa653ce44f7b2950..2b24ef227e3324aa3b80fcd04d612b61c4efbedd 100644 --- a/graphics/java/android/graphics/NinePatch.java +++ b/graphics/java/android/graphics/NinePatch.java @@ -26,10 +26,10 @@ package android.graphics; * way that you define, when content added within the image exceeds the normal * bounds of the graphic. For a thorough explanation of a NinePatch image, * read the discussion in the - * Available - * Resource Types document. + * 2D + * Graphics document. *

                  - * The Draw 9-patch + * The Draw 9-Patch * tool offers an extremely handy way to create your NinePatch images, * using a WYSIWYG graphics editor. *

                  @@ -50,6 +50,17 @@ public class NinePatch { validateNinePatchChunk(mBitmap.ni(), chunk); } + /** + * @hide + */ + public NinePatch(NinePatch patch) { + mBitmap = patch.mBitmap; + mChunk = patch.mChunk; + mSrcName = patch.mSrcName; + mPaint = new Paint(patch.mPaint); + validateNinePatchChunk(mBitmap.ni(), mChunk); + } + public void setPaint(Paint p) { mPaint = p; } diff --git a/graphics/java/android/graphics/Paint.java b/graphics/java/android/graphics/Paint.java index 6fac9695421584bef355b090afad53127f6f5da7..81980d9580ea9802b7ecd1314922e7901d753e99 100644 --- a/graphics/java/android/graphics/Paint.java +++ b/graphics/java/android/graphics/Paint.java @@ -109,13 +109,13 @@ public class Paint { */ BUTT (0), /** - * The stroke projects out as a square, with the center at the end - * of the path. + * The stroke projects out as a semicircle, with the center at the + * end of the path. */ ROUND (1), /** - * The stroke projects out as a semicircle, with the center at the - * end of the path. + * The stroke projects out as a square, with the center at the end + * of the path. */ SQUARE (2); diff --git a/graphics/java/android/graphics/drawable/AnimationDrawable.java b/graphics/java/android/graphics/drawable/AnimationDrawable.java index c6b772e96e470fcf30e48fdfb8e1b72a43404b9d..bab1703fbf242bc14e1c1f864e9c4510ef1165f6 100644 --- a/graphics/java/android/graphics/drawable/AnimationDrawable.java +++ b/graphics/java/android/graphics/drawable/AnimationDrawable.java @@ -74,6 +74,7 @@ import android.util.AttributeSet; public class AnimationDrawable extends DrawableContainer implements Runnable { private final AnimationState mAnimationState; private int mCurFrame = -1; + private boolean mMutated; public AnimationDrawable() { this(null); @@ -283,6 +284,15 @@ public class AnimationDrawable extends DrawableContainer implements Runnable { setFrame(0, true, false); } + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mAnimationState.mDurations = mAnimationState.mDurations.clone(); + mMutated = true; + } + return this; + } + private final static class AnimationState extends DrawableContainerState { private int[] mDurations; private boolean mOneShot; diff --git a/graphics/java/android/graphics/drawable/BitmapDrawable.java b/graphics/java/android/graphics/drawable/BitmapDrawable.java index 7f3df9afc15798a0cf43cdc570dc147fe9a82a29..5b32246c9bb938ab6dd79fa972257972f94871c8 100644 --- a/graphics/java/android/graphics/drawable/BitmapDrawable.java +++ b/graphics/java/android/graphics/drawable/BitmapDrawable.java @@ -28,6 +28,7 @@ import android.graphics.Rect; import android.graphics.Shader; import android.graphics.BitmapShader; import android.util.AttributeSet; +import android.util.DisplayMetrics; import android.view.Gravity; import org.xmlpull.v1.XmlPullParser; @@ -62,9 +63,12 @@ public class BitmapDrawable extends Drawable { private boolean mApplyGravity; private boolean mRebuildShader; + private int mBitmapWidth; + private int mBitmapHeight; + private boolean mMutated; public BitmapDrawable() { - mBitmapState = new BitmapState(null); + mBitmapState = new BitmapState((Bitmap) null); } public BitmapDrawable(Bitmap bitmap) { @@ -92,7 +96,62 @@ public class BitmapDrawable extends Drawable { public final Bitmap getBitmap() { return mBitmap; } - + + private void setBitmap(Bitmap bitmap) { + mBitmap = bitmap; + if (bitmap != null) { + mBitmapWidth = bitmap.getWidth(); + mBitmapHeight = bitmap.getHeight(); + } else { + mBitmapWidth = mBitmapHeight = -1; + } + } + + /** + * Set the density scale at which this drawable will be rendered. This + * method assumes the drawable will be rendered at the same density as the + * specified canvas. + * + * @param canvas The Canvas from which the density scale must be obtained. + * + * @see android.graphics.Bitmap#setDensityScale(float) + * @see android.graphics.Bitmap#getDensityScale() + * + * @hide pending API council approval + */ + public void setDensityScale(Canvas canvas) { + setDensityScale(canvas.getDensityScale()); + } + + /** + * Set the density scale at which this drawable will be rendered. + * + * @param metrics The DisplayMetrics indicating the density scale for this drawable. + * + * @see android.graphics.Bitmap#setDensityScale(float) + * @see android.graphics.Bitmap#getDensityScale() + * + * @hide pending API council approval + */ + public void setDensityScale(DisplayMetrics metrics) { + setDensityScale(metrics.density); + } + + /** + * Set the density scale at which this drawable will be rendered. + * + * @param density The density scale for this drawable. + * + * @see android.graphics.Bitmap#setDensityScale(float) + * @see android.graphics.Bitmap#getDensityScale() + * + * @hide pending API council approval + */ + public void setDensityScale(float density) { + density = (density == Bitmap.DENSITY_SCALE_UNKNOWN ? 1.0f : density); + mBitmapState.mTargetDensityScale = density; + } + /** Get the gravity used to position/stretch the bitmap within its bounds. See android.view.Gravity * @return the gravity applied to the bitmap @@ -184,7 +243,7 @@ public class BitmapDrawable extends Drawable { Shader shader = state.mPaint.getShader(); if (shader == null) { if (mApplyGravity) { - Gravity.apply(state.mGravity, bitmap.getWidth(), bitmap.getHeight(), + Gravity.apply(state.mGravity, mBitmapWidth, mBitmapHeight, getBounds(), mDstRect); mApplyGravity = false; } @@ -209,6 +268,21 @@ public class BitmapDrawable extends Drawable { mBitmapState.mPaint.setColorFilter(cf); } + /** + * A mutable BitmapDrawable still shares its Bitmap with any other Drawable + * that comes from the same resource. + * + * @return This drawable. + */ + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mBitmapState = new BitmapState(mBitmapState); + mMutated = true; + } + return this; + } + @Override public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) throws XmlPullParserException, IOException { @@ -226,7 +300,9 @@ public class BitmapDrawable extends Drawable { throw new XmlPullParserException(parser.getPositionDescription() + ": requires a valid src attribute"); } - mBitmapState.mBitmap = mBitmap = bitmap; + mBitmapState.mBitmap = bitmap; + setBitmap(bitmap); + setDensityScale(r.getDisplayMetrics()); final Paint paint = mBitmapState.mPaint; paint.setAntiAlias(a.getBoolean(com.android.internal.R.styleable.BitmapDrawable_antialias, @@ -256,14 +332,29 @@ public class BitmapDrawable extends Drawable { @Override public int getIntrinsicWidth() { - Bitmap bitmap = mBitmap; - return bitmap != null ? bitmap.getWidth() : -1; + final Bitmap bitmap = mBitmap; + final BitmapState state = mBitmapState; + + if (!state.mAutoScale || state.mBitmapScale == Bitmap.DENSITY_SCALE_UNKNOWN) { + return mBitmapWidth; + } else { + return bitmap != null ? (int) (mBitmapWidth / + (state.mBitmapScale / state.mTargetDensityScale) + 0.5f) : -1; + + } } @Override public int getIntrinsicHeight() { - Bitmap bitmap = mBitmap; - return bitmap != null ? bitmap.getHeight() : -1; + final Bitmap bitmap = mBitmap; + final BitmapState state = mBitmapState; + + if (!state.mAutoScale || state.mBitmapScale == Bitmap.DENSITY_SCALE_UNKNOWN) { + return mBitmapHeight; + } else { + return bitmap != null ? (int) (mBitmapHeight / + (state.mBitmapScale / state.mTargetDensityScale) + 0.5f) : -1; + } } @Override @@ -289,9 +380,29 @@ public class BitmapDrawable extends Drawable { Paint mPaint = new Paint(DEFAULT_PAINT_FLAGS); Shader.TileMode mTileModeX; Shader.TileMode mTileModeY; + boolean mAutoScale; + float mBitmapScale; + float mTargetDensityScale = 1.0f; BitmapState(Bitmap bitmap) { mBitmap = bitmap; + if (bitmap != null) { + mBitmapScale = bitmap.getDensityScale(); + mAutoScale = bitmap.isAutoScalingEnabled(); + } else { + mBitmapScale = 1.0f; + mAutoScale = false; + } + } + + BitmapState(BitmapState bitmapState) { + this(bitmapState.mBitmap); + mChangingConfigurations = bitmapState.mChangingConfigurations; + mGravity = bitmapState.mGravity; + mTileModeX = bitmapState.mTileModeX; + mTileModeY = bitmapState.mTileModeY; + mTargetDensityScale = bitmapState.mTargetDensityScale; + mPaint = new Paint(bitmapState.mPaint); } @Override @@ -307,6 +418,6 @@ public class BitmapDrawable extends Drawable { private BitmapDrawable(BitmapState state) { mBitmapState = state; - mBitmap = state.mBitmap; + setBitmap(state.mBitmap); } } diff --git a/graphics/java/android/graphics/drawable/ClipDrawable.java b/graphics/java/android/graphics/drawable/ClipDrawable.java index 60293885e76114e82cdd8d4372ba2f08348aae87..95d4dd096b9cf32e5243d38ac07e9753d3ece4bf 100644 --- a/graphics/java/android/graphics/drawable/ClipDrawable.java +++ b/graphics/java/android/graphics/drawable/ClipDrawable.java @@ -24,7 +24,6 @@ import android.content.res.TypedArray; import android.graphics.*; import android.view.Gravity; import android.util.AttributeSet; -import android.util.Log; import java.io.IOException; @@ -100,9 +99,8 @@ public class ClipDrawable extends Drawable implements Drawable.Callback { mClipState.mDrawable = dr; mClipState.mOrientation = orientation; mClipState.mGravity = g; - if (dr != null) { - dr.setCallback(this); - } + + dr.setCallback(this); } // overrides from Drawable.Callback @@ -168,8 +166,7 @@ public class ClipDrawable extends Drawable implements Drawable.Callback { @Override protected boolean onStateChange(int[] state) { - boolean changed = mClipState.mDrawable.setState(state); - return changed; + return mClipState.mDrawable.setState(state); } @Override @@ -233,7 +230,17 @@ public class ClipDrawable extends Drawable implements Drawable.Callback { return null; } + + final static class ClipState extends ConstantState { + Drawable mDrawable; + int mChangingConfigurations; + int mOrientation; + int mGravity; + + private boolean mCheckedConstantState; + private boolean mCanConstantState; + ClipState(ClipState orig, ClipDrawable owner) { if (orig != null) { mDrawable = orig.mDrawable.getConstantState().newDrawable(); @@ -262,14 +269,6 @@ public class ClipDrawable extends Drawable implements Drawable.Callback { return mCanConstantState; } - - Drawable mDrawable; - int mChangingConfigurations; - int mOrientation; - int mGravity; - - private boolean mCheckedConstantState; - private boolean mCanConstantState; } private ClipDrawable(ClipState state) { diff --git a/graphics/java/android/graphics/drawable/Drawable.java b/graphics/java/android/graphics/drawable/Drawable.java index 00212415aa93bd0440480be455137d0e691ff86b..42e28e8a1aa31c4c8f7c7c040a8e9af553681953 100644 --- a/graphics/java/android/graphics/drawable/Drawable.java +++ b/graphics/java/android/graphics/drawable/Drawable.java @@ -29,6 +29,7 @@ import android.graphics.*; import android.util.AttributeSet; import android.util.StateSet; import android.util.Xml; +import android.util.TypedValue; /** * A Drawable is a general abstraction for "something that can be drawn." Most @@ -91,7 +92,7 @@ import android.util.Xml; * whose overall size is modified based on the current level. *
                *

                For information and examples of creating drawable resources (XML or bitmap files that - * can be loaded in code), see Resources + * can be loaded in code), see Resources * and Internationalization. */ public abstract class Drawable { @@ -102,7 +103,7 @@ public abstract class Drawable { private Rect mBounds = new Rect(); /*package*/ Callback mCallback = null; private boolean mVisible = true; - + /** * Draw in its bounds (set via setBounds) respecting optional effects such * as alpha (set via setAlpha) and color filter (set via setColorFilter). @@ -617,10 +618,37 @@ public abstract class Drawable { return false; } + /** + * Make this drawable mutable. This operation cannot be reversed. A mutable + * drawable is guaranteed to not share its state with any other drawable. + * This is especially useful when you need to modify properties of drawables + * loaded from resources. By default, all drawables instances loaded from + * the same resource share a common state; if you modify the state of one + * instance, all the other instances will receive the same modification. + * + * Calling this method on a mutable Drawable will have no effect. + * + * @return This drawable. + */ + public Drawable mutate() { + return this; + } + /** * Create a drawable from an inputstream */ public static Drawable createFromStream(InputStream is, String srcName) { + return createFromResourceStream(null, null, is, srcName); + } + + /** + * Create a drawable from an inputstream + * + * @hide pending API council approval + */ + public static Drawable createFromResourceStream(Resources res, TypedValue value, + InputStream is, String srcName) { + if (is == null) { return null; } @@ -632,14 +660,14 @@ public abstract class Drawable { Rects only to drop them on the floor. */ Rect pad = new Rect(); - Bitmap bm = BitmapFactory.decodeStream(is, pad, null); + Bitmap bm = BitmapFactory.decodeStream(res, value, is, pad, null); if (bm != null) { byte[] np = bm.getNinePatchChunk(); if (np == null || !NinePatch.isNinePatchChunk(np)) { np = null; pad = null; } - return drawableFromBitmap(bm, np, pad, srcName); + return drawableFromBitmap(res, bm, np, pad, srcName); } return null; } @@ -647,7 +675,7 @@ public abstract class Drawable { /** * Create a drawable from an XML document. For more information on how to * create resources in XML, see - * Resources and + * Resources and * Internationalization. */ public static Drawable createFromXml(Resources r, XmlPullParser parser) @@ -708,6 +736,11 @@ public abstract class Drawable { drawable = new InsetDrawable(); } else if (name.equals("bitmap")) { drawable = new BitmapDrawable(); + if (r != null) { + ((BitmapDrawable) drawable).setDensityScale(r.getDisplayMetrics()); + } + } else if (name.equals("nine-patch")) { + drawable = new NinePatchDrawable(); } else { throw new XmlPullParserException(parser.getPositionDescription() + ": invalid drawable tag " + name); @@ -728,7 +761,7 @@ public abstract class Drawable { Bitmap bm = BitmapFactory.decodeFile(pathName); if (bm != null) { - return drawableFromBitmap(bm, null, null, pathName); + return drawableFromBitmap(null, bm, null, null, pathName); } return null; @@ -758,11 +791,19 @@ public abstract class Drawable { return null; } - private static Drawable drawableFromBitmap(Bitmap bm, byte[] np, Rect pad, String srcName) { + private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np, + Rect pad, String srcName) { + if (np != null) { return new NinePatchDrawable(bm, np, pad, srcName); } - return new BitmapDrawable(bm); + + final BitmapDrawable drawable = new BitmapDrawable(bm); + if (res != null) { + drawable.setDensityScale(res.getDisplayMetrics()); + } + + return drawable; } } diff --git a/graphics/java/android/graphics/drawable/DrawableContainer.java b/graphics/java/android/graphics/drawable/DrawableContainer.java index e6c48be9921ad3be0614eb607c504c2f1a0a8b5a..29f2a0018f17d4dae44a68b50f5955e6c88f0fda 100644 --- a/graphics/java/android/graphics/drawable/DrawableContainer.java +++ b/graphics/java/android/graphics/drawable/DrawableContainer.java @@ -21,12 +21,13 @@ import android.graphics.*; public class DrawableContainer extends Drawable implements Drawable.Callback { private DrawableContainerState mDrawableContainerState; - private Drawable mCurrDrawable; - private int mAlpha = 0xFF; - private ColorFilter mColorFilter; - private boolean mDither; + private Drawable mCurrDrawable; + private int mAlpha = 0xFF; + private ColorFilter mColorFilter; + private boolean mDither; - private int mCurIndex = -1; + private int mCurIndex = -1; + private boolean mMutated; // overrides from Drawable @@ -229,6 +230,17 @@ public class DrawableContainer extends Drawable implements Drawable.Callback { return null; } + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + for (Drawable child : mDrawableContainerState.mDrawables) { + child.mutate(); + } + mMutated = true; + } + return this; + } + public abstract static class DrawableContainerState extends ConstantState { final DrawableContainer mOwner; @@ -277,7 +289,9 @@ public class DrawableContainer extends Drawable implements Drawable.Callback { mCheckedConstantState = mCanConstantState = true; mVariablePadding = orig.mVariablePadding; - mConstantPadding = orig.mConstantPadding; + if (orig.mConstantPadding != null) { + mConstantPadding = new Rect(orig.mConstantPadding); + } mConstantSize = orig.mConstantSize; mComputedConstantSize = orig.mComputedConstantSize; mConstantWidth = orig.mConstantWidth; diff --git a/graphics/java/android/graphics/drawable/GradientDrawable.java b/graphics/java/android/graphics/drawable/GradientDrawable.java index cdfca1be8559c6e77222eae3bd833cbd2f7786d8..3db45f0daa082694bc0720f3e0a27d18725c254a 100644 --- a/graphics/java/android/graphics/drawable/GradientDrawable.java +++ b/graphics/java/android/graphics/drawable/GradientDrawable.java @@ -47,7 +47,9 @@ import java.io.IOException; * @attr ref android.R.styleable#GradientDrawable_visible * @attr ref android.R.styleable#GradientDrawable_shape * @attr ref android.R.styleable#GradientDrawable_innerRadiusRatio + * @attr ref android.R.styleable#GradientDrawable_innerRadius * @attr ref android.R.styleable#GradientDrawable_thicknessRatio + * @attr ref android.R.styleable#GradientDrawable_thickness * @attr ref android.R.styleable#GradientDrawable_useLevel * @attr ref android.R.styleable#GradientDrawableSize_width * @attr ref android.R.styleable#GradientDrawableSize_height @@ -106,20 +108,23 @@ public class GradientDrawable extends Drawable { */ public static final int SWEEP_GRADIENT = 2; - private final GradientState mGradientState; + private GradientState mGradientState; private final Paint mFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG); - private Rect mPadding; - private Paint mStrokePaint; // optional, set by the caller + private Rect mPadding; + private Paint mStrokePaint; // optional, set by the caller private ColorFilter mColorFilter; // optional, set by the caller - private int mAlpha = 0xFF; // modified by the caller - private boolean mDither; + private int mAlpha = 0xFF; // modified by the caller + private boolean mDither; - private final Path mPath = new Path(); + private final Path mPath = new Path(); private final RectF mRect = new RectF(); - private Paint mLayerPaint; // internal, used if we use saveLayer() - private boolean mRectIsDirty; // internal state + private Paint mLayerPaint; // internal, used if we use saveLayer() + private boolean mRectIsDirty; // internal state + private boolean mMutated; + private Path mRingPath; + private boolean mPathIsDirty; /** * Controls how the gradient is oriented relative to the drawable's bounds @@ -212,6 +217,7 @@ public class GradientDrawable extends Drawable { } public void setShape(int shape) { + mRingPath = null; mGradientState.setShape(shape); } @@ -247,14 +253,12 @@ public class GradientDrawable extends Drawable { // remember the alpha values, in case we temporarily overwrite them // when we modulate them with mAlpha final int prevFillAlpha = mFillPaint.getAlpha(); - final int prevStrokeAlpha = mStrokePaint != null ? - mStrokePaint.getAlpha() : 0; + final int prevStrokeAlpha = mStrokePaint != null ? mStrokePaint.getAlpha() : 0; // compute the modulate alpha values final int currFillAlpha = modulateAlpha(prevFillAlpha); final int currStrokeAlpha = modulateAlpha(prevStrokeAlpha); - final boolean haveStroke = currStrokeAlpha > 0 && - mStrokePaint.getStrokeWidth() > 0; + final boolean haveStroke = currStrokeAlpha > 0 && mStrokePaint.getStrokeWidth() > 0; final boolean haveFill = currFillAlpha > 0; final GradientState st = mGradientState; /* we need a layer iff we're drawing both a fill and stroke, and the @@ -263,7 +267,7 @@ public class GradientDrawable extends Drawable { of the fill (if any) without worrying about blending artifacts. */ final boolean useLayer = haveStroke && haveFill && st.mShape != LINE && - currStrokeAlpha < 255; + currStrokeAlpha < 255; /* Drawing with a layer is slower than direct drawing, but it allows us to apply paint effects like alpha and colorfilter to @@ -335,10 +339,10 @@ public class GradientDrawable extends Drawable { break; } case RING: - Path ring = buildRing(st); - canvas.drawPath(ring, mFillPaint); + Path path = buildRing(st); + canvas.drawPath(path, mFillPaint); if (haveStroke) { - canvas.drawPath(ring, mStrokePaint); + canvas.drawPath(path, mStrokePaint); } break; } @@ -354,6 +358,9 @@ public class GradientDrawable extends Drawable { } private Path buildRing(GradientState st) { + if (mRingPath != null && (!st.mUseLevelForShape || !mPathIsDirty)) return mRingPath; + mPathIsDirty = false; + float sweep = st.mUseLevelForShape ? (360.0f * getLevel() / 10000.0f) : 360f; RectF bounds = new RectF(mRect); @@ -361,9 +368,11 @@ public class GradientDrawable extends Drawable { float x = bounds.width() / 2.0f; float y = bounds.height() / 2.0f; - float thickness = bounds.width() / st.mThickness; + float thickness = st.mThickness != -1 ? + st.mThickness : bounds.width() / st.mThicknessRatio; // inner radius - float radius = bounds.width() / st.mInnerRadius; + float radius = st.mInnerRadius != -1 ? + st.mInnerRadius : bounds.width() / st.mInnerRadiusRatio; RectF innerBounds = new RectF(bounds); innerBounds.inset(x - radius, y - radius); @@ -371,27 +380,33 @@ public class GradientDrawable extends Drawable { bounds = new RectF(innerBounds); bounds.inset(-thickness, -thickness); - Path path = new Path(); + if (mRingPath == null) { + mRingPath = new Path(); + } else { + mRingPath.reset(); + } + + final Path ringPath = mRingPath; // arcTo treats the sweep angle mod 360, so check for that, since we // think 360 means draw the entire oval if (sweep < 360 && sweep > -360) { - path.setFillType(Path.FillType.EVEN_ODD); + ringPath.setFillType(Path.FillType.EVEN_ODD); // inner top - path.moveTo(x + radius, y); + ringPath.moveTo(x + radius, y); // outer top - path.lineTo(x + radius + thickness, y); + ringPath.lineTo(x + radius + thickness, y); // outer arc - path.arcTo(bounds, 0.0f, sweep, false); + ringPath.arcTo(bounds, 0.0f, sweep, false); // inner arc - path.arcTo(innerBounds, sweep, -sweep, false); - path.close(); + ringPath.arcTo(innerBounds, sweep, -sweep, false); + ringPath.close(); } else { // add the entire ovals - path.addOval(bounds, Path.Direction.CW); - path.addOval(innerBounds, Path.Direction.CCW); + ringPath.addOval(bounds, Path.Direction.CW); + ringPath.addOval(innerBounds, Path.Direction.CCW); } - return path; + return ringPath; } public void setColor(int argb) { @@ -429,6 +444,8 @@ public class GradientDrawable extends Drawable { @Override protected void onBoundsChange(Rect r) { super.onBoundsChange(r); + mRingPath = null; + mPathIsDirty = true; mRectIsDirty = true; } @@ -436,6 +453,7 @@ public class GradientDrawable extends Drawable { protected boolean onLevelChange(int level) { super.onLevelChange(level); mRectIsDirty = true; + mPathIsDirty = true; invalidateSelf(); return true; } @@ -461,8 +479,9 @@ public class GradientDrawable extends Drawable { mRect.set(bounds.left + inset, bounds.top + inset, bounds.right - inset, bounds.bottom - inset); - - if (st.mColors != null) { + + final int[] colors = st.mColors; + if (colors != null) { RectF r = mRect; float x0, x1, y0, y1; @@ -504,8 +523,7 @@ public class GradientDrawable extends Drawable { } mFillPaint.setShader(new LinearGradient(x0, y0, x1, y1, - st.mColors, st.mPositions, - Shader.TileMode.CLAMP)); + colors, st.mPositions, Shader.TileMode.CLAMP)); } else if (st.mGradient == RADIAL_GRADIENT) { x0 = r.left + (r.right - r.left) * st.mCenterX; y0 = r.top + (r.bottom - r.top) * st.mCenterY; @@ -513,30 +531,38 @@ public class GradientDrawable extends Drawable { final float level = st.mUseLevel ? (float) getLevel() / 10000.0f : 1.0f; mFillPaint.setShader(new RadialGradient(x0, y0, - level * st.mGradientRadius, st.mColors, null, + level * st.mGradientRadius, colors, null, Shader.TileMode.CLAMP)); } else if (st.mGradient == SWEEP_GRADIENT) { x0 = r.left + (r.right - r.left) * st.mCenterX; y0 = r.top + (r.bottom - r.top) * st.mCenterY; - float[] positions = null; - int[] colors = st.mColors; + int[] tempColors = colors; + float[] tempPositions = null; if (st.mUseLevel) { - final int length = st.mColors.length; - colors = new int[length + 1]; - System.arraycopy(st.mColors, 0, colors, 0, length); - colors[length] = st.mColors[length - 1]; + tempColors = st.mTempColors; + final int length = colors.length; + if (tempColors == null || tempColors.length != length + 1) { + tempColors = st.mTempColors = new int[length + 1]; + } + System.arraycopy(colors, 0, tempColors, 0, length); + tempColors[length] = colors[length - 1]; + tempPositions = st.mTempPositions; final float fraction = 1.0f / (float) (length - 1); - positions = new float[length + 1]; + if (tempPositions == null || tempPositions.length != length + 1) { + tempPositions = st.mTempPositions = new float[length + 1]; + } + final float level = (float) getLevel() / 10000.0f; for (int i = 0; i < length; i++) { - positions[i] = i * fraction * level; + tempPositions[i] = i * fraction * level; } - positions[length] = 1.0f; + tempPositions[length] = 1.0f; + } - mFillPaint.setShader(new SweepGradient(x0, y0, colors, positions)); + mFillPaint.setShader(new SweepGradient(x0, y0, tempColors, tempPositions)); } } } @@ -560,10 +586,18 @@ public class GradientDrawable extends Drawable { com.android.internal.R.styleable.GradientDrawable_shape, RECTANGLE); if (shapeType == RING) { - st.mInnerRadius = a.getFloat( - com.android.internal.R.styleable.GradientDrawable_innerRadiusRatio, 3.0f); - st.mThickness = a.getFloat( - com.android.internal.R.styleable.GradientDrawable_thicknessRatio, 9.0f); + st.mInnerRadius = a.getDimensionPixelSize( + com.android.internal.R.styleable.GradientDrawable_innerRadius, -1); + if (st.mInnerRadius == -1) { + st.mInnerRadiusRatio = a.getFloat( + com.android.internal.R.styleable.GradientDrawable_innerRadiusRatio, 3.0f); + } + st.mThickness = a.getDimensionPixelSize( + com.android.internal.R.styleable.GradientDrawable_thickness, -1); + if (st.mThickness == -1) { + st.mThicknessRatio = a.getFloat( + com.android.internal.R.styleable.GradientDrawable_thicknessRatio, 9.0f); + } st.mUseLevelForShape = a.getBoolean( com.android.internal.R.styleable.GradientDrawable_useLevel, true); } @@ -791,31 +825,45 @@ public class GradientDrawable extends Drawable { return mGradientState; } + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mGradientState = new GradientState(mGradientState); + initializeWithState(mGradientState); + mMutated = true; + } + return this; + } + final static class GradientState extends ConstantState { - public int mChangingConfigurations; - public int mShape = RECTANGLE; - public int mGradient = LINEAR_GRADIENT; - public Orientation mOrientation; - public int[] mColors; - public float[] mPositions; - public boolean mHasSolidColor; - public int mSolidColor; - public int mStrokeWidth = -1; // if >= 0 use stroking. - public int mStrokeColor; - public float mStrokeDashWidth; - public float mStrokeDashGap; - public float mRadius; // use this if mRadiusArray is null - public float[] mRadiusArray; - public Rect mPadding; - public int mWidth = -1; - public int mHeight = -1; - public float mInnerRadius; - public float mThickness; - private float mCenterX = 0.5f; - private float mCenterY = 0.5f; - private float mGradientRadius = 0.5f; - private boolean mUseLevel; - private boolean mUseLevelForShape; + public int mChangingConfigurations; + public int mShape = RECTANGLE; + public int mGradient = LINEAR_GRADIENT; + public Orientation mOrientation; + public int[] mColors; + public int[] mTempColors; // no need to copy + public float[] mTempPositions; // no need to copy + public float[] mPositions; + public boolean mHasSolidColor; + public int mSolidColor; + public int mStrokeWidth = -1; // if >= 0 use stroking. + public int mStrokeColor; + public float mStrokeDashWidth; + public float mStrokeDashGap; + public float mRadius; // use this if mRadiusArray is null + public float[] mRadiusArray; + public Rect mPadding; + public int mWidth = -1; + public int mHeight = -1; + public float mInnerRadiusRatio; + public float mThicknessRatio; + public int mInnerRadius; + public int mThickness; + private float mCenterX = 0.5f; + private float mCenterY = 0.5f; + private float mGradientRadius = 0.5f; + private boolean mUseLevel; + private boolean mUseLevelForShape; GradientState() { @@ -827,6 +875,40 @@ public class GradientDrawable extends Drawable { mColors = colors; } + public GradientState(GradientState state) { + mChangingConfigurations = state.mChangingConfigurations; + mShape = state.mShape; + mGradient = state.mGradient; + mOrientation = state.mOrientation; + mColors = state.mColors.clone(); + if (state.mPositions != null) { + mPositions = state.mPositions.clone(); + } + mHasSolidColor = state.mHasSolidColor; + mStrokeWidth = state.mStrokeWidth; + mStrokeColor = state.mStrokeColor; + mStrokeDashWidth = state.mStrokeDashWidth; + mStrokeDashGap = state.mStrokeDashGap; + mRadius = state.mRadius; + if (state.mRadiusArray != null) { + mRadiusArray = state.mRadiusArray.clone(); + } + if (state.mPadding != null) { + mPadding = new Rect(state.mPadding); + } + mWidth = state.mWidth; + mHeight = state.mHeight; + mInnerRadiusRatio = state.mInnerRadiusRatio; + mThicknessRatio = state.mThicknessRatio; + mInnerRadius = state.mInnerRadius; + mThickness = state.mThickness; + mCenterX = state.mCenterX; + mCenterY = state.mCenterY; + mGradientRadius = state.mGradientRadius; + mUseLevel = state.mUseLevel; + mUseLevelForShape = state.mUseLevelForShape; + } + @Override public Drawable newDrawable() { return new GradientDrawable(this); @@ -895,6 +977,11 @@ public class GradientDrawable extends Drawable { private GradientDrawable(GradientState state) { mGradientState = state; + initializeWithState(state); + mRectIsDirty = true; + } + + private void initializeWithState(GradientState state) { if (state.mHasSolidColor) { mFillPaint.setColor(state.mSolidColor); } @@ -906,12 +993,11 @@ public class GradientDrawable extends Drawable { mStrokePaint.setColor(state.mStrokeColor); if (state.mStrokeDashWidth != 0.0f) { - DashPathEffect e = new DashPathEffect(new float[] { - state.mStrokeDashWidth, state.mStrokeDashGap}, 0); + DashPathEffect e = new DashPathEffect( + new float[] { state.mStrokeDashWidth, state.mStrokeDashGap }, 0); mStrokePaint.setPathEffect(e); } } - mRectIsDirty = true; } } diff --git a/graphics/java/android/graphics/drawable/InsetDrawable.java b/graphics/java/android/graphics/drawable/InsetDrawable.java index 80b8e96e46d9a6d040cc4fdf7d0a2954bda38d97..604772602ae168b571a05ad691744eda116fb122 100644 --- a/graphics/java/android/graphics/drawable/InsetDrawable.java +++ b/graphics/java/android/graphics/drawable/InsetDrawable.java @@ -44,6 +44,9 @@ import java.io.IOException; public class InsetDrawable extends Drawable implements Drawable.Callback { // Most of this is copied from ScaleDrawable. + private InsetState mInsetState; + private final Rect mTmpRect = new Rect(); + private boolean mMutated; /*package*/ InsetDrawable() { this(null); @@ -239,7 +242,27 @@ public class InsetDrawable extends Drawable implements Drawable.Callback return null; } + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mInsetState.mDrawable.mutate(); + mMutated = true; + } + return this; + } + final static class InsetState extends ConstantState { + Drawable mDrawable; + int mChangingConfigurations; + + int mInsetLeft; + int mInsetTop; + int mInsetRight; + int mInsetBottom; + + boolean mCheckedConstantState; + boolean mCanConstantState; + InsetState(InsetState orig, InsetDrawable owner) { if (orig != null) { mDrawable = orig.mDrawable.getConstantState().newDrawable(); @@ -270,25 +293,10 @@ public class InsetDrawable extends Drawable implements Drawable.Callback return mCanConstantState; } - - Drawable mDrawable; - int mChangingConfigurations; - - int mInsetLeft; - int mInsetTop; - int mInsetRight; - int mInsetBottom; - - boolean mCheckedConstantState; - boolean mCanConstantState; } private InsetDrawable(InsetState state) { - InsetState as = new InsetState(state, this); - mInsetState = as; + mInsetState = new InsetState(state, this); } - - private InsetState mInsetState; - private final Rect mTmpRect = new Rect(); } diff --git a/graphics/java/android/graphics/drawable/LayerDrawable.java b/graphics/java/android/graphics/drawable/LayerDrawable.java index 59dfbd46c758161b67fc70cf6829b24a424cfd87..c7772053f98cdf02e4a9dc2273f62aef34825834 100644 --- a/graphics/java/android/graphics/drawable/LayerDrawable.java +++ b/graphics/java/android/graphics/drawable/LayerDrawable.java @@ -51,6 +51,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { private int[] mPaddingB; private final Rect mTmpRect = new Rect(); + private boolean mMutated; /** * Create a new layer drawable with the list of specified layers. @@ -71,16 +72,16 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { LayerDrawable(Drawable[] layers, LayerState state) { this(state); int length = layers.length; - Rec[] r = new Rec[length]; + ChildDrawable[] r = new ChildDrawable[length]; for (int i = 0; i < length; i++) { - r[i] = new Rec(); + r[i] = new ChildDrawable(); r[i].mDrawable = layers[i]; layers[i].setCallback(this); mLayerState.mChildrenChangingConfigurations |= layers[i].getChangingConfigurations(); } mLayerState.mNum = length; - mLayerState.mArray = r; + mLayerState.mChildren = r; ensurePadding(); } @@ -171,26 +172,26 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { */ private void addLayer(Drawable layer, int id, int left, int top, int right, int bottom) { final LayerState st = mLayerState; - int N = st.mArray != null ? st.mArray.length : 0; + int N = st.mChildren != null ? st.mChildren.length : 0; int i = st.mNum; if (i >= N) { - Rec[] nu = new Rec[N + 10]; + ChildDrawable[] nu = new ChildDrawable[N + 10]; if (i > 0) { - System.arraycopy(st.mArray, 0, nu, 0, i); + System.arraycopy(st.mChildren, 0, nu, 0, i); } - st.mArray = nu; + st.mChildren = nu; } mLayerState.mChildrenChangingConfigurations |= layer.getChangingConfigurations(); - Rec rec = new Rec(); - st.mArray[i] = rec; - rec.mId = id; - rec.mDrawable = layer; - rec.mInsetL = left; - rec.mInsetT = top; - rec.mInsetR = right; - rec.mInsetB = bottom; + ChildDrawable childDrawable = new ChildDrawable(); + st.mChildren[i] = childDrawable; + childDrawable.mId = id; + childDrawable.mDrawable = layer; + childDrawable.mInsetL = left; + childDrawable.mInsetT = top; + childDrawable.mInsetR = right; + childDrawable.mInsetB = bottom; st.mNum++; layer.setCallback(this); @@ -203,7 +204,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { * @return The {@link Drawable} of the layer that has the given id in the hierarchy or null. */ public Drawable findDrawableByLayerId(int id) { - final Rec[] layers = mLayerState.mArray; + final ChildDrawable[] layers = mLayerState.mChildren; for (int i = mLayerState.mNum - 1; i >= 0; i--) { if (layers[i].mId == id) { @@ -221,7 +222,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { * @param id The ID to assign to the layer. */ public void setId(int index, int id) { - mLayerState.mArray[index].mId = id; + mLayerState.mChildren[index].mId = id; } /** @@ -240,7 +241,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { * @return The {@link android.graphics.drawable.Drawable} at the specified layer index. */ public Drawable getDrawable(int index) { - return mLayerState.mArray[index].mDrawable; + return mLayerState.mChildren[index].mDrawable; } /** @@ -251,7 +252,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { * @return The id of the layer or {@link android.view.View#NO_ID} if the layer has no id. */ public int getId(int index) { - return mLayerState.mArray[index].mId; + return mLayerState.mChildren[index].mId; } /** @@ -263,7 +264,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { * the id was not found). */ public boolean setDrawableByLayerId(int id, Drawable drawable) { - final Rec[] layers = mLayerState.mArray; + final ChildDrawable[] layers = mLayerState.mChildren; for (int i = mLayerState.mNum - 1; i >= 0; i--) { if (layers[i].mId == id) { @@ -282,11 +283,11 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { bottom -= b; */ public void setLayerInset(int index, int l, int t, int r, int b) { - Rec rec = mLayerState.mArray[index]; - rec.mInsetL = l; - rec.mInsetT = t; - rec.mInsetR = r; - rec.mInsetB = b; + ChildDrawable childDrawable = mLayerState.mChildren[index]; + childDrawable.mInsetL = l; + childDrawable.mInsetT = t; + childDrawable.mInsetR = r; + childDrawable.mInsetB = b; } // overrides from Drawable.Callback @@ -313,7 +314,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { @Override public void draw(Canvas canvas) { - final Rec[] array = mLayerState.mArray; + final ChildDrawable[] array = mLayerState.mChildren; final int N = mLayerState.mNum; for (int i=0; i width) { @@ -478,11 +479,11 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { @Override public int getIntrinsicHeight() { int height = -1; - final Rec[] array = mLayerState.mArray; + final ChildDrawable[] array = mLayerState.mChildren; final int N = mLayerState.mNum; int padT=0, padB=0; for (int i=0; i height) { height = h; @@ -493,7 +494,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { return height; } - private boolean reapplyPadding(int i, Rec r) { + private boolean reapplyPadding(int i, ChildDrawable r) { final Rect rect = mTmpRect; r.mDrawable.getPadding(rect); if (rect.left != mPaddingL[i] || rect.top != mPaddingT[i] || @@ -527,7 +528,20 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { return null; } - static class Rec { + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + final ChildDrawable[] array = mLayerState.mChildren; + final int N = mLayerState.mNum; + for (int i = 0; i < N; i++) { + array[i].mDrawable.mutate(); + } + mMutated = true; + } + return this; + } + + static class ChildDrawable { public Drawable mDrawable; public int mInsetL, mInsetT, mInsetR, mInsetB; public int mId; @@ -535,7 +549,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { static class LayerState extends ConstantState { int mNum; - Rec[] mArray; + ChildDrawable[] mChildren; int mChangingConfigurations; int mChildrenChangingConfigurations; @@ -551,18 +565,18 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { LayerState(LayerState orig, LayerDrawable owner) { if (orig != null) { - final Rec[] origRec = orig.mArray; + final ChildDrawable[] origChildDrawable = orig.mChildren; final int N = orig.mNum; mNum = N; - mArray = new Rec[N]; + mChildren = new ChildDrawable[N]; mChangingConfigurations = orig.mChangingConfigurations; mChildrenChangingConfigurations = orig.mChildrenChangingConfigurations; for (int i = 0; i < N; i++) { - final Rec r = mArray[i] = new Rec(); - final Rec or = origRec[i]; + final ChildDrawable r = mChildren[i] = new ChildDrawable(); + final ChildDrawable or = origChildDrawable[i]; r.mDrawable = or.mDrawable.getConstantState().newDrawable(); r.mDrawable.setCallback(owner); r.mInsetL = or.mInsetL; @@ -579,7 +593,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { mCheckedConstantState = mCanConstantState = true; } else { mNum = 0; - mArray = null; + mChildren = null; } } @@ -599,11 +613,9 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { } final int N = mNum; - int op = N > 0 ? mArray[0].mDrawable.getOpacity() - : PixelFormat.TRANSPARENT; + int op = N > 0 ? mChildren[0].mDrawable.getOpacity() : PixelFormat.TRANSPARENT; for (int i = 1; i < N; i++) { - op = Drawable.resolveOpacity(op, mArray[i].mDrawable - .getOpacity()); + op = Drawable.resolveOpacity(op, mChildren[i].mDrawable.getOpacity()); } mOpacity = op; mHaveOpacity = true; @@ -618,7 +630,7 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { boolean stateful = false; final int N = mNum; for (int i = 0; i < N; i++) { - if (mArray[i].mDrawable.isStateful()) { + if (mChildren[i].mDrawable.isStateful()) { stateful = true; break; } @@ -630,11 +642,11 @@ public class LayerDrawable extends Drawable implements Drawable.Callback { } public synchronized boolean canConstantState() { - if (!mCheckedConstantState && mArray != null) { + if (!mCheckedConstantState && mChildren != null) { mCanConstantState = true; final int N = mNum; for (int i=0; i * It can be defined in an XML file with the <level-list> element. - * Each Drawable level is defined in a nested <item> + * Each Drawable level is defined in a nested <item>. For example: *

                + *
                + * <level-list xmlns:android="http://schemas.android.com/apk/res/android">
                + *  <item android:maxLevel="0" android:drawable="@drawable/ic_wifi_signal_1" />
                + *  <item android:maxLevel="1" android:drawable="@drawable/ic_wifi_signal_2" />
                + *  <item android:maxLevel="2" android:drawable="@drawable/ic_wifi_signal_3" />
                + *  <item android:maxLevel="3" android:drawable="@drawable/ic_wifi_signal_4" />
                + * </level-list>
                + *
                + *

                With this XML saved into the res/drawable/ folder of the project, it can be referenced as + * the drawable for an {@link android.widget.ImageView}. The default image is the first in the list. + * It can then be changed to one of the other levels with + * {@link android.widget.ImageView#setImageLevel(int)}.

                * @attr ref android.R.styleable#LevelListDrawableItem_minLevel * @attr ref android.R.styleable#LevelListDrawableItem_maxLevel * @attr ref android.R.styleable#LevelListDrawableItem_drawable */ public class LevelListDrawable extends DrawableContainer { - public LevelListDrawable() - { + private final LevelListState mLevelListState; + private boolean mMutated; + + public LevelListDrawable() { this(null); } @@ -54,7 +67,7 @@ public class LevelListDrawable extends DrawableContainer { onLevelChange(getLevel()); } } - + // overrides from Drawable @Override @@ -65,21 +78,22 @@ public class LevelListDrawable extends DrawableContainer { } return super.onLevelChange(level); } - - @Override public void inflate(Resources r, XmlPullParser parser, - AttributeSet attrs) - throws XmlPullParserException, IOException { + + @Override + public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) + throws XmlPullParserException, IOException { + super.inflate(r, parser, attrs); - + int type; int low = 0; - final int innerDepth = parser.getDepth()+1; + final int innerDepth = parser.getDepth() + 1; int depth; - while ((type=parser.next()) != XmlPullParser.END_DOCUMENT - && ((depth=parser.getDepth()) >= innerDepth - || type != XmlPullParser.END_TAG)) { + while ((type = parser.next()) != XmlPullParser.END_DOCUMENT + && ((depth = parser.getDepth()) >= innerDepth + || type != XmlPullParser.END_TAG)) { if (type != XmlPullParser.START_TAG) { continue; } @@ -87,50 +101,60 @@ public class LevelListDrawable extends DrawableContainer { if (depth > innerDepth || !parser.getName().equals("item")) { continue; } - + TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.LevelListDrawableItem); - + low = a.getInt( com.android.internal.R.styleable.LevelListDrawableItem_minLevel, 0); int high = a.getInt( com.android.internal.R.styleable.LevelListDrawableItem_maxLevel, 0); int drawableRes = a.getResourceId( com.android.internal.R.styleable.LevelListDrawableItem_drawable, 0); - + a.recycle(); - + if (high < 0) { throw new XmlPullParserException(parser.getPositionDescription() - + ": tag requires a 'maxLevel' attribute"); + + ": tag requires a 'maxLevel' attribute"); } - + Drawable dr; if (drawableRes != 0) { dr = r.getDrawable(drawableRes); } else { - while ((type=parser.next()) == XmlPullParser.TEXT) { + while ((type = parser.next()) == XmlPullParser.TEXT) { } if (type != XmlPullParser.START_TAG) { throw new XmlPullParserException( parser.getPositionDescription() - + ": tag requires a 'drawable' attribute or " - + "child tag defining a drawable"); + + ": tag requires a 'drawable' attribute or " + + "child tag defining a drawable"); } dr = Drawable.createFromXmlInner(r, parser, attrs); } mLevelListState.addLevel(low, high, dr); - low = high+1; } onLevelChange(getLevel()); } - private final static class LevelListState extends DrawableContainerState - { - LevelListState(LevelListState orig, LevelListDrawable owner) - { + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mLevelListState.mLows = mLevelListState.mLows.clone(); + mLevelListState.mHighs = mLevelListState.mHighs.clone(); + mMutated = true; + } + return this; + } + + private final static class LevelListState extends DrawableContainerState { + private int[] mLows; + private int[] mHighs; + + LevelListState(LevelListState orig, LevelListDrawable owner) { super(orig, owner); if (orig != null) { @@ -142,19 +166,17 @@ public class LevelListDrawable extends DrawableContainer { } } - public void addLevel(int low, int high, Drawable drawable) - { + public void addLevel(int low, int high, Drawable drawable) { int pos = addChild(drawable); mLows[pos] = low; mHighs[pos] = high; } - public int indexOfLevel(int level) - { + public int indexOfLevel(int level) { final int[] lows = mLows; final int[] highs = mHighs; final int N = getChildCount(); - for (int i=0; i= lows[i] && level <= highs[i]) { return i; } @@ -163,14 +185,12 @@ public class LevelListDrawable extends DrawableContainer { } @Override - public Drawable newDrawable() - { + public Drawable newDrawable() { return new LevelListDrawable(this); } @Override - public void growArray(int oldSize, int newSize) - { + public void growArray(int oldSize, int newSize) { super.growArray(oldSize, newSize); int[] newInts = new int[newSize]; System.arraycopy(mLows, 0, newInts, 0, oldSize); @@ -179,19 +199,13 @@ public class LevelListDrawable extends DrawableContainer { System.arraycopy(mHighs, 0, newInts, 0, oldSize); mHighs = newInts; } - - private int[] mLows; - private int[] mHighs; } - private LevelListDrawable(LevelListState state) - { + private LevelListDrawable(LevelListState state) { LevelListState as = new LevelListState(state, this); mLevelListState = as; setConstantState(as); onLevelChange(getLevel()); } - - private final LevelListState mLevelListState; } diff --git a/graphics/java/android/graphics/drawable/NinePatchDrawable.java b/graphics/java/android/graphics/drawable/NinePatchDrawable.java index c98ef5ba75215babfd887b7dc8a41b338e6ceebc..dace96c9c891958614b12e9fa9aa32f061a2427d 100644 --- a/graphics/java/android/graphics/drawable/NinePatchDrawable.java +++ b/graphics/java/android/graphics/drawable/NinePatchDrawable.java @@ -17,6 +17,15 @@ package android.graphics.drawable; import android.graphics.*; +import android.content.res.Resources; +import android.content.res.TypedArray; +import android.util.AttributeSet; +import android.util.TypedValue; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; + +import java.io.IOException; +import java.io.InputStream; /** * @@ -26,9 +35,16 @@ import android.graphics.*; * */ public class NinePatchDrawable extends Drawable { + private NinePatchState mNinePatchState; + private NinePatch mNinePatch; + private Rect mPadding; + private Paint mPaint; + private boolean mMutated; + + NinePatchDrawable() { + } - public NinePatchDrawable(Bitmap bitmap, byte[] chunk, - Rect padding, String srcName) { + public NinePatchDrawable(Bitmap bitmap, byte[] chunk, Rect padding, String srcName) { this(new NinePatchState(new NinePatch(bitmap, chunk, srcName), padding)); } @@ -36,6 +52,13 @@ public class NinePatchDrawable extends Drawable { this(new NinePatchState(patch, null)); } + private void setNinePatchState(NinePatchState state) { + mNinePatchState = state; + mNinePatch = state.mNinePatch; + mPadding = state.mPadding; + if (state.mDither) setDither(state.mDither); + } + // overrides @Override @@ -45,8 +68,7 @@ public class NinePatchDrawable extends Drawable { @Override public int getChangingConfigurations() { - return super.getChangingConfigurations() - | mNinePatchState.mChangingConfigurations; + return super.getChangingConfigurations() | mNinePatchState.mChangingConfigurations; } @Override @@ -70,6 +92,55 @@ public class NinePatchDrawable extends Drawable { getPaint().setDither(dither); } + @Override + public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) + throws XmlPullParserException, IOException { + super.inflate(r, parser, attrs); + + TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.NinePatchDrawable); + + final int id = a.getResourceId(com.android.internal.R.styleable.NinePatchDrawable_src, 0); + if (id == 0) { + throw new XmlPullParserException(parser.getPositionDescription() + + ": requires a valid src attribute"); + } + + final boolean dither = a.getBoolean( + com.android.internal.R.styleable.NinePatchDrawable_dither, false); + final BitmapFactory.Options options = new BitmapFactory.Options(); + if (dither) { + options.inDither = false; + } + + final Rect padding = new Rect(); + Bitmap bitmap = null; + + try { + final TypedValue value = new TypedValue(); + final InputStream is = r.openRawResource(id, value); + + bitmap = BitmapFactory.decodeStream(r, value, is, padding, options); + + is.close(); + } catch (IOException e) { + // Ignore + } + + if (bitmap == null) { + throw new XmlPullParserException(parser.getPositionDescription() + + ": requires a valid src attribute"); + } else if (bitmap.getNinePatchChunk() == null) { + throw new XmlPullParserException(parser.getPositionDescription() + + ": requires a valid 9-patch source image"); + } + + setNinePatchState(new NinePatchState( + new NinePatch(bitmap, bitmap.getNinePatchChunk(), "XML 9-patch"), padding, dither)); + + a.recycle(); + } + + public Paint getPaint() { if (mPaint == null) { mPaint = new Paint(); @@ -104,12 +175,13 @@ public class NinePatchDrawable extends Drawable { } /** - * Returns a {@link android.graphics.PixelFormat graphics.PixelFormat} value of OPAQUE or TRANSLUCENT. + * Returns a {@link android.graphics.PixelFormat graphics.PixelFormat} + * value of OPAQUE or TRANSLUCENT. */ @Override public int getOpacity() { - return mNinePatch.hasAlpha() || (mPaint != null && mPaint.getAlpha() < 255) - ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE; + return mNinePatch.hasAlpha() || (mPaint != null && mPaint.getAlpha() < 255) ? + PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE; } @Override @@ -123,16 +195,42 @@ public class NinePatchDrawable extends Drawable { return mNinePatchState; } + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mNinePatchState = new NinePatchState(mNinePatchState); + mNinePatch = mNinePatchState.mNinePatch; + mPadding = mNinePatchState.mPadding; + mMutated = true; + } + return this; + } + final static class NinePatchState extends ConstantState { - NinePatchState(NinePatch ninePatch, Rect padding) - { + final NinePatch mNinePatch; + final Rect mPadding; + final boolean mDither; + int mChangingConfigurations; + + NinePatchState(NinePatch ninePatch, Rect padding) { + this(ninePatch, padding, false); + } + + NinePatchState(NinePatch ninePatch, Rect rect, boolean dither) { mNinePatch = ninePatch; - mPadding = padding; + mPadding = rect; + mDither = dither; + } + + NinePatchState(NinePatchState state) { + mNinePatch = new NinePatch(state.mNinePatch); + mPadding = new Rect(state.mPadding); + mChangingConfigurations = state.mChangingConfigurations; + mDither = state.mDither; } @Override - public Drawable newDrawable() - { + public Drawable newDrawable() { return new NinePatchDrawable(this); } @@ -140,21 +238,10 @@ public class NinePatchDrawable extends Drawable { public int getChangingConfigurations() { return mChangingConfigurations; } - - final NinePatch mNinePatch; - final Rect mPadding; - int mChangingConfigurations; } private NinePatchDrawable(NinePatchState state) { - mNinePatchState = state; - mNinePatch = state.mNinePatch; - mPadding = state.mPadding; + setNinePatchState(state); } - - private final NinePatchState mNinePatchState; - private final NinePatch mNinePatch; - private final Rect mPadding; - private Paint mPaint; } diff --git a/graphics/java/android/graphics/drawable/RotateDrawable.java b/graphics/java/android/graphics/drawable/RotateDrawable.java index 3e03ed4c905125971b1d619d185d81239d5540c2..cb16cb711b42728f1089aadae0c62d65d1cb65f3 100644 --- a/graphics/java/android/graphics/drawable/RotateDrawable.java +++ b/graphics/java/android/graphics/drawable/RotateDrawable.java @@ -45,6 +45,10 @@ import java.io.IOException; * @attr ref android.R.styleable#RotateDrawable_drawable */ public class RotateDrawable extends Drawable implements Drawable.Callback { + private static final float MAX_LEVEL = 10000.0f; + + private RotateState mState; + private boolean mMutated; /** *

                Create a new rotating drawable with an empty state.

                @@ -84,6 +88,13 @@ public class RotateDrawable extends Drawable implements Drawable.Callback { canvas.restoreToCount(saveCount); } + /** + * Returns the drawable rotated by this RotateDrawable. + */ + public Drawable getDrawable() { + return mState.mDrawable; + } + @Override public int getChangingConfigurations() { return super.getChangingConfigurations() @@ -248,6 +259,15 @@ public class RotateDrawable extends Drawable implements Drawable.Callback { } } + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mState.mDrawable.mutate(); + mMutated = true; + } + return this; + } + /** *

                Represents the state of a rotation for a given drawable. The same * rotate drawable can be invoked with different states to drive several @@ -268,6 +288,9 @@ public class RotateDrawable extends Drawable implements Drawable.Callback { float mCurrentDegrees; + private boolean mCanConstantState; + private boolean mCheckedConstantState; + public RotateState(RotateState source, RotateDrawable owner) { if (source != null) { mDrawable = source.mDrawable.getConstantState().newDrawable(); @@ -300,12 +323,5 @@ public class RotateDrawable extends Drawable implements Drawable.Callback { return mCanConstantState; } - - private boolean mCanConstantState; - private boolean mCheckedConstantState; } - - private static final float MAX_LEVEL = 10000.0f; - - private RotateState mState; } diff --git a/graphics/java/android/graphics/drawable/ScaleDrawable.java b/graphics/java/android/graphics/drawable/ScaleDrawable.java index c40c8c068164236209e78224f4b07f8b4b065715..7125ab1e689e8bf601d289d10fcf6591561e0d5b 100644 --- a/graphics/java/android/graphics/drawable/ScaleDrawable.java +++ b/graphics/java/android/graphics/drawable/ScaleDrawable.java @@ -24,7 +24,6 @@ import android.content.res.TypedArray; import android.graphics.*; import android.view.Gravity; import android.util.AttributeSet; -import android.util.Log; import java.io.IOException; @@ -44,6 +43,7 @@ import java.io.IOException; */ public class ScaleDrawable extends Drawable implements Drawable.Callback { private ScaleState mScaleState; + private boolean mMutated; private final Rect mTmpRect = new Rect(); ScaleDrawable() { @@ -63,6 +63,13 @@ public class ScaleDrawable extends Drawable implements Drawable.Callback { } } + /** + * Returns the drawable scaled by this ScaleDrawable. + */ + public Drawable getDrawable() { + return mScaleState.mDrawable; + } + private static float getPercent(TypedArray a, int name) { String s = a.getString(name); if (s != null) { @@ -234,7 +241,25 @@ public class ScaleDrawable extends Drawable implements Drawable.Callback { return null; } + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mScaleState.mDrawable.mutate(); + mMutated = true; + } + return this; + } + final static class ScaleState extends ConstantState { + Drawable mDrawable; + int mChangingConfigurations; + float mScaleWidth; + float mScaleHeight; + int mGravity; + + private boolean mCheckedConstantState; + private boolean mCanConstantState; + ScaleState(ScaleState orig, ScaleDrawable owner) { if (orig != null) { mDrawable = orig.mDrawable.getConstantState().newDrawable(); @@ -264,15 +289,6 @@ public class ScaleDrawable extends Drawable implements Drawable.Callback { return mCanConstantState; } - - Drawable mDrawable; - int mChangingConfigurations; - float mScaleWidth; - float mScaleHeight; - int mGravity; - - private boolean mCheckedConstantState; - private boolean mCanConstantState; } private ScaleDrawable(ScaleState state) { diff --git a/graphics/java/android/graphics/drawable/ShapeDrawable.java b/graphics/java/android/graphics/drawable/ShapeDrawable.java index 7e1284f7309b112a27aac94640d40c678a3ff95a..d24194f545f1206ffc868cac10c7474037cccbaf 100644 --- a/graphics/java/android/graphics/drawable/ShapeDrawable.java +++ b/graphics/java/android/graphics/drawable/ShapeDrawable.java @@ -28,15 +28,24 @@ import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; /** - * An object that draws primitive shapes. + * A Drawable object that draws primitive shapes. * A ShapeDrawable takes a {@link android.graphics.drawable.shapes.Shape} * object and manages its presence on the screen. If no Shape is given, then * the ShapeDrawable will default to a * {@link android.graphics.drawable.shapes.RectShape}. + * + * @attr ref android.R.styleable#ShapeDrawablePadding_left + * @attr ref android.R.styleable#ShapeDrawablePadding_top + * @attr ref android.R.styleable#ShapeDrawablePadding_right + * @attr ref android.R.styleable#ShapeDrawablePadding_bottom + * @attr ref android.R.styleable#ShapeDrawable_color + * @attr ref android.R.styleable#ShapeDrawable_width + * @attr ref android.R.styleable#ShapeDrawable_height */ public class ShapeDrawable extends Drawable { private ShapeState mShapeState; - + private boolean mMutated; + /** * ShapeDrawable constructor. */ @@ -334,6 +343,21 @@ public class ShapeDrawable extends Drawable { return mShapeState; } + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + mShapeState.mPaint = new Paint(mShapeState.mPaint); + mShapeState.mPadding = new Rect(mShapeState.mPadding); + try { + mShapeState.mShape = mShapeState.mShape.clone(); + } catch (CloneNotSupportedException e) { + return null; + } + mMutated = true; + } + return this; + } + /** * Defines the intrinsic properties of this ShapeDrawable's Shape. */ diff --git a/graphics/java/android/graphics/drawable/StateListDrawable.java b/graphics/java/android/graphics/drawable/StateListDrawable.java index 1dc162724fad8ea3d7c63357af11e0870ef0abf5..d22a4baaee6973c38e472edf7741348fa77e1a42 100644 --- a/graphics/java/android/graphics/drawable/StateListDrawable.java +++ b/graphics/java/android/graphics/drawable/StateListDrawable.java @@ -27,10 +27,9 @@ import android.util.AttributeSet; import android.util.StateSet; /** - * * Lets you assign a number of graphic images to a single Drawable and swap out the visible item by a string * ID value. - * + *

                *

                It can be defined in an XML file with the <selector> element. * Each state Drawable is defined in a nested <item> element.

                * @@ -51,15 +50,18 @@ import android.util.StateSet; * @attr ref android.R.styleable#DrawableStates_state_pressed */ public class StateListDrawable extends DrawableContainer { - public StateListDrawable() - { + private final StateListState mStateListState; + private boolean mMutated; + + public StateListDrawable() { this(null); } /** * Add a new image/string ID to the set of images. + * * @param stateSet - An array of resource Ids to associate with the image. - * Switch to this image by calling setState(). + * Switch to this image by calling setState(). * @param drawable -The image to show. */ public void addState(int[] stateSet, Drawable drawable) { @@ -74,7 +76,7 @@ public class StateListDrawable extends DrawableContainer { public boolean isStateful() { return true; } - + @Override protected boolean onStateChange(int[] stateSet) { int idx = mStateListState.indexOfStateSet(stateSet); @@ -87,30 +89,31 @@ public class StateListDrawable extends DrawableContainer { return super.onStateChange(stateSet); } - @Override public void inflate(Resources r, XmlPullParser parser, + @Override + public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) - throws XmlPullParserException, IOException { - + throws XmlPullParserException, IOException { + TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.StateListDrawable); super.inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.StateListDrawable_visible); - + mStateListState.setVariablePadding(a.getBoolean( com.android.internal.R.styleable.StateListDrawable_variablePadding, false)); mStateListState.setConstantSize(a.getBoolean( com.android.internal.R.styleable.StateListDrawable_constantSize, false)); - + a.recycle(); - + int type; - final int innerDepth = parser.getDepth()+1; + final int innerDepth = parser.getDepth() + 1; int depth; - while ((type=parser.next()) != XmlPullParser.END_DOCUMENT - && ((depth=parser.getDepth()) >= innerDepth - || type != XmlPullParser.END_TAG)) { + while ((type = parser.next()) != XmlPullParser.END_DOCUMENT + && ((depth = parser.getDepth()) >= innerDepth + || type != XmlPullParser.END_TAG)) { if (type != XmlPullParser.START_TAG) { continue; } @@ -118,9 +121,9 @@ public class StateListDrawable extends DrawableContainer { if (depth > innerDepth || !parser.getName().equals("item")) { continue; } - + int drawableRes = 0; - + int i; int j = 0; final int numAttrs = attrs.getAttributeCount(); @@ -132,27 +135,27 @@ public class StateListDrawable extends DrawableContainer { drawableRes = attrs.getAttributeResourceValue(i, 0); } else { states[j++] = attrs.getAttributeBooleanValue(i, false) - ? stateResId - : -stateResId; + ? stateResId + : -stateResId; } } states = StateSet.trimStateSet(states, j); - + Drawable dr; if (drawableRes != 0) { dr = r.getDrawable(drawableRes); } else { - while ((type=parser.next()) == XmlPullParser.TEXT) { + while ((type = parser.next()) == XmlPullParser.TEXT) { } if (type != XmlPullParser.START_TAG) { throw new XmlPullParserException( parser.getPositionDescription() - + ": tag requires a 'drawable' attribute or " - + "child tag defining a drawable"); + + ": tag requires a 'drawable' attribute or " + + "child tag defining a drawable"); } dr = Drawable.createFromXmlInner(r, parser, attrs); } - + mStateListState.addStateSet(states, dr); } @@ -162,49 +165,76 @@ public class StateListDrawable extends DrawableContainer { StateListState getStateListState() { return mStateListState; } - + /** * Gets the number of states contained in this drawable. - * + * * @return The number of states contained in this drawable. + * @hide pending API council * @see #getStateSet(int) * @see #getStateDrawable(int) - * @hide pending API council */ public int getStateCount() { - return mStateListState.getChildCount(); + return mStateListState.getChildCount(); } /** * Gets the state set at an index. - * + * * @param index The index of the state set. * @return The state set at the index. + * @hide pending API council * @see #getStateCount() * @see #getStateDrawable(int) - * @hide pending API council */ public int[] getStateSet(int index) { return mStateListState.mStateSets[index]; } - + /** * Gets the drawable at an index. - * + * * @param index The index of the drawable. * @return The drawable at the index. + * @hide pending API council * @see #getStateCount() * @see #getStateSet(int) - * @hide pending API council */ public Drawable getStateDrawable(int index) { return mStateListState.getChildren()[index]; } - static final class StateListState extends DrawableContainerState - { - StateListState(StateListState orig, StateListDrawable owner) - { + /** + * Gets the index of the drawable with the provided state set. + * + * @param stateSet the state set to look up + * @return the index of the provided state set, or -1 if not found + * @hide pending API council + * @see #getStateDrawable(int) + * @see #getStateSet(int) + */ + public int getStateDrawableIndex(int[] stateSet) { + return mStateListState.indexOfStateSet(stateSet); + } + + @Override + public Drawable mutate() { + if (!mMutated && super.mutate() == this) { + final int[][] sets = mStateListState.mStateSets; + final int count = sets.length; + mStateListState.mStateSets = new int[count][]; + for (int i = 0; i < count; i++) { + mStateListState.mStateSets[i] = sets[i].clone(); + } + mMutated = true; + } + return this; + } + + static final class StateListState extends DrawableContainerState { + private int[][] mStateSets; + + StateListState(StateListState orig, StateListDrawable owner) { super(orig, owner); if (orig != null) { @@ -220,11 +250,10 @@ public class StateListDrawable extends DrawableContainer { return pos; } - private int indexOfStateSet(int[] stateSet) - { + private int indexOfStateSet(int[] stateSet) { final int[][] stateSets = mStateSets; final int N = getChildCount(); - for (int i=0; i mState.mDuration) { - if (mState.mAlpha == 0) { + if (time - mStartTimeMillis > mDuration) { + if (mAlpha == 0) { mFrom = 0; mTo = 255; - mState.mAlpha = 0; + mAlpha = 0; mReverse = false; } else { mFrom = 255; mTo = 0; - mState.mAlpha = 255; + mAlpha = 255; mReverse = true; } - mDuration = mState.mDuration = duration; + mDuration = mOriginalDuration = duration; mTransitionState = TRANSITION_STARTING; invalidateSelf(); return; } mReverse = !mReverse; - mFrom = mState.mAlpha; + mFrom = mAlpha; mTo = mReverse ? 0 : 255; mDuration = (int) (mReverse ? time - mStartTimeMillis : - mState.mDuration - (time - mStartTimeMillis)); + mOriginalDuration - (time - mStartTimeMillis)); mTransitionState = TRANSITION_STARTING; } @Override public void draw(Canvas canvas) { boolean done = true; - final TransitionState state = mState; switch (mTransitionState) { case TRANSITION_STARTING: @@ -177,14 +176,14 @@ public class TransitionDrawable extends LayerDrawable implements Drawable.Callba (SystemClock.uptimeMillis() - mStartTimeMillis) / mDuration; done = normalized >= 1.0f; normalized = Math.min(normalized, 1.0f); - state.mAlpha = (int) (mFrom + (mTo - mFrom) * normalized); + mAlpha = (int) (mFrom + (mTo - mFrom) * normalized); } break; } - final int alpha = state.mAlpha; - final boolean crossFade = state.mCrossFade; - final Rec[] array = mLayerState.mArray; + final int alpha = mAlpha; + final boolean crossFade = mCrossFade; + final ChildDrawable[] array = mLayerState.mChildren; Drawable d; d = array[0].mDrawable; @@ -217,7 +216,7 @@ public class TransitionDrawable extends LayerDrawable implements Drawable.Callba * @param enabled True to enable cross fading, false otherwise. */ public void setCrossFadeEnabled(boolean enabled) { - mState.mCrossFade = enabled; + mCrossFade = enabled; } /** @@ -226,14 +225,10 @@ public class TransitionDrawable extends LayerDrawable implements Drawable.Callba * @return True if cross fading is enabled, false otherwise. */ public boolean isCrossFadeEnabled() { - return mState.mCrossFade; + return mCrossFade; } static class TransitionState extends LayerState { - int mAlpha = 0; - int mDuration; - boolean mCrossFade; - TransitionState(TransitionState orig, TransitionDrawable owner) { super(orig, owner); } diff --git a/graphics/java/android/graphics/drawable/package.html b/graphics/java/android/graphics/drawable/package.html index 17ee865296dcf9276e7f415d8cd834ad27458697..da49df763bfaacead76f0fb45badba90a13e2ef6 100644 --- a/graphics/java/android/graphics/drawable/package.html +++ b/graphics/java/android/graphics/drawable/package.html @@ -4,6 +4,6 @@ Provides classes to manage a variety of visual elements that are intended for display only, such as bitmaps and gradients. These elements are often used by widgets as background images or simply as indicators (for example, a volume level indicator). You can create most of these in XML as described in Resources. +href="{@docRoot}guide/topics/resources/available-resources.html">Availeble Resource Types. diff --git a/graphics/java/android/graphics/drawable/shapes/PathShape.java b/graphics/java/android/graphics/drawable/shapes/PathShape.java index 3656a0b9e676b20d4f59e45d63ec79d5b76055f6..30b73479a98cbbc8ff51a73f0e709d1aa6fbb357 100644 --- a/graphics/java/android/graphics/drawable/shapes/PathShape.java +++ b/graphics/java/android/graphics/drawable/shapes/PathShape.java @@ -64,5 +64,12 @@ public class PathShape extends Shape { mScaleX = width / mStdWidth; mScaleY = height / mStdHeight; } + + @Override + public PathShape clone() throws CloneNotSupportedException { + PathShape shape = (PathShape) super.clone(); + shape.mPath = new Path(mPath); + return shape; + } } diff --git a/graphics/java/android/graphics/drawable/shapes/RectShape.java b/graphics/java/android/graphics/drawable/shapes/RectShape.java index 4f038aef143fc2352d84814865c97c62551bf561..a3d2654b89306bb17b37df52a774f3f3c2e4fe34 100644 --- a/graphics/java/android/graphics/drawable/shapes/RectShape.java +++ b/graphics/java/android/graphics/drawable/shapes/RectShape.java @@ -50,4 +50,11 @@ public class RectShape extends Shape { protected final RectF rect() { return mRect; } + + @Override + public RectShape clone() throws CloneNotSupportedException { + final RectShape shape = (RectShape) super.clone(); + shape.mRect = new RectF(mRect); + return shape; + } } diff --git a/graphics/java/android/graphics/drawable/shapes/RoundRectShape.java b/graphics/java/android/graphics/drawable/shapes/RoundRectShape.java index 54ef3f76f248fce939ab46890db7d19902834754..f4cf15c7469884dd1ad7b42cab969a2451d9ad2b 100644 --- a/graphics/java/android/graphics/drawable/shapes/RoundRectShape.java +++ b/graphics/java/android/graphics/drawable/shapes/RoundRectShape.java @@ -105,4 +105,15 @@ public class RoundRectShape extends RectShape { } } } + + @Override + public RoundRectShape clone() throws CloneNotSupportedException { + RoundRectShape shape = (RoundRectShape) super.clone(); + shape.mOuterRadii = mOuterRadii.clone(); + shape.mInnerRadii = mInnerRadii.clone(); + shape.mInset = new RectF(mInset); + shape.mInnerRect = new RectF(mInnerRect); + shape.mPath = new Path(mPath); + return shape; + } } diff --git a/graphics/java/android/graphics/drawable/shapes/Shape.java b/graphics/java/android/graphics/drawable/shapes/Shape.java index fc54bc185b3c80c16f4c4ae93f2f63dbdc0b4ac1..4e192f95dac97a8a256fe65be25c71a03f65ce76 100644 --- a/graphics/java/android/graphics/drawable/shapes/Shape.java +++ b/graphics/java/android/graphics/drawable/shapes/Shape.java @@ -25,7 +25,7 @@ import android.graphics.Paint; * but more graphical control is available if you instead pass * it to a {@link android.graphics.drawable.ShapeDrawable}. */ -public abstract class Shape { +public abstract class Shape implements Cloneable { private float mWidth; private float mHeight; @@ -92,4 +92,9 @@ public abstract class Shape { * @param height the new height of the Shape */ protected void onResize(float width, float height) {} + + @Override + public Shape clone() throws CloneNotSupportedException { + return (Shape) super.clone(); + } } diff --git a/include/GLES/egl.h b/include/GLES/egl.h deleted file mode 100644 index 08834ab8b6d6a4a516d057e20acb4ed9d65546f3..0000000000000000000000000000000000000000 --- a/include/GLES/egl.h +++ /dev/null @@ -1,268 +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. - */ - -#ifndef ANDROID_EGL_H -#define ANDROID_EGL_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define EGL_VERSION_1_0 1 -#define EGL_VERSION_1_1 1 -#define EGL_VERSION_1_2 1 - -#define EGL_FALSE 0 -#define EGL_TRUE 1 - -/* Errors */ -#define EGL_SUCCESS 0x3000 -#define EGL_NOT_INITIALIZED 0x3001 -#define EGL_BAD_ACCESS 0x3002 -#define EGL_BAD_ALLOC 0x3003 -#define EGL_BAD_ATTRIBUTE 0x3004 -#define EGL_BAD_CONFIG 0x3005 -#define EGL_BAD_CONTEXT 0x3006 -#define EGL_BAD_CURRENT_SURFACE 0x3007 -#define EGL_BAD_DISPLAY 0x3008 -#define EGL_BAD_MATCH 0x3009 -#define EGL_BAD_NATIVE_PIXMAP 0x300A -#define EGL_BAD_NATIVE_WINDOW 0x300B -#define EGL_BAD_PARAMETER 0x300C -#define EGL_BAD_SURFACE 0x300D -#define EGL_CONTEXT_LOST 0x300E - -/* Config attributes */ -#define EGL_BUFFER_SIZE 0x3020 -#define EGL_ALPHA_SIZE 0x3021 -#define EGL_BLUE_SIZE 0x3022 -#define EGL_GREEN_SIZE 0x3023 -#define EGL_RED_SIZE 0x3024 -#define EGL_DEPTH_SIZE 0x3025 -#define EGL_STENCIL_SIZE 0x3026 -#define EGL_CONFIG_CAVEAT 0x3027 -#define EGL_CONFIG_ID 0x3028 -#define EGL_LEVEL 0x3029 -#define EGL_MAX_PBUFFER_HEIGHT 0x302A -#define EGL_MAX_PBUFFER_PIXELS 0x302B -#define EGL_MAX_PBUFFER_WIDTH 0x302C -#define EGL_NATIVE_RENDERABLE 0x302D -#define EGL_NATIVE_VISUAL_ID 0x302E -#define EGL_NATIVE_VISUAL_TYPE 0x302F -#define EGL_SAMPLES 0x3031 -#define EGL_SAMPLE_BUFFERS 0x3032 -#define EGL_SURFACE_TYPE 0x3033 -#define EGL_TRANSPARENT_TYPE 0x3034 -#define EGL_TRANSPARENT_BLUE_VALUE 0x3035 -#define EGL_TRANSPARENT_GREEN_VALUE 0x3036 -#define EGL_TRANSPARENT_RED_VALUE 0x3037 -#define EGL_NONE 0x3038 -#define EGL_BIND_TO_TEXTURE_RGB 0x3039 -#define EGL_BIND_TO_TEXTURE_RGBA 0x303A -#define EGL_MIN_SWAP_INTERVAL 0x303B -#define EGL_MAX_SWAP_INTERVAL 0x303C -#define EGL_LUMINANCE_SIZE 0x303D -#define EGL_ALPHA_MASK_SIZE 0x303E -#define EGL_COLOR_BUFFER_TYPE 0x303F -#define EGL_RENDERABLE_TYPE 0x3040 - -/* Config values */ -#define EGL_DONT_CARE ((EGLint)-1) - -#define EGL_SLOW_CONFIG 0x3050 -#define EGL_NON_CONFORMANT_CONFIG 0x3051 -#define EGL_TRANSPARENT_RGB 0x3052 -#define EGL_NO_TEXTURE 0x305C -#define EGL_TEXTURE_RGB 0x305D -#define EGL_TEXTURE_RGBA 0x305E -#define EGL_TEXTURE_2D 0x305F -#define EGL_RGB_BUFFER 0x308E -#define EGL_LUMINANCE_BUFFER 0x308F - -/* Config attribute mask bits */ -#define EGL_PBUFFER_BIT 0x01 -#define EGL_PIXMAP_BIT 0x02 -#define EGL_WINDOW_BIT 0x04 -#define EGL_OPENGL_ES_BIT 0x01 -#define EGL_OPENVG_BIT 0x02 - -/* String names */ -#define EGL_VENDOR 0x3053 -#define EGL_VERSION 0x3054 -#define EGL_EXTENSIONS 0x3055 -#define EGL_CLIENT_APIS 0x308D - -/* Surface attributes */ -#define EGL_HEIGHT 0x3056 -#define EGL_WIDTH 0x3057 -#define EGL_LARGEST_PBUFFER 0x3058 -#define EGL_TEXTURE_FORMAT 0x3080 -#define EGL_TEXTURE_TARGET 0x3081 -#define EGL_MIPMAP_TEXTURE 0x3082 -#define EGL_MIPMAP_LEVEL 0x3083 -#define EGL_RENDER_BUFFER 0x3086 -#define EGL_COLORSPACE 0x3087 -#define EGL_ALPHA_FORMAT 0x3088 -#define EGL_HORIZONTAL_RESOLUTION 0x3090 -#define EGL_VERTICAL_RESOLUTION 0x3091 -#define EGL_PIXEL_ASPECT_RATIO 0x3092 -#define EGL_SWAP_BEHAVIOR 0x3093 - -#define EGL_BACK_BUFFER 0x3084 -#define EGL_SINGLE_BUFFER 0x3085 - -#define EGL_DISPLAY_SCALING 10000 - -#define EGL_UNKNOWN ((EGLint)-1) - -/* Back buffer swap behaviors */ -#define EGL_BUFFER_PRESERVED 0x3094 -#define EGL_BUFFER_DESTROYED 0x3095 - -/* CreatePbufferFromClientBuffer buffer types */ -#define EGL_OPENVG_IMAGE 0x3096 - -/* QueryContext targets */ -#define EGL_CONTEXT_CLIENT_TYPE 0x3097 - -/* BindAPI/QueryAPI targets */ -#define EGL_OPENGL_ES_API 0x30A0 -#define EGL_OPENVG_API 0x30A1 - -/* WaitNative engines */ -#define EGL_CORE_NATIVE_ENGINE 0x305B - -/* Current surfaces */ -#define EGL_DRAW 0x3059 -#define EGL_READ 0x305A - - -EGLDisplay eglGetDisplay(NativeDisplayType display); -EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor); -EGLBoolean eglTerminate(EGLDisplay dpy); - -EGLBoolean eglGetConfigs( EGLDisplay dpy, - EGLConfig *configs, - EGLint config_size, EGLint *num_config); - -EGLBoolean eglChooseConfig( EGLDisplay dpy, const EGLint *attrib_list, - EGLConfig *configs, EGLint config_size, - EGLint *num_config); - -EGLBoolean eglGetConfigAttrib( EGLDisplay dpy, EGLConfig config, - EGLint attribute, EGLint *value); - -EGLSurface eglCreateWindowSurface( EGLDisplay dpy, EGLConfig config, - NativeWindowType window, - const EGLint *attrib_list); - -EGLSurface eglCreatePixmapSurface( EGLDisplay dpy, EGLConfig config, - NativePixmapType pixmap, - const EGLint *attrib_list); - -EGLSurface eglCreatePbufferSurface( EGLDisplay dpy, EGLConfig config, - const EGLint *attrib_list); - -EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface); - -EGLBoolean eglQuerySurface( EGLDisplay dpy, EGLSurface surface, - EGLint attribute, EGLint *value); - -EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config, - EGLContext share_list, const EGLint *attrib_list); - -EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx); - -EGLBoolean eglMakeCurrent( EGLDisplay dpy, EGLSurface draw, - EGLSurface read, EGLContext ctx); - -EGLContext eglGetCurrentContext(void); -EGLSurface eglGetCurrentSurface(EGLint readdraw); -EGLDisplay eglGetCurrentDisplay(void); -EGLBoolean eglQueryContext( EGLDisplay dpy, EGLContext ctx, - EGLint attribute, EGLint *value); - -EGLBoolean eglWaitGL(void); -EGLBoolean eglWaitNative(EGLint engine); -EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw); -EGLBoolean eglCopyBuffers( EGLDisplay dpy, EGLSurface surface, - NativePixmapType target); - -EGLint eglGetError(void); -const char* eglQueryString(EGLDisplay dpy, EGLint name); -void (*eglGetProcAddress (const char *procname))(); - -/* ---------------------------------------------------------------------------- - * EGL 1.1 - * ---------------------------------------------------------------------------- - */ - -EGLBoolean eglSurfaceAttrib( - EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value); -EGLBoolean eglBindTexImage( - EGLDisplay dpy, EGLSurface surface, EGLint buffer); -EGLBoolean eglReleaseTexImage( - EGLDisplay dpy, EGLSurface surface, EGLint buffer); - -EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval); - -/* ---------------------------------------------------------------------------- - * EGL 1.2 - * ---------------------------------------------------------------------------- - */ - -EGLBoolean eglBindAPI(EGLenum api); -EGLenum eglQueryAPI(void); -EGLBoolean eglWaitClient(void); -EGLBoolean eglReleaseThread(void); -EGLSurface eglCreatePbufferFromClientBuffer( - EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, - EGLConfig config, const EGLint *attrib_list); - -/* ---------------------------------------------------------------------------- - * Android extentions - * ---------------------------------------------------------------------------- - */ - -EGLBoolean eglSwapRectangleANDROID(EGLDisplay dpy, EGLSurface draw, - EGLint l, EGLint t, EGLint w, EGLint h); - -EGLBoolean eglCopyFrontToBackANDROID(EGLDisplay dpy, - EGLSurface surface, - EGLint l, EGLint t, EGLint w, EGLint h); - -const char* eglQueryStringConfigANDROID( - EGLDisplay dpy, EGLConfig config, EGLint name); - -void* eglGetRenderBufferAddressANDROID(EGLDisplay dpy, EGLSurface surface); - -EGLBoolean eglCopyBitsANDROID(EGLDisplay dpy, - NativeWindowType draw, EGLint x, EGLint y, - NativeWindowType read, - EGLint crop_x, EGLint crop_y, EGLint crop_w, EGLint crop_h, - EGLint flags); - - -#ifdef __cplusplus -} -#endif - - -#endif /*ANDROID_EGL_H*/ diff --git a/include/GLES/gl.h b/include/GLES/gl.h deleted file mode 100644 index 50b6ac43f88b685f8ab0da9e92891bc7532792c0..0000000000000000000000000000000000000000 --- a/include/GLES/gl.h +++ /dev/null @@ -1,639 +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. - */ - -#ifndef __gl_h_ -#define __gl_h_ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/*****************************************************************************/ - -typedef int8_t GLbyte; // b -typedef int16_t GLshort; // s -typedef int32_t GLint; // i -typedef ssize_t GLsizei; // i -typedef int32_t GLfixed; // x -typedef int32_t GLclampx; // x -typedef float GLfloat; // f -typedef float GLclampf; // f -typedef uint8_t GLubyte; // ub -typedef uint8_t GLboolean; // ub -typedef uint16_t GLushort; // us -typedef uint32_t GLuint; // ui -typedef unsigned int GLenum; // ui -typedef unsigned int GLbitfield; // ui -typedef void GLvoid; -typedef intptr_t GLintptr; -typedef int GLsizeiptr; -typedef GLintptr GLintptrARB; -typedef GLsizeiptr GLsizeiptrARB; - -/*****************************************************************************/ - -#define GL_VERSION_ES_CM_1_0 1 -#define GL_VERSION_ES_CL_1_0 1 -#define GL_VERSION_ES_CM_1_1 1 -#define GL_VERSION_ES_CL_1_1 1 - -#define GL_OES_byte_coordinates 1 -#define GL_OES_fixed_point 1 -#define GL_OES_single_precision 1 -#define GL_OES_read_format 1 -#define GL_OES_compressed_paletted_texture 1 -#define GL_OES_draw_texture 1 -#define GL_OES_matrix_get 1 -#define GL_OES_query_matrix 1 -#define GL_OES_vertex_buffer_object 1 -#define GL_OES_point_size_array 1 -#define GL_OES_point_sprite 1 -#define GL_ARB_texture_non_power_of_two 1 - -/*****************************************************************************/ -/* OpenGL ES 1.0 names */ - -#define GL_FALSE 0 -#define GL_TRUE 1 - -/* begin mode */ -#define GL_POINTS 0x0000 -#define GL_LINES 0x0001 -#define GL_LINE_LOOP 0x0002 -#define GL_LINE_STRIP 0x0003 -#define GL_TRIANGLES 0x0004 -#define GL_TRIANGLE_STRIP 0x0005 -#define GL_TRIANGLE_FAN 0x0006 - -/* clear mask */ -#define GL_DEPTH_BUFFER_BIT 0x00000100 -#define GL_STENCIL_BUFFER_BIT 0x00000400 -#define GL_COLOR_BUFFER_BIT 0x00004000 - -/* enable/disable */ -#define GL_FOG 0x0B60 -#define GL_LIGHTING 0x0B50 -#define GL_TEXTURE_2D 0x0DE1 -#define GL_CULL_FACE 0x0B44 -#define GL_ALPHA_TEST 0x0BC0 -#define GL_BLEND 0x0BE2 -#define GL_COLOR_LOGIC_OP 0x0BF2 -#define GL_DITHER 0x0BD0 -#define GL_STENCIL_TEST 0x0B90 -#define GL_DEPTH_TEST 0x0B71 -#define GL_POINT_SMOOTH 0x0B10 -#define GL_LINE_SMOOTH 0x0B20 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_COLOR_MATERIAL 0x0B57 -#define GL_NORMALIZE 0x0BA1 -#define GL_RESCALE_NORMAL 0x803A -#define GL_POLYGON_OFFSET_FILL 0x8037 -#define GL_VERTEX_ARRAY 0x8074 -#define GL_NORMAL_ARRAY 0x8075 -#define GL_COLOR_ARRAY 0x8076 -#define GL_TEXTURE_COORD_ARRAY 0x8078 -#define GL_MULTISAMPLE 0x809D -#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E -#define GL_SAMPLE_ALPHA_TO_ONE 0x809F -#define GL_SAMPLE_COVERAGE 0x80A0 - -/* gets */ -#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 -#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 -#define GL_ALIASED_POINT_SIZE_RANGE 0x846D -#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E -#define GL_MAX_LIGHTS 0x0D31 -#define GL_MAX_CLIP_PLANES 0x0D32 -#define GL_MAX_TEXTURE_SIZE 0x0D33 -#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 -#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 -#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 -#define GL_MAX_VIEWPORT_DIMS 0x0D3A -#define GL_MAX_ELEMENTS_VERTICES 0x80E8 -#define GL_MAX_ELEMENTS_INDICES 0x80E9 -#define GL_MAX_TEXTURE_UNITS 0x84E2 -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 -#define GL_SUBPIXEL_BITS 0x0D50 -#define GL_RED_BITS 0x0D52 -#define GL_GREEN_BITS 0x0D53 -#define GL_BLUE_BITS 0x0D54 -#define GL_ALPHA_BITS 0x0D55 -#define GL_DEPTH_BITS 0x0D56 -#define GL_STENCIL_BITS 0x0D57 - -/* clip planes */ -#define GL_CLIP_PLANE0 0x3000 -#define GL_CLIP_PLANE1 0x3001 -#define GL_CLIP_PLANE2 0x3002 -#define GL_CLIP_PLANE3 0x3003 -#define GL_CLIP_PLANE4 0x3004 -#define GL_CLIP_PLANE5 0x3005 - -/* errors */ -#define GL_NO_ERROR 0 -#define GL_INVALID_ENUM 0x0500 -#define GL_INVALID_VALUE 0x0501 -#define GL_INVALID_OPERATION 0x0502 -#define GL_STACK_OVERFLOW 0x0503 -#define GL_STACK_UNDERFLOW 0x0504 -#define GL_OUT_OF_MEMORY 0x0505 - -/* fog */ -#define GL_EXP 0x0800 -#define GL_EXP2 0x0801 -#define GL_FOG_DENSITY 0x0B62 -#define GL_FOG_START 0x0B63 -#define GL_FOG_END 0x0B64 -#define GL_FOG_MODE 0x0B65 -#define GL_FOG_COLOR 0x0B66 - -/* culling */ -#define GL_CW 0x0900 -#define GL_CCW 0x0901 - -#define GL_FRONT 0x0404 -#define GL_BACK 0x0405 -#define GL_FRONT_AND_BACK 0x0408 - -/* hints */ -#define GL_DONT_CARE 0x1100 -#define GL_FASTEST 0x1101 -#define GL_NICEST 0x1102 - -#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 -#define GL_POINT_SMOOTH_HINT 0x0C51 -#define GL_LINE_SMOOTH_HINT 0x0C52 -#define GL_POLYGON_SMOOTH_HINT 0x0C53 -#define GL_FOG_HINT 0x0C54 -#define GL_GENERATE_MIPMAP_HINT 0x8192 - -/* lights */ -#define GL_LIGHT_MODEL_AMBIENT 0x0B53 -#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 - -#define GL_AMBIENT 0x1200 -#define GL_DIFFUSE 0x1201 -#define GL_SPECULAR 0x1202 -#define GL_POSITION 0x1203 -#define GL_SPOT_DIRECTION 0x1204 -#define GL_SPOT_EXPONENT 0x1205 -#define GL_SPOT_CUTOFF 0x1206 -#define GL_CONSTANT_ATTENUATION 0x1207 -#define GL_LINEAR_ATTENUATION 0x1208 -#define GL_QUADRATIC_ATTENUATION 0x1209 - -#define GL_LIGHT0 0x4000 -#define GL_LIGHT1 0x4001 -#define GL_LIGHT2 0x4002 -#define GL_LIGHT3 0x4003 -#define GL_LIGHT4 0x4004 -#define GL_LIGHT5 0x4005 -#define GL_LIGHT6 0x4006 -#define GL_LIGHT7 0x4007 - -/* material */ -#define GL_EMISSION 0x1600 -#define GL_SHININESS 0x1601 -#define GL_AMBIENT_AND_DIFFUSE 0x1602 - -/* matrix */ -#define GL_MODELVIEW 0x1700 -#define GL_PROJECTION 0x1701 -#define GL_TEXTURE 0x1702 - -/* types */ -#define GL_BYTE 0x1400 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_SHORT 0x1402 -#define GL_UNSIGNED_SHORT 0x1403 -#define GL_FLOAT 0x1406 -#define GL_FIXED 0x140C - -/* pixel formats */ -#define GL_ALPHA 0x1906 -#define GL_RGB 0x1907 -#define GL_RGBA 0x1908 -#define GL_LUMINANCE 0x1909 -#define GL_LUMINANCE_ALPHA 0x190A - -/* pixel store */ -#define GL_UNPACK_ALIGNMENT 0x0CF5 -#define GL_PACK_ALIGNMENT 0x0D05 - -/* pixel types */ -#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 -#define GL_UNSIGNED_SHORT_5_6_5 0x8363 - -/* logic op */ -#define GL_CLEAR 0x1500 // 0 -#define GL_AND 0x1501 // s & d -#define GL_AND_REVERSE 0x1502 // s & ~d -#define GL_COPY 0x1503 // s -#define GL_AND_INVERTED 0x1504 // ~s & d -#define GL_NOOP 0x1505 // d -#define GL_XOR 0x1506 // s ^ d -#define GL_OR 0x1507 // s | d -#define GL_NOR 0x1508 // ~(s | d) -#define GL_EQUIV 0x1509 // ~(s ^ d) -#define GL_INVERT 0x150A // ~d -#define GL_OR_REVERSE 0x150B // s | ~d -#define GL_COPY_INVERTED 0x150C // ~s -#define GL_OR_INVERTED 0x150D // ~s | d -#define GL_NAND 0x150E // ~(s & d) -#define GL_SET 0x150F // 1 - -/* shade model */ -#define GL_FLAT 0x1D00 -#define GL_SMOOTH 0x1D01 - -/* strings */ -#define GL_VENDOR 0x1F00 -#define GL_RENDERER 0x1F01 -#define GL_VERSION 0x1F02 -#define GL_EXTENSIONS 0x1F03 - -/* stencil */ -#define GL_KEEP 0x1E00 -#define GL_REPLACE 0x1E01 -#define GL_INCR 0x1E02 -#define GL_DECR 0x1E03 - -/* alpha & stencil */ -#define GL_NEVER 0x0200 -#define GL_LESS 0x0201 -#define GL_EQUAL 0x0202 -#define GL_LEQUAL 0x0203 -#define GL_GREATER 0x0204 -#define GL_NOTEQUAL 0x0205 -#define GL_GEQUAL 0x0206 -#define GL_ALWAYS 0x0207 - -/* blending equation & function */ -#define GL_ZERO 0 // SD -#define GL_ONE 1 // SD -#define GL_SRC_COLOR 0x0300 // D -#define GL_ONE_MINUS_SRC_COLOR 0x0301 // D -#define GL_SRC_ALPHA 0x0302 // SD -#define GL_ONE_MINUS_SRC_ALPHA 0x0303 // SD -#define GL_DST_ALPHA 0x0304 // SD -#define GL_ONE_MINUS_DST_ALPHA 0x0305 // SD -#define GL_DST_COLOR 0x0306 // S -#define GL_ONE_MINUS_DST_COLOR 0x0307 // S -#define GL_SRC_ALPHA_SATURATE 0x0308 // S - -/* Texture parameter name */ -#define GL_TEXTURE_MIN_FILTER 0x2801 -#define GL_TEXTURE_MAG_FILTER 0x2800 -#define GL_TEXTURE_WRAP_S 0x2802 -#define GL_TEXTURE_WRAP_T 0x2803 -#define GL_GENERATE_MIPMAP 0x8191 -#define GL_TEXTURE_CROP_RECT_OES 0x8B9D - -/* Texture Filter */ -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 - -/* Texture Wrap Mode */ -#define GL_CLAMP 0x2900 -#define GL_REPEAT 0x2901 -#define GL_CLAMP_TO_EDGE 0x812F - -/* Texture Env Mode */ -#define GL_REPLACE 0x1E01 -#define GL_MODULATE 0x2100 -#define GL_DECAL 0x2101 -#define GL_ADD 0x0104 - -/* Texture Env Parameter */ -#define GL_TEXTURE_ENV_MODE 0x2200 -#define GL_TEXTURE_ENV_COLOR 0x2201 - -/* Texture Env Target */ -#define GL_TEXTURE_ENV 0x2300 - -/* TMUs */ -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE3 0x84C3 -#define GL_TEXTURE4 0x84C4 -#define GL_TEXTURE5 0x84C5 -#define GL_TEXTURE6 0x84C6 -#define GL_TEXTURE7 0x84C7 -#define GL_TEXTURE8 0x84C8 -#define GL_TEXTURE9 0x84C9 -#define GL_TEXTURE10 0x84CA -#define GL_TEXTURE11 0x84CB -#define GL_TEXTURE12 0x84CC -#define GL_TEXTURE13 0x84CD -#define GL_TEXTURE14 0x84CE -#define GL_TEXTURE15 0x84CF -#define GL_TEXTURE16 0x84D0 -#define GL_TEXTURE17 0x84D1 -#define GL_TEXTURE18 0x84D2 -#define GL_TEXTURE19 0x84D3 -#define GL_TEXTURE20 0x84D4 -#define GL_TEXTURE21 0x84D5 -#define GL_TEXTURE22 0x84D6 -#define GL_TEXTURE23 0x84D7 -#define GL_TEXTURE24 0x84D8 -#define GL_TEXTURE25 0x84D9 -#define GL_TEXTURE26 0x84DA -#define GL_TEXTURE27 0x84DB -#define GL_TEXTURE28 0x84DC -#define GL_TEXTURE29 0x84DD -#define GL_TEXTURE30 0x84DE -#define GL_TEXTURE31 0x84DF - -/*****************************************************************************/ -/* OpenGL ES 1.1 additions */ - -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 - -#define GL_STATIC_DRAW 0x88E4 -#define GL_DYNAMIC_DRAW 0x88E8 - -#define GL_BUFFER_SIZE 0x8764 -#define GL_BUFFER_USAGE 0x8765 - -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 -#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 -#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 -#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A - -/*****************************************************************************/ -/* Required extensions */ - -#define GL_PALETTE4_RGB8_OES 0x8B90 -#define GL_PALETTE4_RGBA8_OES 0x8B91 -#define GL_PALETTE4_R5_G6_B5_OES 0x8B92 -#define GL_PALETTE4_RGBA4_OES 0x8B93 -#define GL_PALETTE4_RGB5_A1_OES 0x8B94 -#define GL_PALETTE8_RGB8_OES 0x8B95 -#define GL_PALETTE8_RGBA8_OES 0x8B96 -#define GL_PALETTE8_R5_G6_B5_OES 0x8B97 -#define GL_PALETTE8_RGBA4_OES 0x8B98 -#define GL_PALETTE8_RGB5_A1_OES 0x8B99 - -#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A -#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B - -#define GL_POINT_SPRITE_OES 0x8861 -#define GL_COORD_REPLACE_OES 0x8862 - -#define GL_POINT_SIZE_ARRAY_OES 0x8B9C -#define GL_POINT_SIZE_ARRAY_TYPE_OES 0x898A -#define GL_POINT_SIZE_ARRAY_STRIDE_OES 0x898B -#define GL_POINT_SIZE_ARRAY_POINTER_OES 0x898C -#define GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES 0x8B9F - -/*****************************************************************************/ -/* Extensions */ - -#define GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES 0x898D -#define GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES 0x898E -#define GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES 0x898F - -#define GL_DIRECT_TEXTURE_2D_QUALCOMM 0x7E80 - - - - -/*****************************************************************************/ -/* OpenGL ES 1.0 functions */ - -void glActiveTexture(GLenum texture); -void glAlphaFunc(GLenum func, GLclampf ref); -void glAlphaFuncx(GLenum func, GLclampx ref); -void glBindTexture(GLenum target, GLuint texture); -void glBlendFunc(GLenum sfactor, GLenum dfactor); -void glClear(GLbitfield mask); -void glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); -void glClearColorx(GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha); -void glClearDepthf(GLclampf depth); -void glClearDepthx(GLclampx depth); -void glClearStencil(GLint s); -void glClientActiveTexture(GLenum texture); -void glColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -void glColor4x(GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); -void glColorMask(GLboolean r, GLboolean g, GLboolean b, GLboolean a); -void glColorPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr); -void glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, - GLsizei width, GLsizei height, GLint border, - GLsizei imageSize, const GLvoid *data); -void glCompressedTexSubImage2D( GLenum target, GLint level, GLint xoffset, - GLint yoffset, GLsizei width, GLsizei height, - GLenum format, GLsizei imageSize, - const GLvoid *data); -void glCopyTexImage2D( GLenum target, GLint level, GLenum internalformat, - GLint x, GLint y, GLsizei width, GLsizei height, - GLint border); -void glCopyTexSubImage2D( GLenum target, GLint level, GLint xoffset, - GLint yoffset, GLint x, GLint y, GLsizei width, - GLsizei height); -void glCullFace(GLenum mode); -void glDeleteTextures(GLsizei n, const GLuint *textures); -void glDepthFunc(GLenum func); -void glDepthMask(GLboolean flag); -void glDepthRangef(GLclampf zNear, GLclampf zFar); -void glDepthRangex(GLclampx zNear, GLclampx zFar); -void glDisable(GLenum cap); -void glDisableClientState(GLenum array); -void glDrawArrays(GLenum mode, GLint first, GLsizei count); -void glDrawElements(GLenum mode, GLsizei count, - GLenum type, const GLvoid *indices); -void glEnable(GLenum cap); -void glEnableClientState(GLenum array); -void glFinish(void); -void glFlush(void); -void glFogf(GLenum pname, GLfloat param); -void glFogfv(GLenum pname, const GLfloat *params); -void glFogx(GLenum pname, GLfixed param); -void glFogxv(GLenum pname, const GLfixed *params); -void glFrontFace(GLenum mode); -void glFrustumf(GLfloat left, GLfloat right, - GLfloat bottom, GLfloat top, - GLfloat zNear, GLfloat zFar); -void glFrustumx(GLfixed left, GLfixed right, - GLfixed bottom, GLfixed top, - GLfixed zNear, GLfixed zFar); -void glGenTextures(GLsizei n, GLuint *textures); -GLenum glGetError(void); -void glGetIntegerv(GLenum pname, GLint *params); -const GLubyte * glGetString(GLenum name); -void glHint(GLenum target, GLenum mode); -void glLightModelf(GLenum pname, GLfloat param); -void glLightModelfv(GLenum pname, const GLfloat *params); -void glLightModelx(GLenum pname, GLfixed param); -void glLightModelxv(GLenum pname, const GLfixed *params); -void glLightf(GLenum light, GLenum pname, GLfloat param); -void glLightfv(GLenum light, GLenum pname, const GLfloat *params); -void glLightx(GLenum light, GLenum pname, GLfixed param); -void glLightxv(GLenum light, GLenum pname, const GLfixed *params); -void glLineWidth(GLfloat width); -void glLineWidthx(GLfixed width); -void glLoadIdentity(void); -void glLoadMatrixf(const GLfloat *m); -void glLoadMatrixx(const GLfixed *m); -void glLogicOp(GLenum opcode); -void glMaterialf(GLenum face, GLenum pname, GLfloat param); -void glMaterialfv(GLenum face, GLenum pname, const GLfloat *params); -void glMaterialx(GLenum face, GLenum pname, GLfixed param); -void glMaterialxv(GLenum face, GLenum pname, const GLfixed *params); -void glMatrixMode(GLenum mode); -void glMultMatrixf(const GLfloat *m); -void glMultMatrixx(const GLfixed *m); -void glMultiTexCoord4f(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); -void glMultiTexCoord4x(GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q); -void glNormal3f(GLfloat nx, GLfloat ny, GLfloat nz); -void glNormal3x(GLfixed nx, GLfixed ny, GLfixed nz); -void glNormalPointer(GLenum type, GLsizei stride, const GLvoid *pointer); -void glOrthof( GLfloat left, GLfloat right, - GLfloat bottom, GLfloat top, - GLfloat zNear, GLfloat zFar); -void glOrthox( GLfixed left, GLfixed right, - GLfixed bottom, GLfixed top, - GLfixed zNear, GLfixed zFar); -void glPixelStorei(GLenum pname, GLint param); -void glPointSize(GLfloat size); -void glPointSizex(GLfixed size); -void glPolygonOffset(GLfloat factor, GLfloat units); -void glPolygonOffsetx(GLfixed factor, GLfixed units); -void glPopMatrix(void); -void glPushMatrix(void); -void glReadPixels( GLint x, GLint y, GLsizei width, GLsizei height, - GLenum format, GLenum type, GLvoid *pixels); -void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); -void glRotatex(GLfixed angle, GLfixed x, GLfixed y, GLfixed z); -void glSampleCoverage(GLclampf value, GLboolean invert); -void glSampleCoveragex(GLclampx value, GLboolean invert); -void glScalef(GLfloat x, GLfloat y, GLfloat z); -void glScalex(GLfixed x, GLfixed y, GLfixed z); -void glScissor(GLint x, GLint y, GLsizei width, GLsizei height); -void glShadeModel(GLenum mode); -void glStencilFunc(GLenum func, GLint ref, GLuint mask); -void glStencilMask(GLuint mask); -void glStencilOp(GLenum fail, GLenum zfail, GLenum zpass); -void glTexCoordPointer( GLint size, GLenum type, - GLsizei stride, const GLvoid *pointer); -void glTexEnvf(GLenum target, GLenum pname, GLfloat param); -void glTexEnvfv(GLenum target, GLenum pname, const GLfloat *params); -void glTexEnvx(GLenum target, GLenum pname, GLfixed param); -void glTexEnvxv(GLenum target, GLenum pname, const GLfixed *params); -void glTexImage2D( GLenum target, GLint level, GLenum internalformat, - GLsizei width, GLsizei height, GLint border, GLenum format, - GLenum type, const GLvoid *pixels); -void glTexParameterf(GLenum target, GLenum pname, GLfloat param); -void glTexParameterx(GLenum target, GLenum pname, GLfixed param); -void glTexSubImage2D( GLenum target, GLint level, GLint xoffset, - GLint yoffset, GLsizei width, GLsizei height, - GLenum format, GLenum type, const GLvoid *pixels); -void glTranslatef(GLfloat x, GLfloat y, GLfloat z); -void glTranslatex(GLfixed x, GLfixed y, GLfixed z); -void glVertexPointer( GLint size, GLenum type, - GLsizei stride, const GLvoid *pointer); -void glViewport(GLint x, GLint y, GLsizei width, GLsizei height); - -/*****************************************************************************/ -/* OpenGL ES 1.1 functions */ - -void glClipPlanef(GLenum plane, const GLfloat* equation); -void glClipPlanex(GLenum plane, const GLfixed* equation); - -void glBindBuffer(GLenum target, GLuint buffer); -void glBufferData(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage); -void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data); -void glDeleteBuffers(GLsizei n, const GLuint* buffers); -void glGenBuffers(GLsizei n, GLuint* buffers); - -void glGetBooleanv(GLenum pname, GLboolean *params); -void glGetFixedv(GLenum pname, GLfixed *params); -void glGetFloatv(GLenum pname, GLfloat *params); -void glGetPointerv(GLenum pname, void **params); -void glGetBufferParameteriv(GLenum target, GLenum pname, GLint *params); -void glGetClipPlanef(GLenum pname, GLfloat eqn[4]); -void glGetClipPlanex(GLenum pname, GLfixed eqn[4]); -void glGetLightxv(GLenum light, GLenum pname, GLfixed *params); -void glGetLightfv(GLenum light, GLenum pname, GLfloat *params); -void glGetMaterialxv(GLenum face, GLenum pname, GLfixed *params); -void glGetMaterialfv(GLenum face, GLenum pname, GLfloat *params); -void glGetTexEnvfv(GLenum env, GLenum pname, GLfloat *params); -void glGetTexEnviv(GLenum env, GLenum pname, GLint *params); -void glGetTexEnvxv(GLenum env, GLenum pname, GLfixed *params); -void glGetTexParameterfv(GLenum target, GLenum pname, GLfloat *params); -void glGetTexParameteriv(GLenum target, GLenum pname, GLint *params); -void glGetTexParameterxv(GLenum target, GLenum pname, GLfixed *params); -GLboolean glIsBuffer(GLuint buffer); -GLboolean glIsEnabled(GLenum cap); -GLboolean glIsTexture(GLuint texture); -void glPointParameterf(GLenum pname, GLfloat param); -void glPointParameterfv(GLenum pname, const GLfloat *params); -void glPointParameterx(GLenum pname, GLfixed param); -void glPointParameterxv(GLenum pname, const GLfixed *params); -void glColor4ub(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); -void glTexEnvi(GLenum target, GLenum pname, GLint param); -void glTexEnviv(GLenum target, GLenum pname, const GLint *params); -void glTexParameterfv(GLenum target, GLenum pname, const GLfloat *params); -void glTexParameteriv(GLenum target, GLenum pname, const GLint *params); -void glTexParameteri(GLenum target, GLenum pname, GLint param); -void glTexParameterxv(GLenum target, GLenum pname, const GLfixed *params); - -/*****************************************************************************/ -/* Required extensions functions */ - -void glPointSizePointerOES(GLenum type, GLsizei stride, const GLvoid *pointer); - - -/*****************************************************************************/ -/* Extensions functions */ - -void glDrawTexsOES(GLshort x , GLshort y, GLshort z, GLshort w, GLshort h); -void glDrawTexiOES(GLint x, GLint y, GLint z, GLint w, GLint h); -void glDrawTexfOES(GLfloat x, GLfloat y, GLfloat z, GLfloat w, GLfloat h); -void glDrawTexxOES(GLfixed x, GLfixed y, GLfixed z, GLfixed w, GLfixed h); -void glDrawTexsvOES(const GLshort* coords); -void glDrawTexivOES(const GLint* coords); -void glDrawTexfvOES(const GLfloat* coords); -void glDrawTexxvOES(const GLfixed* coords); -GLbitfield glQueryMatrixxOES(GLfixed* mantissa, GLint* exponent); - -/* called by dalvik */ -void glColorPointerBounds(GLint size, GLenum type, GLsizei stride, - const GLvoid *ptr, GLsizei count); -void glNormalPointerBounds(GLenum type, GLsizei stride, - const GLvoid *pointer, GLsizei count); -void glTexCoordPointerBounds(GLint size, GLenum type, - GLsizei stride, const GLvoid *pointer, GLsizei count); -void glVertexPointerBounds(GLint size, GLenum type, - GLsizei stride, const GLvoid *pointer, GLsizei count); - -#ifdef __cplusplus -} -#endif - -#endif /* __gl_h_ */ diff --git a/include/media/AudioRecord.h b/include/media/AudioRecord.h index dd585c9da5644bf84bbf0878469d4b924f91b4c5..ff6485536cfea6e0f61cfcd8a2537d85bb08dc13 100644 --- a/include/media/AudioRecord.h +++ b/include/media/AudioRecord.h @@ -125,7 +125,8 @@ public: * channelCount: Number of PCM channels (e.g 2 for stereo). * frameCount: Total size of track PCM buffer in frames. This defines the * latency of the track. - * flags: Reserved for future use. + * flags: A bitmask of acoustic values from enum record_flags. It enables + * AGC, NS, and IIR. * cbf: Callback function. If not null, this function is called periodically * to provide new PCM data. * notificationFrames: The callback function is called each time notificationFrames PCM @@ -133,6 +134,12 @@ public: * user Context for use by the callback receiver. */ + enum record_flags { + RECORD_AGC_ENABLE = AudioSystem::AGC_ENABLE, + RECORD_NS_ENABLE = AudioSystem::NS_ENABLE, + RECORD_IIR_ENABLE = AudioSystem::TX_IIR_ENABLE + }; + AudioRecord(int streamType, uint32_t sampleRate = 0, int format = 0, diff --git a/include/media/AudioSystem.h b/include/media/AudioSystem.h index 77676bf464cff351f6ca7fa63c93c0faf95b3298..77c90ba7fc1fef4d31d6d29d9cb2e2cb0e398f4f 100644 --- a/include/media/AudioSystem.h +++ b/include/media/AudioSystem.h @@ -29,8 +29,27 @@ class AudioSystem { public: + enum stream_type { + DEFAULT =-1, + VOICE_CALL = 0, + SYSTEM = 1, + RING = 2, + MUSIC = 3, + ALARM = 4, + NOTIFICATION = 5, + BLUETOOTH_SCO = 6, + NUM_STREAM_TYPES + }; + + enum audio_output_type { + AUDIO_OUTPUT_DEFAULT =-1, + AUDIO_OUTPUT_HARDWARE = 0, + AUDIO_OUTPUT_A2DP = 1, + NUM_AUDIO_OUTPUT_TYPES + }; + enum audio_format { - DEFAULT = 0, + FORMAT_DEFAULT = 0, PCM_16_BIT, PCM_8_BIT, INVALID_FORMAT @@ -51,7 +70,16 @@ public: ROUTE_BLUETOOTH_SCO = (1 << 2), ROUTE_HEADSET = (1 << 3), ROUTE_BLUETOOTH_A2DP = (1 << 4), - ROUTE_ALL = 0xFFFFFFFF + ROUTE_ALL = -1UL, + }; + + enum audio_in_acoustics { + AGC_ENABLE = 0x0001, + AGC_DISABLE = 0, + NS_ENABLE = 0x0002, + NS_DISABLE = 0, + TX_IIR_ENABLE = 0x0004, + TX_DISABLE = 0 }; /* These are static methods to control the system-wide AudioFlinger @@ -96,33 +124,52 @@ public: static float linearToLog(int volume); static int logToLinear(float volume); - static status_t getOutputSamplingRate(int* samplingRate); - static status_t getOutputFrameCount(int* frameCount); - static status_t getOutputLatency(uint32_t* latency); + static status_t getOutputSamplingRate(int* samplingRate, int stream = DEFAULT); + static status_t getOutputFrameCount(int* frameCount, int stream = DEFAULT); + static status_t getOutputLatency(uint32_t* latency, int stream = DEFAULT); + + static bool routedToA2dpOutput(int streamType); + + static status_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount, + size_t* buffSize); // ---------------------------------------------------------------------------- private: - class DeathNotifier: public IBinder::DeathRecipient + class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient { public: - DeathNotifier() { + AudioFlingerClient() { } + // DeathRecipient virtual void binderDied(const wp& who); + + // IAudioFlingerClient + virtual void a2dpEnabledChanged(bool enabled); + }; + static int getOutput(int streamType); - static sp gDeathNotifier; + static sp gAudioFlingerClient; - friend class DeathNotifier; + friend class AudioFlingerClient; static Mutex gLock; static sp gAudioFlinger; static audio_error_callback gAudioErrorCallback; - static int gOutSamplingRate; - static int gOutFrameCount; - static uint32_t gOutLatency; + static int gOutSamplingRate[NUM_AUDIO_OUTPUT_TYPES]; + static int gOutFrameCount[NUM_AUDIO_OUTPUT_TYPES]; + static uint32_t gOutLatency[NUM_AUDIO_OUTPUT_TYPES]; + static bool gA2dpEnabled; + + static size_t gInBuffSize; + // previous parameters for recording buffer size queries + static uint32_t gPrevInSamplingRate; + static int gPrevInFormat; + static int gPrevInChannelCount; + }; }; // namespace android diff --git a/include/media/AudioTrack.h b/include/media/AudioTrack.h index fd62daad8fc2a86bceddc3e73cb4756241981ebb..659f5f8aa335e85296ee5a49d7f6e3732cf62922 100644 --- a/include/media/AudioTrack.h +++ b/include/media/AudioTrack.h @@ -42,18 +42,6 @@ class audio_track_cblk_t; class AudioTrack { public: - - enum stream_type { - DEFAULT =-1, - VOICE_CALL = 0, - SYSTEM = 1, - RING = 2, - MUSIC = 3, - ALARM = 4, - NOTIFICATION = 5, - NUM_STREAM_TYPES - }; - enum channel_index { MONO = 0, LEFT = 0, @@ -127,7 +115,7 @@ public: * Parameters: * * streamType: Select the type of audio stream this track is attached to - * (e.g. AudioTrack::MUSIC). + * (e.g. AudioSystem::MUSIC). * sampleRate: Track sampling rate in Hz. * format: PCM sample format (e.g AudioSystem::PCM_16_BIT for signed * 16 bits per sample). diff --git a/include/media/IAudioFlinger.h b/include/media/IAudioFlinger.h index 69703b2b003af785ec9367c4f804a53032384a96..6f13fe0b52c25c300564ec78dd9bc7e21bb2073c 100644 --- a/include/media/IAudioFlinger.h +++ b/include/media/IAudioFlinger.h @@ -26,6 +26,7 @@ #include #include #include +#include namespace android { @@ -64,11 +65,11 @@ public: /* query the audio hardware state. This state never changes, * and therefore can be cached. */ - virtual uint32_t sampleRate() const = 0; - virtual int channelCount() const = 0; - virtual int format() const = 0; - virtual size_t frameCount() const = 0; - virtual uint32_t latency() const = 0; + virtual uint32_t sampleRate(int output) const = 0; + virtual int channelCount(int output) const = 0; + virtual int format(int output) const = 0; + virtual size_t frameCount(int output) const = 0; + virtual uint32_t latency(int output) const = 0; /* set/get the audio hardware state. This will probably be used by * the preference panel, mostly. @@ -107,6 +108,18 @@ public: // Temporary interface, do not use // TODO: Replace with a more generic key:value get/set mechanism virtual status_t setParameter(const char* key, const char* value) = 0; + + // register a current process for audio output change notifications + virtual void registerClient(const sp& client) = 0; + + // retrieve the audio recording buffer size + virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount) = 0; + + // force AudioFlinger thread out of standby + virtual void wakeUp() = 0; + + // is A2DP output enabled + virtual bool isA2dpEnabled() const = 0; }; diff --git a/include/media/IAudioFlingerClient.h b/include/media/IAudioFlingerClient.h new file mode 100644 index 0000000000000000000000000000000000000000..c3deb0b4e8f28b05f3f5eb9e75715d3dea0d841d --- /dev/null +++ b/include/media/IAudioFlingerClient.h @@ -0,0 +1,55 @@ +/* + * 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 ANDROID_IAUDIOFLINGERCLIENT_H +#define ANDROID_IAUDIOFLINGERCLIENT_H + + +#include +#include + + +namespace android { + +// ---------------------------------------------------------------------------- + +class IAudioFlingerClient : public IInterface +{ +public: + DECLARE_META_INTERFACE(AudioFlingerClient); + + // Notifies a change of audio output from/to hardware to/from A2DP. + virtual void a2dpEnabledChanged(bool enabled) = 0; + +}; + + +// ---------------------------------------------------------------------------- + +class BnAudioFlingerClient : public BnInterface +{ +public: + virtual status_t onTransact( uint32_t code, + const Parcel& data, + Parcel* reply, + uint32_t flags = 0); +}; + +// ---------------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_IAUDIOFLINGERCLIENT_H diff --git a/include/media/IMediaRecorder.h b/include/media/IMediaRecorder.h index 49e45d138ffdcd9dfef8c3682ea4d7687e4b98a1..64d3a40a30978dbec4934eb3148442d4782d8ff6 100644 --- a/include/media/IMediaRecorder.h +++ b/include/media/IMediaRecorder.h @@ -24,6 +24,7 @@ namespace android { class ISurface; class ICamera; +class IMediaPlayerClient; class IMediaRecorder: public IInterface { @@ -38,8 +39,11 @@ public: virtual status_t setVideoEncoder(int ve) = 0; virtual status_t setAudioEncoder(int ae) = 0; virtual status_t setOutputFile(const char* path) = 0; + virtual status_t setOutputFile(int fd, int64_t offset, int64_t length) = 0; virtual status_t setVideoSize(int width, int height) = 0; virtual status_t setVideoFrameRate(int frames_per_second) = 0; + virtual status_t setParameters(const String8& params) = 0; + virtual status_t setListener(const sp& listener) = 0; virtual status_t prepare() = 0; virtual status_t getMaxAmplitude(int* max) = 0; virtual status_t start() = 0; diff --git a/include/media/JetPlayer.h b/include/media/JetPlayer.h index 426817048d0d1dc041e563901e1dd48c343b91c8..16764a9192bdcd59835a88ccb94ea5fb3b3a5cac 100644 --- a/include/media/JetPlayer.h +++ b/include/media/JetPlayer.h @@ -33,9 +33,12 @@ class JetPlayer { public: - static const int JET_USERID_UPDATE = 1; - static const int JET_NUMQUEUEDSEGMENT_UPDATE = 2; - static const int JET_PAUSE_UPDATE = 3; + // to keep in sync with the JetPlayer class constants + // defined in frameworks/base/media/java/android/media/JetPlayer.java + static const int JET_EVENT = 1; + static const int JET_USERID_UPDATE = 2; + static const int JET_NUMQUEUEDSEGMENT_UPDATE = 3; + static const int JET_PAUSE_UPDATE = 4; JetPlayer(jobject javaJetPlayer, int maxTracks = 32, @@ -44,7 +47,8 @@ public: int init(); int release(); - int openFile(const char* url); + int loadFromFile(const char* url); + int loadFromFD(const int fd, const long long offset, const long long length); int closeFile(); int play(); int pause(); @@ -53,6 +57,7 @@ public: int setMuteFlags(EAS_U32 muteFlags, bool sync); int setMuteFlag(int trackNum, bool muteFlag, bool sync); int triggerClip(int clipId); + int clearQueue(); void setEventCallback(jetevent_callback callback); @@ -62,7 +67,8 @@ public: private: static int renderThread(void*); int render(); - void fireEventOnStatusChange(); + void fireUpdateOnStatusChange(); + void fireEventsFromJetQueue(); JetPlayer() {} // no default constructor void dump(); diff --git a/include/media/MediaPlayerInterface.h b/include/media/MediaPlayerInterface.h index 30e4578c42124e3a257b2ab0b8f50e39010029ce..7f0e7b3a473ed4a0518020fc5f3a6b4d46c99045 100644 --- a/include/media/MediaPlayerInterface.h +++ b/include/media/MediaPlayerInterface.h @@ -17,9 +17,6 @@ #ifndef ANDROID_MEDIAPLAYERINTERFACE_H #define ANDROID_MEDIAPLAYERINTERFACE_H -#include -#include - #ifdef __cplusplus #include @@ -74,7 +71,6 @@ public: virtual ~MediaPlayerBase() {} virtual status_t initCheck() = 0; virtual bool hardwareOutput() = 0; - virtual status_t setSigBusHandlerStructTLSKey(pthread_key_t key) { return 0; } virtual status_t setDataSource(const char *url) = 0; virtual status_t setDataSource(int fd, int64_t offset, int64_t length) = 0; virtual status_t setVideoSurface(const sp& surface) = 0; @@ -125,34 +121,6 @@ public: #endif // __cplusplus -// A thread can set the thread local variable identified by the pthread_key_t -// that was passed to the player using the setSigBusHandlerStructTLSKey() -// method to the address of the following structure. -// If 'handlesigbus' is non-NULL, the function it points to will be called, -// and if it returns 0, the signal will be assumed to have been handled, -// and no other action will be taken. If it returns non-zero, the old SIGBUS -// handler will be called. -// If 'handlesigbus is NULL, then sigbusvar must be non NULL. The system's -// SIGBUS handler will map an accessible page filled with zeroes at the -// location that caused the original fault, set the variable pointed to by -// sigbusvar to a non-zero value, and exit (which causes the operation to -// be retried, which should now succeed). -// If base and len are non zero, which is strongly recommended, they will -// be used as additional constraints on the signal handler. That is, when -// specified, the fault address must be in the range specified by base and -// len in order for handlesigbus() to be called or sigbusvar to be set. -// If the fault address is outside of the range, the old SIGBUS handler -// will be called. -struct mediasigbushandler { - int (*handlesigbus)(siginfo_t *, struct mediasigbushandler *); - int *sigbusvar; - char *base; - int len; - // these next two are free for application use - struct mediasigbushandler *next; - void *data; -}; - #endif // ANDROID_MEDIAPLAYERINTERFACE_H diff --git a/include/media/PVMediaRecorder.h b/include/media/PVMediaRecorder.h index 5fee0d6a7eadc684f6ebd0d2e8aaebacd5b12e2d..0c71932bbf59b70ffa72a4af454138e5a971eb70 100644 --- a/include/media/PVMediaRecorder.h +++ b/include/media/PVMediaRecorder.h @@ -19,6 +19,7 @@ #define ANDROID_PVMEDIARECORDER_H #include +#include namespace android { @@ -43,6 +44,9 @@ public: status_t setCamera(const sp& camera); status_t setPreviewSurface(const sp& surface); status_t setOutputFile(const char *path); + status_t setOutputFile(int fd, int64_t offset, int64_t length); + status_t setParameters(const String8& params); + status_t setListener(const sp& listener); status_t prepare(); status_t start(); status_t stop(); diff --git a/include/media/PVPlayer.h b/include/media/PVPlayer.h index 5f302ed8c4cdfcb62c6bd8e68483e2e8df2b8452..8122df60eb5dde7ef60a053fb79de48e51b47754 100644 --- a/include/media/PVPlayer.h +++ b/include/media/PVPlayer.h @@ -20,6 +20,12 @@ #include #include +#define MAX_OPENCORE_INSTANCES 25 + +#ifdef MAX_OPENCORE_INSTANCES +#include +#endif + class PlayerDriver; namespace android { @@ -31,7 +37,6 @@ public: virtual ~PVPlayer(); virtual status_t initCheck(); - virtual status_t setSigBusHandlerStructTLSKey(pthread_key_t key); virtual status_t setDataSource(const char *url); virtual status_t setDataSource(int fd, int64_t offset, int64_t length); virtual status_t setVideoSurface(const sp& surface); @@ -48,8 +53,8 @@ public: virtual status_t setLooping(int loop); virtual player_type playerType() { return PV_PLAYER; } - // make available to PlayerDriver - void sendEvent(int msg, int ext1=0, int ext2=0) { MediaPlayerBase::sendEvent(msg, ext1, ext2); } + // make available to PlayerDriver + void sendEvent(int msg, int ext1=0, int ext2=0) { MediaPlayerBase::sendEvent(msg, ext1, ext2); } private: static void do_nothing(status_t s, void *cookie, bool cancelled) { } @@ -62,10 +67,13 @@ private: char * mDataSourcePath; bool mIsDataSourceSet; sp mSurface; - void * mMemBase; - off_t mMemSize; + int mSharedFd; status_t mInit; int mDuration; + +#ifdef MAX_OPENCORE_INSTANCES + static volatile int32_t sNumInstances; +#endif }; }; // namespace android diff --git a/include/media/ToneGenerator.h b/include/media/ToneGenerator.h index 0cfdeec7309a8f1b5efdeacd5b9c26e9134ec651..ec64e4d70434749fd34bc60d4bc68a8c8227a288 100644 --- a/include/media/ToneGenerator.h +++ b/include/media/ToneGenerator.h @@ -85,8 +85,6 @@ private: TONE_RESTARTING // }; - static const unsigned int NUM_PCM_BUFFERS = 2; // Number of AudioTrack pcm buffers - static const unsigned int TONEGEN_MAX_WAVES = 3; static const unsigned int TONEGEN_MAX_SEGMENTS = 4; // Maximun number of elenemts in static const unsigned int TONEGEN_INF = 0xFFFFFFFF; // Represents infinite time duration @@ -127,7 +125,6 @@ private: const ToneDescriptor *mpNewToneDesc; // pointer to next active tone descriptor int mSamplingRate; // AudioFlinger Sampling rate - int mBufferSize; // PCM buffer size in frames AudioTrack *mpAudioTrack; // Pointer to audio track used for playback Mutex mLock; // Mutex to control concurent access to ToneGenerator object from audio callback and application API Mutex mCbkCondLock; // Mutex associated to mWaitCbkCond diff --git a/include/media/mediaplayer.h b/include/media/mediaplayer.h index 728844599768f2934e182e3fe64c7a8832eef719..58906d117377441224cbc88a07f8dc186ea4cded 100644 --- a/include/media/mediaplayer.h +++ b/include/media/mediaplayer.h @@ -34,11 +34,72 @@ enum media_event_type { MEDIA_SEEK_COMPLETE = 4, MEDIA_SET_VIDEO_SIZE = 5, MEDIA_ERROR = 100, + MEDIA_INFO = 200, }; -typedef int media_error_type; -const media_error_type MEDIA_ERROR_UNKNOWN = 1; -const media_error_type MEDIA_ERROR_SERVER_DIED = 100; +// Generic error codes for the media player framework. Errors are fatal, the +// playback must abort. +// +// Errors are communicated back to the client using the +// MediaPlayerListener::notify method defined below. +// In this situation, 'notify' is invoked with the following: +// 'msg' is set to MEDIA_ERROR. +// 'ext1' should be a value from the enum media_error_type. +// 'ext2' contains an implementation dependant error code to provide +// more details. Should default to 0 when not used. +// +// The codes are distributed as follow: +// 0xx: Reserved +// 1xx: Android Player errors. Something went wrong inside the MediaPlayer. +// 2xx: Media errors (e.g Codec not supported). There is a problem with the +// media itself. +// 3xx: Runtime errors. Some extraordinary condition arose making the playback +// impossible. +// +enum media_error_type { + // 0xx + MEDIA_ERROR_UNKNOWN = 1, + // 1xx + MEDIA_ERROR_SERVER_DIED = 100, + // 2xx + MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200, + // 3xx +}; + + +// Info and warning codes for the media player framework. These are non fatal, +// the playback is going on but there might be some user visible issues. +// +// Info and warning messages are communicated back to the client using the +// MediaPlayerListener::notify method defined below. In this situation, +// 'notify' is invoked with the following: +// 'msg' is set to MEDIA_INFO. +// 'ext1' should be a value from the enum media_info_type. +// 'ext2' contains an implementation dependant error code to provide +// more details. Should default to 0 when not used. +// +// The codes are distributed as follow: +// 0xx: Reserved +// 7xx: Android Player info/warning (e.g player lagging behind.) +// 8xx: Media info/warning (e.g media badly interleaved.) +// +enum media_info_type { + // 0xx + MEDIA_INFO_UNKNOWN = 1, + // 7xx + // The video is too complex for the decoder: it can't decode frames fast + // enough. Possibly only the audio plays fine at this stage. + MEDIA_INFO_VIDEO_TRACK_LAGGING = 700, + // 8xx + // Bad interleaving means that a media has been improperly interleaved or not + // interleaved at all, e.g has all the video samples first then all the audio + // ones. Video is playing but a lot of disk seek may be happening. + MEDIA_INFO_BAD_INTERLEAVING = 800, + // The media is not seekable (e.g live stream). + MEDIA_INFO_NOT_SEEKABLE = 801, +}; + + enum media_player_states { MEDIA_PLAYER_STATE_ERROR = 0, @@ -141,4 +202,3 @@ private: }; // namespace android #endif // ANDROID_MEDIAPLAYER_H - diff --git a/include/media/mediarecorder.h b/include/media/mediarecorder.h index a901d32ee3c96d96e3151f1ccf17eb89e8800d25..78d76219baf856d5c9d0ddcc0d6efc3f552343d0 100644 --- a/include/media/mediarecorder.h +++ b/include/media/mediarecorder.h @@ -19,6 +19,7 @@ #define ANDROID_MEDIARECORDER_H #include +#include namespace android { @@ -87,7 +88,34 @@ enum media_recorder_states { MEDIA_RECORDER_RECORDING = 1 << 4, }; -class MediaRecorder +// The "msg" code passed to the listener in notify. +enum media_recorder_event_type { + MEDIA_RECORDER_EVENT_ERROR = 1, + MEDIA_RECORDER_EVENT_INFO = 2 +}; + +enum media_recorder_error_type { + MEDIA_RECORDER_ERROR_UNKNOWN = 1 +}; + +// The codes are distributed as follow: +// 0xx: Reserved +// 8xx: General info/warning +// +enum media_recorder_info_type { + MEDIA_RECORDER_INFO_UNKNOWN = 1, + MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800 +}; + +// ---------------------------------------------------------------------------- +// ref-counted object for callbacks +class MediaRecorderListener: virtual public RefBase +{ +public: + virtual void notify(int msg, int ext1, int ext2) = 0; +}; + +class MediaRecorder : public BnMediaPlayerClient { public: MediaRecorder(); @@ -102,8 +130,11 @@ public: status_t setVideoEncoder(int ve); status_t setAudioEncoder(int ae); status_t setOutputFile(const char* path); + status_t setOutputFile(int fd, int64_t offset, int64_t length); status_t setVideoSize(int width, int height); status_t setVideoFrameRate(int frames_per_second); + status_t setParameters(const String8& params); + status_t setListener(const sp& listener); status_t prepare(); status_t getMaxAmplitude(int* max); status_t start(); @@ -112,18 +143,22 @@ public: status_t init(); status_t close(); status_t release(); + void notify(int msg, int ext1, int ext2); private: void doCleanUp(); status_t doReset(); - sp mMediaRecorder; - media_recorder_states mCurrentState; - bool mIsAudioSourceSet; - bool mIsVideoSourceSet; - bool mIsAudioEncoderSet; - bool mIsVideoEncoderSet; - bool mIsOutputFileSet; + sp mMediaRecorder; + sp mListener; + media_recorder_states mCurrentState; + bool mIsAudioSourceSet; + bool mIsVideoSourceSet; + bool mIsAudioEncoderSet; + bool mIsVideoEncoderSet; + bool mIsOutputFileSet; + Mutex mLock; + Mutex mNotifyLock; }; }; // namespace android diff --git a/include/media/thread_init.h b/include/media/thread_init.h index 2c0c1f18fd560fc42faf97111ef9bb8a25d41d30..2feac861dbfdb779e372d306d8c64f09f44ad7d7 100644 --- a/include/media/thread_init.h +++ b/include/media/thread_init.h @@ -19,7 +19,6 @@ bool InitializeForThread(); void UninitializeForThread(); -void keydestructor(void*); #endif /* THREAD_INIT_H*/ diff --git a/include/private/opengles/gl_context.h b/include/private/opengles/gl_context.h index 3056139bef9176cc8a44aaf355da8886540909f4..0c7ad462fb2ac60be2c32776b230d2dbb84a2b3c 100644 --- a/include/private/opengles/gl_context.h +++ b/include/private/opengles/gl_context.h @@ -28,6 +28,7 @@ #include #include +#include namespace android { diff --git a/include/ui/Camera.h b/include/ui/Camera.h index 44acce5dd0b6b43d6e451f8cb25ce8ff655e4da7..e593feab7899aa29c1c0267fb369b8d3ec2644e9 100644 --- a/include/ui/Camera.h +++ b/include/ui/Camera.h @@ -23,8 +23,8 @@ namespace android { /* - * A set of bit masks for specifying how the received frames from preview are - * handled before the frame callback call. + * A set of bit masks for specifying how the received preview frames are + * handled before the previewCallback() call. * * The least significant 3 bits of an "int" value are used for this purpose: * @@ -34,10 +34,18 @@ namespace android { * | |-----------> determine whether the callback is one-shot or not * |-------------> determine whether the frame is copied out or not * + * WARNING: + * When a frame is sent directly without copying, it is the frame receiver's + * responsiblity to make sure that the frame data won't get corrupted by + * subsequent preview frames filled by the camera. This flag is recommended + * only when copying out data brings significant performance price and the + * handling/processing of the received frame data is always faster than + * the preview frame rate so that data corruption won't occur. + * * For instance, * 1. 0x00 disables the callback. In this case, copy out and one shot bits * are ignored. - * 2. 0x01 enables a callback without copying out the recievied frames. A + * 2. 0x01 enables a callback without copying out the received frames. A * typical use case is the Camcorder application to avoid making costly * frame copies. * 3. 0x05 is enabling a callback with frame copied out repeatedly. A typical @@ -96,6 +104,18 @@ public: // get preview state bool previewEnabled(); + // start recording mode, must call setPreviewDisplay first + status_t startRecording(); + + // stop recording mode + void stopRecording(); + + // get recording state + bool recordingEnabled(); + + // release a recording frame + void releaseRecordingFrame(const sp& mem); + // autoFocus - status returned from callback status_t autoFocus(); @@ -111,20 +131,19 @@ public: void setShutterCallback(shutter_callback cb, void *cookie); void setRawCallback(frame_callback cb, void *cookie); void setJpegCallback(frame_callback cb, void *cookie); - - void setFrameCallback(frame_callback cb, - void *cookie, - int frame_callback_flag = FRAME_CALLBACK_FLAG_NOOP); - + void setRecordingCallback(frame_callback cb, void *cookie); + void setPreviewCallback(frame_callback cb, void *cookie, int preview_callback_flag = FRAME_CALLBACK_FLAG_NOOP); void setErrorCallback(error_callback cb, void *cookie); void setAutoFocusCallback(autofocus_callback cb, void *cookie); + // ICameraClient interface virtual void shutterCallback(); virtual void rawCallback(const sp& picture); virtual void jpegCallback(const sp& picture); - virtual void frameCallback(const sp& frame); + virtual void previewCallback(const sp& frame); virtual void errorCallback(status_t error); virtual void autoFocusCallback(bool focused); + virtual void recordingCallback(const sp& frame); sp remote(); @@ -155,8 +174,10 @@ private: void *mRawCallbackCookie; frame_callback mJpegCallback; void *mJpegCallbackCookie; - frame_callback mFrameCallback; - void *mFrameCallbackCookie; + frame_callback mPreviewCallback; + void *mPreviewCallbackCookie; + frame_callback mRecordingCallback; + void *mRecordingCallbackCookie; error_callback mErrorCallback; void *mErrorCallbackCookie; autofocus_callback mAutoFocusCallback; diff --git a/include/ui/CameraHardwareInterface.h b/include/ui/CameraHardwareInterface.h index 2bd53dde32e09c2fcce05989821f33e5da944365..73036f0fa78374478c605f7973c73af3153eedcc 100644 --- a/include/ui/CameraHardwareInterface.h +++ b/include/ui/CameraHardwareInterface.h @@ -20,12 +20,16 @@ #include #include #include +#include namespace android { /** Callback for startPreview() */ typedef void (*preview_callback)(const sp& mem, void* user); +/** Callback for startRecord() */ +typedef void (*recording_callback)(const sp& mem, void* user); + /** Callback for takePicture() */ typedef void (*shutter_callback)(void* user); @@ -83,12 +87,20 @@ public: /** Return the IMemoryHeap for the preview image heap */ virtual sp getPreviewHeap() const = 0; + /** Return the IMemoryHeap for the raw image heap */ + virtual sp getRawHeap() const = 0; + /** * Start preview mode. When a preview image is available * preview_callback is called with the user parameter. The * call back parameter may be null. */ virtual status_t startPreview(preview_callback cb, void* user) = 0; + /** + * Only used if overlays are used for camera preview. + */ + virtual bool useOverlay() {return false;} + virtual status_t setOverlay(const sp &overlay) {return BAD_VALUE;} /** * Stop a previously started preview. @@ -100,6 +112,29 @@ public: */ virtual bool previewEnabled() = 0; + /** + * Start record mode. When a record image is available recording_callback() + * is called with the user parameter. Every record frame must be released + * by calling releaseRecordingFrame(). + */ + virtual status_t startRecording(recording_callback cb, void* user) = 0; + + /** + * Stop a previously started recording. + */ + virtual void stopRecording() = 0; + + /** + * Returns true if recording is enabled. + */ + virtual bool recordingEnabled() = 0; + + /** + * Release a record frame previously returned by the recording_callback() + * passed to startRecord(). + */ + virtual void releaseRecordingFrame(const sp& mem) = 0; + /** * Start auto focus, the callback routine is called * once when focusing is complete. autoFocus() will diff --git a/include/ui/CameraParameters.h b/include/ui/CameraParameters.h index e35a0546ba09a666f8fb03ed865fb75dd7294476..9ca18068ef5909aac0261ea5a733e36b1855e6e7 100644 --- a/include/ui/CameraParameters.h +++ b/include/ui/CameraParameters.h @@ -29,6 +29,12 @@ public: CameraParameters(const String8 ¶ms) { unflatten(params); } ~CameraParameters(); + enum { + CAMERA_ORIENTATION_UNKNOWN = 0, + CAMERA_ORIENTATION_PORTRAIT = 1, + CAMERA_ORIENTATION_LANDSCAPE = 2, + }; + String8 flatten() const; void unflatten(const String8 ¶ms); @@ -57,6 +63,9 @@ public: void setPictureFormat(const char *format); const char *getPictureFormat() const; + int getOrientation() const; + void setOrientation(int orientation); + void dump() const; status_t dump(int fd, const Vector& args) const; diff --git a/include/ui/EGLDisplaySurface.h b/include/ui/EGLDisplaySurface.h index 0190e099792cc0090bab006e2b281f6fcbed350e..a8b58539d192d0b893cd33726848189db77b8853 100644 --- a/include/ui/EGLDisplaySurface.h +++ b/include/ui/EGLDisplaySurface.h @@ -27,7 +27,10 @@ #include #include +#include + struct copybit_device_t; +struct copybit_image_t; // --------------------------------------------------------------------------- namespace android { @@ -44,17 +47,17 @@ public: int32_t getPageFlipCount() const; void copyFrontToBack(const Region& copyback); + void copyFrontToImage(const copybit_image_t& dst); + void copyBackToImage(const copybit_image_t& dst); + void setSwapRectangle(int l, int t, int w, int h); + private: static void hook_incRef(NativeWindowType window); static void hook_decRef(NativeWindowType window); static uint32_t hook_swapBuffers(NativeWindowType window); - static void hook_setSwapRectangle(NativeWindowType window, int l, int t, int w, int h); - static uint32_t hook_nextBuffer(NativeWindowType window); uint32_t swapBuffers(); - uint32_t nextBuffer(); - void setSwapRectangle(int l, int t, int w, int h); status_t mapFrameBuffer(); diff --git a/include/ui/EGLNativeSurface.h b/include/ui/EGLNativeSurface.h index c303cd8d4ac87004c6bcbfc252120218bc22012f..7964e7c6bac993df8a269c25b908afb82a02e713 100644 --- a/include/ui/EGLNativeSurface.h +++ b/include/ui/EGLNativeSurface.h @@ -23,7 +23,7 @@ #include #include -#include +#include // --------------------------------------------------------------------------- namespace android { diff --git a/include/ui/EGLNativeWindowSurface.h b/include/ui/EGLNativeWindowSurface.h index 058479a2a6e4b897665755ef83b71711bb61d6f6..3494234636042202a212f2c87b61e912a920cedf 100644 --- a/include/ui/EGLNativeWindowSurface.h +++ b/include/ui/EGLNativeWindowSurface.h @@ -20,6 +20,7 @@ #include #include #include +#include // --------------------------------------------------------------------------- namespace android { @@ -33,18 +34,16 @@ public: EGLNativeWindowSurface(const sp& surface); ~EGLNativeWindowSurface(); + void setSwapRectangle(int l, int t, int w, int h); + private: static void hook_incRef(NativeWindowType window); static void hook_decRef(NativeWindowType window); static uint32_t hook_swapBuffers(NativeWindowType window); - static uint32_t hook_nextBuffer(NativeWindowType window); - static void hook_setSwapRectangle(NativeWindowType window, int l, int t, int w, int h); static void hook_connect(NativeWindowType window); static void hook_disconnect(NativeWindowType window); uint32_t swapBuffers(); - uint32_t nextBuffer(); - void setSwapRectangle(int l, int t, int w, int h); void connect(); void disconnect(); diff --git a/include/ui/EventHub.h b/include/ui/EventHub.h index 017c145bfb4c6768a6fc04b3f9d1148869b70024..3848d8c3bdc03e2ec85dd9b4d079b385c4e21d5e 100644 --- a/include/ui/EventHub.h +++ b/include/ui/EventHub.h @@ -76,6 +76,9 @@ public: DEVICE_REMOVED = 0x20000000 }; + // examine key input devices for specific framework keycode support + bool hasKeys(size_t numCodes, int32_t* keyCodes, uint8_t* outFlags); + virtual bool getEvent(int32_t* outDeviceId, int32_t* outType, int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags, int32_t* outValue, nsecs_t* outWhen); @@ -100,6 +103,7 @@ private: const String8 path; String8 name; uint32_t classes; + uint8_t* keyBitmask; KeyLayoutMap* layoutMap; String8 keylayoutFilename; device_t* next; @@ -134,8 +138,6 @@ private: #ifdef EV_SW int32_t mSwitches[SW_MAX+1]; #endif - - KeyLayoutMap * mLayoutMap; }; }; // namespace android diff --git a/include/ui/ICamera.h b/include/ui/ICamera.h index ea2fcee2ae5eecdd4b6ce22d52514438f869af33..241fb632616fad1bad7e31fc4ddb4c84a2db14e3 100644 --- a/include/ui/ICamera.h +++ b/include/ui/ICamera.h @@ -48,9 +48,9 @@ public: // pass the buffered ISurface to the camera service virtual status_t setPreviewDisplay(const sp& surface) = 0; - // set the frame callback flag to affect how the received frames from + // set the preview callback flag to affect how the received frames from // preview are handled. - virtual void setFrameCallbackFlag(int frame_callback_flag) = 0; + virtual void setPreviewCallbackFlag(int flag) = 0; // start preview mode, must call setPreviewDisplay first virtual status_t startPreview() = 0; @@ -61,6 +61,18 @@ public: // get preview state virtual bool previewEnabled() = 0; + // start recording mode + virtual status_t startRecording() = 0; + + // stop recording mode + virtual void stopRecording() = 0; + + // get recording state + virtual bool recordingEnabled() = 0; + + // release a recording frame + virtual void releaseRecordingFrame(const sp& mem) = 0; + // auto focus virtual status_t autoFocus() = 0; diff --git a/include/ui/ICameraClient.h b/include/ui/ICameraClient.h index a286b8e0a5a1725b25100c1eeaaf481976f16937..73b951cf3cc0e1e15551b173733404166827b73a 100644 --- a/include/ui/ICameraClient.h +++ b/include/ui/ICameraClient.h @@ -32,9 +32,10 @@ public: virtual void shutterCallback() = 0; virtual void rawCallback(const sp& picture) = 0; virtual void jpegCallback(const sp& picture) = 0; - virtual void frameCallback(const sp& frame) = 0; + virtual void previewCallback(const sp& frame) = 0; virtual void errorCallback(status_t error) = 0; virtual void autoFocusCallback(bool focused) = 0; + virtual void recordingCallback(const sp& frame) = 0; }; diff --git a/include/ui/ICameraService.h b/include/ui/ICameraService.h index dfd89230017d5be57ddcbfaba6d2d8560b5a1454..c652c5169a0a4257d34393fb26e31860cc1d79bf 100644 --- a/include/ui/ICameraService.h +++ b/include/ui/ICameraService.h @@ -28,7 +28,7 @@ namespace android { class ICameraService : public IInterface { -protected: +public: enum { CONNECT = IBinder::FIRST_CALL_TRANSACTION, }; diff --git a/include/ui/ISurface.h b/include/ui/ISurface.h index 9a7383cc242d62b4042154ea5023d8592e2cf264..87b320f431b88b498c97289621f7d9711128455c 100644 --- a/include/ui/ISurface.h +++ b/include/ui/ISurface.h @@ -25,6 +25,8 @@ #include #include +#include + namespace android { typedef int32_t SurfaceID; @@ -34,11 +36,48 @@ class OverlayRef; class ISurface : public IInterface { +protected: + enum { + REGISTER_BUFFERS = IBinder::FIRST_CALL_TRANSACTION, + UNREGISTER_BUFFERS, + POST_BUFFER, // one-way transaction + CREATE_OVERLAY, + }; + public: DECLARE_META_INTERFACE(Surface); - virtual status_t registerBuffers(int w, int h, int hstride, int vstride, - PixelFormat format, const sp& heap) = 0; + + class BufferHeap { + public: + enum { + /* rotate source image 90 degrees */ + ROT_90 = HAL_TRANSFORM_ROT_90, + }; + BufferHeap(); + + BufferHeap(uint32_t w, uint32_t h, + int32_t hor_stride, int32_t ver_stride, + PixelFormat format, const sp& heap); + + BufferHeap(uint32_t w, uint32_t h, + int32_t hor_stride, int32_t ver_stride, + PixelFormat format, uint32_t transform, uint32_t flags, + const sp& heap); + + ~BufferHeap(); + + uint32_t w; + uint32_t h; + int32_t hor_stride; + int32_t ver_stride; + PixelFormat format; + uint32_t transform; + uint32_t flags; + sp heap; + }; + + virtual status_t registerBuffers(const BufferHeap& buffers) = 0; virtual void postBuffer(ssize_t offset) = 0; // one-way diff --git a/include/ui/KeycodeLabels.h b/include/ui/KeycodeLabels.h index 53c118872814bc0d57c64064422f34f968f0745b..efa6d2bdd3c33e8024e76d159c7af41e8ab1e8aa 100644 --- a/include/ui/KeycodeLabels.h +++ b/include/ui/KeycodeLabels.h @@ -113,6 +113,7 @@ static const KeycodeLabel KEYCODES[] = { { "PREVIOUSSONG", 88 }, { "REWIND", 89 }, { "FORWARD", 90 }, + { "MUTE", 91 }, // NOTE: If you add a new keycode here you must also add it to: // (enum KeyCode, in this file) @@ -216,7 +217,8 @@ typedef enum KeyCode { kKeyCodeNextSong = 87, kKeyCodePreviousSong = 88, kKeyCodeRewind = 89, - kKeyCodeForward = 90 + kKeyCodeForward = 90, + kKeyCodeMute = 91 } KeyCode; static const KeycodeLabel FLAGS[] = { diff --git a/include/ui/PixelFormat.h b/include/ui/PixelFormat.h index b65c959261e737bc91e0448b2608f0461f0fa891..14af8232bb15c53306ead0708634fe709cfaab09 100644 --- a/include/ui/PixelFormat.h +++ b/include/ui/PixelFormat.h @@ -71,6 +71,10 @@ enum { PIXEL_FORMAT_YCbCr_422_SP= GGL_PIXEL_FORMAT_YCbCr_422_SP, PIXEL_FORMAT_YCbCr_420_SP= GGL_PIXEL_FORMAT_YCbCr_420_SP, + PIXEL_FORMAT_YCbCr_422_P = GGL_PIXEL_FORMAT_YCbCr_422_P, + PIXEL_FORMAT_YCbCr_420_P = GGL_PIXEL_FORMAT_YCbCr_420_P, + PIXEL_FORMAT_YCbCr_422_I = GGL_PIXEL_FORMAT_YCbCr_422_I, + PIXEL_FORMAT_YCbCr_420_I = GGL_PIXEL_FORMAT_YCbCr_420_I, // New formats can be added if they're also defined in // pixelflinger/format.h @@ -80,7 +84,19 @@ typedef int32_t PixelFormat; struct PixelFormatInfo { + enum { // components + ALPHA = 1, + RGB = 2, + RGBA = 3, + LUMINANCE = 4, + LUMINANCE_ALPHA = 5, + Y_CB_CR_SP = 6, + Y_CB_CR_P = 7, + Y_CB_CR_I = 8, + }; + inline PixelFormatInfo() : version(sizeof(PixelFormatInfo)) { } + size_t getScanlineSize(unsigned int width) const; size_t version; PixelFormat format; size_t bytesPerPixel; @@ -93,7 +109,9 @@ struct PixelFormatInfo uint8_t l_green; uint8_t h_blue; uint8_t l_blue; - uint32_t reserved[2]; + uint8_t components; + uint8_t reserved0[3]; + uint32_t reserved1; }; // Consider caching the results of these functions are they're not diff --git a/include/utils/ResourceTypes.h b/include/utils/ResourceTypes.h index 2d56e3e263c15c9c07086112fd0145e0db8ecc39..7d3fcf2a837d905808dcf9e44e6716a018c8a2c4 100644 --- a/include/utils/ResourceTypes.h +++ b/include/utils/ResourceTypes.h @@ -223,7 +223,7 @@ struct Res_value { // Number of bytes in this structure. uint16_t size; - + // Always set to 0. uint8_t res0; @@ -1101,16 +1101,22 @@ struct ResTable_config return false; } - // Return true if 'this' can be considered a match for the parameters in + // 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 (settings.mcc != 0 && mcc != 0 - && mcc != settings.mcc) { + if ((settings.mcc != 0 && mcc != 0 + && mcc != settings.mcc) || + (settings.mcc == 0 && mcc != 0)) { return false; } - if (settings.mnc != 0 && mnc != 0 - && mnc != settings.mnc) { + if ((settings.mnc != 0 && mnc != 0 + && mnc != settings.mnc) || + (settings.mnc == 0 && mnc != 0)) { return false; } } @@ -1131,10 +1137,8 @@ struct ResTable_config && orientation != settings.orientation) { return false; } - if (settings.density != 0 && density != 0 - && density != settings.density) { - return false; - } + // Density not taken into account, always match, no matter what + // density is specified for the resource if (settings.touchscreen != 0 && touchscreen != 0 && touchscreen != settings.touchscreen) { return false; @@ -1464,11 +1468,11 @@ public: * @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, - uint32_t* outSpecFlags=NULL) const; + 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, outSpecFlags); + return getResource(res.ident, outValue, false, outSpecFlags, NULL); } ssize_t resolveReference(Res_value* inOutValue, diff --git a/include/utils/logger.h b/include/utils/logger.h deleted file mode 100644 index 3a08019a8866c7a4ee19821a05c9b61701b025f2..0000000000000000000000000000000000000000 --- a/include/utils/logger.h +++ /dev/null @@ -1,46 +0,0 @@ -/* utils/logger.h -** -** Copyright 2007, The Android Open Source Project -** -** This file is dual licensed. It may be redistributed and/or modified -** under the terms of the Apache 2.0 License OR version 2 of the GNU -** General Public License. -*/ - -#ifndef _UTILS_LOGGER_H -#define _UTILS_LOGGER_H - -#include - -struct logger_entry { - uint16_t len; /* length of the payload */ - uint16_t __pad; /* no matter what, we get 2 bytes of padding */ - int32_t pid; /* generating process's pid */ - int32_t tid; /* generating process's tid */ - int32_t sec; /* seconds since Epoch */ - int32_t nsec; /* nanoseconds */ - char msg[0]; /* the entry's payload */ -}; - -#define LOGGER_LOG_MAIN "log/main" -#define LOGGER_LOG_RADIO "log/radio" -#define LOGGER_LOG_EVENTS "log/events" - -#define LOGGER_ENTRY_MAX_LEN (4*1024) -#define LOGGER_ENTRY_MAX_PAYLOAD \ - (LOGGER_ENTRY_MAX_LEN - sizeof(struct logger_entry)) - -#ifdef HAVE_IOCTL - -#include - -#define __LOGGERIO 0xAE - -#define LOGGER_GET_LOG_BUF_SIZE _IO(__LOGGERIO, 1) /* size of log */ -#define LOGGER_GET_LOG_LEN _IO(__LOGGERIO, 2) /* used log len */ -#define LOGGER_GET_NEXT_ENTRY_LEN _IO(__LOGGERIO, 3) /* next entry len */ -#define LOGGER_FLUSH_LOG _IO(__LOGGERIO, 4) /* flush log */ - -#endif // HAVE_IOCTL - -#endif /* _UTILS_LOGGER_H */ diff --git a/include/utils/threads.h b/include/utils/threads.h index 7dca810043e9885d4b1a7a866c876c8d99e0529b..8d8d46a054d8e3893e6996a4bb8379ca74847169 100644 --- a/include/utils/threads.h +++ b/include/utils/threads.h @@ -248,41 +248,6 @@ private: }; -/* - * Read/write lock. The resource can have multiple readers or one writer, - * but can't be read and written at the same time. - * - * The same thread should not call a lock function while it already has - * a lock. (Should be okay for multiple readers.) - */ -class ReadWriteLock { -public: - ReadWriteLock() - : mNumReaders(0), mNumWriters(0) - {} - ~ReadWriteLock() {} - - void lockForRead(); - bool tryLockForRead(); - void unlockForRead(); - - void lockForWrite(); - bool tryLockForWrite(); - void unlockForWrite(); - -private: - int mNumReaders; - int mNumWriters; - - Mutex mLock; - Condition mReadWaiter; - Condition mWriteWaiter; -#if defined(PRINT_RENDER_TIMES) - DurationTimer mDebugTimer; -#endif -}; - - /* * This is our spiffy thread object! */ diff --git a/libs/audioflinger/A2dpAudioInterface.cpp b/libs/audioflinger/A2dpAudioInterface.cpp index c8c8431096d7b5e0dbdad7b54785ac7500285587..2974e32ee179e0eaef8d4f84fa9677e87ec1d3e3 100644 --- a/libs/audioflinger/A2dpAudioInterface.cpp +++ b/libs/audioflinger/A2dpAudioInterface.cpp @@ -48,7 +48,6 @@ AudioStreamOut* A2dpAudioInterface::openOutputStream( int format, int channelCount, uint32_t sampleRate, status_t *status) { LOGD("A2dpAudioInterface::openOutputStream %d, %d, %d\n", format, channelCount, sampleRate); - Mutex::Autolock lock(mLock); status_t err = 0; // only one output stream allowed @@ -72,7 +71,8 @@ AudioStreamOut* A2dpAudioInterface::openOutputStream( } AudioStreamIn* A2dpAudioInterface::openInputStream( - int format, int channelCount, uint32_t sampleRate, status_t *status) + int format, int channelCount, uint32_t sampleRate, status_t *status, + AudioSystem::audio_in_acoustics acoustics) { if (status) *status = -1; @@ -99,6 +99,10 @@ status_t A2dpAudioInterface::setParameter(const char *key, const char *value) if (strcmp(key, "a2dp_sink_address") == 0) { return mOutput->setAddress(value); } + if (strcmp(key, "bluetooth_enabled") == 0 && + strcmp(value, "false") == 0) { + return mOutput->close(); + } return 0; } @@ -126,11 +130,11 @@ status_t A2dpAudioInterface::dump(int fd, const Vector& args) // ---------------------------------------------------------------------------- A2dpAudioInterface::A2dpAudioStreamOut::A2dpAudioStreamOut() : - mFd(-1), mStandby(true), mStartCount(0), mRetryCount(0), mData(NULL), - mInitialized(false) + mFd(-1), mStandby(true), mStartCount(0), mRetryCount(0), mData(NULL) { // use any address by default - strncpy(mA2dpAddress, "00:00:00:00:00:00", sizeof(mA2dpAddress)); + strcpy(mA2dpAddress, "00:00:00:00:00:00"); + init(); } status_t A2dpAudioInterface::A2dpAudioStreamOut::set( @@ -154,23 +158,17 @@ status_t A2dpAudioInterface::A2dpAudioStreamOut::set( A2dpAudioInterface::A2dpAudioStreamOut::~A2dpAudioStreamOut() { - if (mData) - a2dp_cleanup(mData); + close(); } ssize_t A2dpAudioInterface::A2dpAudioStreamOut::write(const void* buffer, size_t bytes) { - status_t status = NO_INIT; - size_t remaining = bytes; + Mutex::Autolock lock(mLock); - if (!mInitialized) { - status = a2dp_init(mA2dpAddress, 44100, 2, &mData); - if (status < 0) { - LOGE("a2dp_init failed err: %d\n", status); - goto Error; - } - mInitialized = true; - } + size_t remaining = bytes; + status_t status = init(); + if (status < 0) + goto Error; while (remaining > 0) { status = a2dp_write(mData, buffer, remaining); @@ -186,17 +184,34 @@ ssize_t A2dpAudioInterface::A2dpAudioStreamOut::write(const void* buffer, size_t return bytes; -Error: +Error: // Simulate audio output timing in case of error usleep(bytes * 1000000 / frameSize() / sampleRate()); return status; } +status_t A2dpAudioInterface::A2dpAudioStreamOut::init() +{ + if (!mData) { + status_t status = a2dp_init(44100, 2, &mData); + if (status < 0) { + LOGE("a2dp_init failed err: %d\n", status); + mData = NULL; + return status; + } + a2dp_set_sink(mData, mA2dpAddress); + } + + return 0; +} + status_t A2dpAudioInterface::A2dpAudioStreamOut::standby() { int result = 0; + Mutex::Autolock lock(mLock); + if (!mStandby) { result = a2dp_stop(mData); if (result == 0) @@ -208,19 +223,24 @@ status_t A2dpAudioInterface::A2dpAudioStreamOut::standby() status_t A2dpAudioInterface::A2dpAudioStreamOut::setAddress(const char* address) { - if (strlen(address) < sizeof(mA2dpAddress)) + Mutex::Autolock lock(mLock); + + if (strlen(address) != strlen("00:00:00:00:00:00")) return -EINVAL; - if (strcmp(address, mA2dpAddress)) { - strcpy(mA2dpAddress, address); - - if (mInitialized) { - a2dp_cleanup(mData); - mData = NULL; - mInitialized = false; - } + strcpy(mA2dpAddress, address); + if (mData) + a2dp_set_sink(mData, mA2dpAddress); + + return NO_ERROR; +} + +status_t A2dpAudioInterface::A2dpAudioStreamOut::close() +{ + if (mData) { + a2dp_cleanup(mData); + mData = NULL; } - return NO_ERROR; } diff --git a/libs/audioflinger/A2dpAudioInterface.h b/libs/audioflinger/A2dpAudioInterface.h index 2197d0eb5b4c1506be7a0e55aa6fb1c067520724..99614dc1087392dac69888b7971530c367f9fbb4 100644 --- a/libs/audioflinger/A2dpAudioInterface.h +++ b/libs/audioflinger/A2dpAudioInterface.h @@ -58,7 +58,8 @@ public: int format, int channelCount, uint32_t sampleRate, - status_t *status); + status_t *status, + AudioSystem::audio_in_acoustics acoustics); protected: virtual status_t doRouting(); @@ -77,7 +78,7 @@ private: virtual size_t bufferSize() const { return 512 * 20; } virtual int channelCount() const { return 2; } virtual int format() const { return AudioSystem::PCM_16_BIT; } - virtual uint32_t latency() const { return ((1000*channelCount()*bufferSize())/frameSize())/sampleRate() + 200; } + virtual uint32_t latency() const { return ((1000*bufferSize())/frameSize())/sampleRate() + 200; } virtual status_t setVolume(float volume) { return INVALID_OPERATION; } virtual ssize_t write(const void* buffer, size_t bytes); status_t standby(); @@ -85,6 +86,8 @@ private: private: friend class A2dpAudioInterface; + status_t init(); + status_t close(); status_t setAddress(const char* address); private: @@ -94,10 +97,9 @@ private: int mRetryCount; char mA2dpAddress[20]; void* mData; - bool mInitialized; + Mutex mLock; }; - Mutex mLock; A2dpAudioStreamOut* mOutput; }; diff --git a/libs/audioflinger/AudioDumpInterface.h b/libs/audioflinger/AudioDumpInterface.h index 42204d6334189236b301ad3ee4409c5ff3772da4..9a941021e651a5651488f078efa0c87e184585d5 100644 --- a/libs/audioflinger/AudioDumpInterface.h +++ b/libs/audioflinger/AudioDumpInterface.h @@ -78,8 +78,9 @@ public: virtual status_t setParameter(const char* key, const char* value) {return mFinalInterface->setParameter(key, value);} - virtual AudioStreamIn* openInputStream( int format, int channelCount, uint32_t sampleRate, status_t *status) - {return mFinalInterface->openInputStream( format, channelCount, sampleRate, status);} + virtual AudioStreamIn* openInputStream( int format, int channelCount, uint32_t sampleRate, status_t *status, + AudioSystem::audio_in_acoustics acoustics) + {return mFinalInterface->openInputStream( format, channelCount, sampleRate, status, acoustics);} virtual status_t dump(int fd, const Vector& args) { return mFinalInterface->dumpState(fd, args); } diff --git a/libs/audioflinger/AudioFlinger.cpp b/libs/audioflinger/AudioFlinger.cpp index 918b01fea9185f212c683e0e865e8ae111c23e34..3c81a47812d08e1f835bd532285686f876d1e299 100644 --- a/libs/audioflinger/AudioFlinger.cpp +++ b/libs/audioflinger/AudioFlinger.cpp @@ -47,6 +47,15 @@ #include "A2dpAudioInterface.h" #endif +// ---------------------------------------------------------------------------- +// the sim build doesn't have gettid + +#ifndef HAVE_GETTID +# define gettid getpid +#endif + +// ---------------------------------------------------------------------------- + namespace android { //static const nsecs_t kStandbyTimeInNsecs = seconds(3); @@ -59,6 +68,16 @@ static const float MAX_GAIN = 4096.0f; static const int8_t kMaxTrackRetries = 50; static const int8_t kMaxTrackStartupRetries = 50; +static const int kStartSleepTime = 30000; +static const int kStopSleepTime = 30000; + +static const int kDumpLockRetries = 50; +static const int kDumpLockSleep = 20000; + +// Maximum number of pending buffers allocated by OutputTrack::write() +static const uint8_t kMaxOutputTrackBuffers = 5; + + #define AUDIOFLINGER_SECURITY_ENABLED 1 // ---------------------------------------------------------------------------- @@ -98,13 +117,10 @@ static bool settingsAllowed() { // ---------------------------------------------------------------------------- AudioFlinger::AudioFlinger() - : BnAudioFlinger(), Thread(false), - mMasterVolume(0), mMasterMute(true), mHardwareAudioMixer(0), mA2dpAudioMixer(0), - mAudioMixer(0), mAudioHardware(0), mA2dpAudioInterface(0), mHardwareOutput(0), - mA2dpOutput(0), mOutput(0), mRequestedOutput(0), mAudioRecordThread(0), - mSampleRate(0), mFrameCount(0), mChannelCount(0), mFormat(0), mMixBuffer(0), - mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mStandby(false), - mInWrite(false), mA2dpDisableCount(0), mA2dpSuppressed(false) + : BnAudioFlinger(), + mAudioHardware(0), mA2dpAudioInterface(0), mA2dpEnabled(false), mNotifyA2dpChange(false), + mForcedSpeakerCount(0), mA2dpDisableCount(0), mA2dpSuppressed(false), mForcedRoute(0), + mRouteRestoreTime(0), mMusicMuteSaved(false) { mHardwareStatus = AUDIO_HW_IDLE; mAudioHardware = AudioHardwareInterface::create(); @@ -113,57 +129,51 @@ AudioFlinger::AudioFlinger() // open 16-bit output stream for s/w mixer mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; status_t status; - mHardwareOutput = mAudioHardware->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status); + AudioStreamOut *hwOutput = mAudioHardware->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status); mHardwareStatus = AUDIO_HW_IDLE; - if (mHardwareOutput) { - mHardwareAudioMixer = new AudioMixer(getOutputFrameCount(mHardwareOutput), mHardwareOutput->sampleRate()); - mRequestedOutput = mHardwareOutput; - doSetOutput(mHardwareOutput); - - // FIXME - this should come from settings - setMasterVolume(1.0f); - setRouting(AudioSystem::MODE_NORMAL, AudioSystem::ROUTE_SPEAKER, AudioSystem::ROUTE_ALL); - setRouting(AudioSystem::MODE_RINGTONE, AudioSystem::ROUTE_SPEAKER, AudioSystem::ROUTE_ALL); - setRouting(AudioSystem::MODE_IN_CALL, AudioSystem::ROUTE_EARPIECE, AudioSystem::ROUTE_ALL); - setMode(AudioSystem::MODE_NORMAL); - mMasterMute = false; + if (hwOutput) { + mHardwareMixerThread = new MixerThread(this, hwOutput, AudioSystem::AUDIO_OUTPUT_HARDWARE); } else { - LOGE("Failed to initialize output stream, status: %d", status); + LOGE("Failed to initialize hardware output stream, status: %d", status); } #ifdef WITH_A2DP // Create A2DP interface mA2dpAudioInterface = new A2dpAudioInterface(); - mA2dpOutput = mA2dpAudioInterface->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status); - mA2dpAudioMixer = new AudioMixer(getOutputFrameCount(mA2dpOutput), mA2dpOutput->sampleRate()); - - // create a buffer big enough for both hardware and A2DP audio output. - size_t hwFrameCount = getOutputFrameCount(mHardwareOutput); - size_t a2dpFrameCount = getOutputFrameCount(mA2dpOutput); - size_t frameCount = (hwFrameCount > a2dpFrameCount ? hwFrameCount : a2dpFrameCount); -#else - size_t frameCount = getOutputFrameCount(mHardwareOutput); + AudioStreamOut *a2dpOutput = mA2dpAudioInterface->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status); + if (a2dpOutput) { + mA2dpMixerThread = new MixerThread(this, a2dpOutput, AudioSystem::AUDIO_OUTPUT_A2DP); + if (hwOutput) { + uint32_t frameCount = ((a2dpOutput->bufferSize()/a2dpOutput->frameSize()) * hwOutput->sampleRate()) / a2dpOutput->sampleRate(); + MixerThread::OutputTrack *a2dpOutTrack = new MixerThread::OutputTrack(mA2dpMixerThread, + hwOutput->sampleRate(), + AudioSystem::PCM_16_BIT, + hwOutput->channelCount(), + frameCount); + mHardwareMixerThread->setOuputTrack(a2dpOutTrack); + } + } else { + LOGE("Failed to initialize A2DP output stream, status: %d", status); + } #endif - // FIXME - Current mixer implementation only supports stereo output: Always - // Allocate a stereo buffer even if HW output is mono. - mMixBuffer = new int16_t[frameCount * 2]; - memset(mMixBuffer, 0, frameCount * 2 * sizeof(int16_t)); - + + // FIXME - this should come from settings + setRouting(AudioSystem::MODE_NORMAL, AudioSystem::ROUTE_SPEAKER, AudioSystem::ROUTE_ALL); + setRouting(AudioSystem::MODE_RINGTONE, AudioSystem::ROUTE_SPEAKER, AudioSystem::ROUTE_ALL); + setRouting(AudioSystem::MODE_IN_CALL, AudioSystem::ROUTE_EARPIECE, AudioSystem::ROUTE_ALL); + setMode(AudioSystem::MODE_NORMAL); + + setMasterVolume(1.0f); + setMasterMute(false); + // Start record thread - mAudioRecordThread = new AudioRecordThread(mAudioHardware); + mAudioRecordThread = new AudioRecordThread(mAudioHardware, this); if (mAudioRecordThread != 0) { mAudioRecordThread->run("AudioRecordThread", PRIORITY_URGENT_AUDIO); } } else { LOGE("Couldn't even initialize the stubbed audio hardware!"); } - - char value[PROPERTY_VALUE_MAX]; - property_get("ro.audio.silent", value, "0"); - if (atoi(value)) { - LOGD("Silence is golden"); - mMasterMute = true; - } } AudioFlinger::~AudioFlinger() @@ -172,59 +182,72 @@ AudioFlinger::~AudioFlinger() mAudioRecordThread->exit(); mAudioRecordThread.clear(); } + mHardwareMixerThread.clear(); delete mAudioHardware; // deleting mA2dpAudioInterface also deletes mA2dpOutput; +#ifdef WITH_A2DP + mA2dpMixerThread.clear(); delete mA2dpAudioInterface; - delete [] mMixBuffer; - delete mHardwareAudioMixer; - delete mA2dpAudioMixer; -} - -void AudioFlinger::setOutput(AudioStreamOut* output) -{ - mRequestedOutput = output; +#endif } -void AudioFlinger::doSetOutput(AudioStreamOut* output) + +#ifdef WITH_A2DP +// setA2dpEnabled_l() must be called with AudioFlinger::mLock held +void AudioFlinger::setA2dpEnabled_l(bool enable) { - mSampleRate = output->sampleRate(); - mChannelCount = output->channelCount(); + SortedVector < sp > tracks; + SortedVector < wp > activeTracks; + + LOGV_IF(enable, "set output to A2DP\n"); + LOGV_IF(!enable, "set output to hardware audio\n"); - // FIXME - Current mixer implementation only supports stereo output - if (mChannelCount == 1) { - LOGE("Invalid audio hardware channel count"); + // Transfer tracks playing on MUSIC stream from one mixer to the other + if (enable) { + mHardwareMixerThread->getTracks_l(tracks, activeTracks); + mA2dpMixerThread->putTracks_l(tracks, activeTracks); + } else { + mA2dpMixerThread->getTracks_l(tracks, activeTracks); + mHardwareMixerThread->putTracks_l(tracks, activeTracks); } - mFormat = output->format(); - mFrameCount = getOutputFrameCount(output); - mAudioMixer = (output == mA2dpOutput ? mA2dpAudioMixer : mHardwareAudioMixer); - mOutput = output; + mA2dpEnabled = enable; + mNotifyA2dpChange = true; + mWaitWorkCV.broadcast(); } -size_t AudioFlinger::getOutputFrameCount(AudioStreamOut* output) +// checkA2dpEnabledChange_l() must be called with AudioFlinger::mLock held +void AudioFlinger::checkA2dpEnabledChange_l() { - return output->bufferSize() / output->channelCount() / sizeof(int16_t); + if (mNotifyA2dpChange) { + // Notify AudioSystem of the A2DP activation/deactivation + size_t size = mNotificationClients.size(); + for (size_t i = 0; i < size; i++) { + sp binder = mNotificationClients.itemAt(i).promote(); + if (binder != NULL) { + LOGV("Notifying output change to client %p", binder.get()); + sp client = interface_cast (binder); + client->a2dpEnabledChanged(mA2dpEnabled); + } + } + mNotifyA2dpChange = false; + } } +#endif // WITH_A2DP -#ifdef WITH_A2DP -bool AudioFlinger::streamDisablesA2dp(int streamType) +bool AudioFlinger::streamForcedToSpeaker(int streamType) { - return (streamType == AudioTrack::SYSTEM || - streamType == AudioTrack::RING || - streamType == AudioTrack::ALARM || - streamType == AudioTrack::NOTIFICATION); + // NOTE that streams listed here must not be routed to A2DP by default: + // AudioSystem::routedToA2dpOutput(streamType) == false + return (streamType == AudioSystem::RING || + streamType == AudioSystem::ALARM || + streamType == AudioSystem::NOTIFICATION); } -void AudioFlinger::setA2dpEnabled(bool enable) +bool AudioFlinger::streamDisablesA2dp(int streamType) { - if (enable) { - LOGD("set output to A2DP\n"); - setOutput(mA2dpOutput); - } else { - LOGD("set output to hardware audio\n"); - setOutput(mHardwareOutput); - } + return (streamType == AudioSystem::VOICE_CALL || + streamType == AudioSystem::BLUETOOTH_SCO); } -#endif // WITH_A2DP status_t AudioFlinger::dumpClients(int fd, const Vector& args) { @@ -247,60 +270,18 @@ status_t AudioFlinger::dumpClients(int fd, const Vector& args) return NO_ERROR; } -status_t AudioFlinger::dumpTracks(int fd, const Vector& args) -{ - const size_t SIZE = 256; - char buffer[SIZE]; - String8 result; - - result.append("Tracks:\n"); - result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n"); - for (size_t i = 0; i < mTracks.size(); ++i) { - wp wTrack = mTracks[i]; - if (wTrack != 0) { - sp track = wTrack.promote(); - if (track != 0) { - track->dump(buffer, SIZE); - result.append(buffer); - } - } - } - - result.append("Active Tracks:\n"); - result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n"); - for (size_t i = 0; i < mActiveTracks.size(); ++i) { - wp wTrack = mTracks[i]; - if (wTrack != 0) { - sp track = wTrack.promote(); - if (track != 0) { - track->dump(buffer, SIZE); - result.append(buffer); - } - } - } - write(fd, result.string(), result.size()); - return NO_ERROR; -} status_t AudioFlinger::dumpInternals(int fd, const Vector& args) { const size_t SIZE = 256; char buffer[SIZE]; String8 result; - - snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", audioMixer()->trackNames()); - result.append(buffer); - snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime)); - result.append(buffer); - snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); - result.append(buffer); - snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); - result.append(buffer); - snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); - result.append(buffer); - snprintf(buffer, SIZE, "standby: %d\n", mStandby); - result.append(buffer); - snprintf(buffer, SIZE, "Hardware status: %d\n", mHardwareStatus); + int hardwareStatus = mHardwareStatus; + + if (hardwareStatus == AUDIO_HW_IDLE && mHardwareMixerThread->mStandby) { + hardwareStatus = AUDIO_HW_STANDBY; + } + snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus); result.append(buffer); write(fd, result.string(), result.size()); return NO_ERROR; @@ -325,316 +306,142 @@ status_t AudioFlinger::dump(int fd, const Vector& args) if (checkCallingPermission(String16("android.permission.DUMP")) == false) { dumpPermissionDenial(fd, args); } else { - AutoMutex lock(&mLock); + bool locked = false; + for (int i = 0; i < kDumpLockRetries; ++i) { + if (mLock.tryLock() == NO_ERROR) { + locked = true; + break; + } + usleep(kDumpLockSleep); + } dumpClients(fd, args); - dumpTracks(fd, args); dumpInternals(fd, args); + mHardwareMixerThread->dump(fd, args); +#ifdef WITH_A2DP + mA2dpMixerThread->dump(fd, args); +#endif + + // dump record client + if (mAudioRecordThread != 0) mAudioRecordThread->dump(fd, args); + if (mAudioHardware) { mAudioHardware->dumpState(fd, args); } + if (locked) mLock.unlock(); } return NO_ERROR; } -// Thread virtuals -bool AudioFlinger::threadLoop() -{ - unsigned long sleepTime = kBufferRecoveryInUsecs; - int16_t* curBuf = mMixBuffer; - Vector< sp > tracksToRemove; - size_t enabledTracks = 0; - nsecs_t standbyTime = systemTime(); +// IAudioFlinger interface - do { - enabledTracks = 0; - { // scope for the mLock - - Mutex::Autolock _l(mLock); - const SortedVector< wp >& activeTracks = mActiveTracks; - // put audio hardware into standby after short delay - if UNLIKELY(!activeTracks.size() && systemTime() > standbyTime) { - // wait until we have something to do... - LOGV("Audio hardware entering standby\n"); - mHardwareStatus = AUDIO_HW_STANDBY; - if (!mStandby) { - mOutput->standby(); - mStandby = true; - } - mHardwareStatus = AUDIO_HW_IDLE; - // we're about to wait, flush the binder command buffer - IPCThreadState::self()->flushCommands(); - mWaitWorkCV.wait(mLock); - LOGV("Audio hardware exiting standby\n"); - standbyTime = systemTime() + kStandbyTimeInNsecs; - continue; - } +sp AudioFlinger::createTrack( + pid_t pid, + int streamType, + uint32_t sampleRate, + int format, + int channelCount, + int frameCount, + uint32_t flags, + const sp& sharedBuffer, + status_t *status) +{ + sp track; + sp trackHandle; + sp client; + wp wclient; + status_t lStatus; - // check for change in output - if (mRequestedOutput != mOutput) { + if (streamType >= AudioSystem::NUM_STREAM_TYPES) { + LOGE("invalid stream type"); + lStatus = BAD_VALUE; + goto Exit; + } - // put current output into standby mode - if (mOutput) mOutput->standby(); + { + Mutex::Autolock _l(mLock); - // change output - doSetOutput(mRequestedOutput); - } + wclient = mClients.valueFor(pid); - // find out which tracks need to be processed - size_t count = activeTracks.size(); - for (size_t i=0 ; i t = activeTracks[i].promote(); - if (t == 0) continue; + if (wclient != NULL) { + client = wclient.promote(); + } else { + client = new Client(this, pid); + mClients.add(pid, client); + } +#ifdef WITH_A2DP + if (isA2dpEnabled() && AudioSystem::routedToA2dpOutput(streamType)) { + track = mA2dpMixerThread->createTrack_l(client, streamType, sampleRate, format, + channelCount, frameCount, sharedBuffer, &lStatus); + } else +#endif + { + track = mHardwareMixerThread->createTrack_l(client, streamType, sampleRate, format, + channelCount, frameCount, sharedBuffer, &lStatus); + } + } + if (lStatus == NO_ERROR) { + trackHandle = new TrackHandle(track); + } else { + track.clear(); + } - Track* const track = t.get(); - audio_track_cblk_t* cblk = track->cblk(); +Exit: + if(status) { + *status = lStatus; + } + return trackHandle; +} - // The first time a track is added we wait - // for all its buffers to be filled before processing it - mAudioMixer->setActiveTrack(track->name()); - if (cblk->framesReady() && (track->isReady() || track->isStopped()) && - !track->isPaused()) - { - //LOGD("u=%08x, s=%08x [OK]", u, s); +uint32_t AudioFlinger::sampleRate(int output) const +{ +#ifdef WITH_A2DP + if (output == AudioSystem::AUDIO_OUTPUT_A2DP) { + return mA2dpMixerThread->sampleRate(); + } +#endif + return mHardwareMixerThread->sampleRate(); +} - // compute volume for this track - int16_t left, right; - if (track->isMuted() || mMasterMute || track->isPausing()) { - left = right = 0; - if (track->isPausing()) { - LOGV("paused(%d)", track->name()); - track->setPaused(); - } - } else { - float typeVolume = mStreamTypes[track->type()].volume; - float v = mMasterVolume * typeVolume; - float v_clamped = v * cblk->volume[0]; - if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; - left = int16_t(v_clamped); - v_clamped = v * cblk->volume[1]; - if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; - right = int16_t(v_clamped); - } +int AudioFlinger::channelCount(int output) const +{ +#ifdef WITH_A2DP + if (output == AudioSystem::AUDIO_OUTPUT_A2DP) { + return mA2dpMixerThread->channelCount(); + } +#endif + return mHardwareMixerThread->channelCount(); +} - // XXX: these things DON'T need to be done each time - mAudioMixer->setBufferProvider(track); - mAudioMixer->enable(AudioMixer::MIXING); +int AudioFlinger::format(int output) const +{ +#ifdef WITH_A2DP + if (output == AudioSystem::AUDIO_OUTPUT_A2DP) { + return mA2dpMixerThread->format(); + } +#endif + return mHardwareMixerThread->format(); +} - int param; - if ( track->mFillingUpStatus == Track::FS_FILLED) { - // no ramp for the first volume setting - track->mFillingUpStatus = Track::FS_ACTIVE; - if (track->mState == TrackBase::RESUMING) { - track->mState = TrackBase::ACTIVE; - param = AudioMixer::RAMP_VOLUME; - } else { - param = AudioMixer::VOLUME; - } - } else { - param = AudioMixer::RAMP_VOLUME; - } - mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left); - mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right); - mAudioMixer->setParameter( - AudioMixer::TRACK, - AudioMixer::FORMAT, track->format()); - mAudioMixer->setParameter( - AudioMixer::TRACK, - AudioMixer::CHANNEL_COUNT, track->channelCount()); - mAudioMixer->setParameter( - AudioMixer::RESAMPLE, - AudioMixer::SAMPLE_RATE, - int(cblk->sampleRate)); +size_t AudioFlinger::frameCount(int output) const +{ +#ifdef WITH_A2DP + if (output == AudioSystem::AUDIO_OUTPUT_A2DP) { + return mA2dpMixerThread->frameCount(); + } +#endif + return mHardwareMixerThread->frameCount(); +} - // reset retry count - track->mRetryCount = kMaxTrackRetries; - enabledTracks++; - } else { - //LOGD("u=%08x, s=%08x [NOT READY]", u, s); - if (track->isStopped()) { - track->reset(); - } - if (track->isTerminated() || track->isStopped() || track->isPaused()) { - // We have consumed all the buffers of this track. - // Remove it from the list of active tracks. - LOGV("remove(%d) from active list", track->name()); - tracksToRemove.add(track); - } else { - // No buffers for this track. Give it a few chances to - // fill a buffer, then remove it from active list. - if (--(track->mRetryCount) <= 0) { - LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); - tracksToRemove.add(track); - } - } - // LOGV("disable(%d)", track->name()); - mAudioMixer->disable(AudioMixer::MIXING); - } - } - - // remove all the tracks that need to be... - count = tracksToRemove.size(); - if (UNLIKELY(count)) { - for (size_t i=0 ; i& track = tracksToRemove[i]; - removeActiveTrack(track); - if (track->isTerminated()) { - mTracks.remove(track); - mAudioMixer->deleteTrackName(track->mName); - } - } - } - } - if (LIKELY(enabledTracks)) { - // mix buffers... - mAudioMixer->process(curBuf); - - // output audio to hardware - mLastWriteTime = systemTime(); - mInWrite = true; - size_t mixBufferSize = mFrameCount*mChannelCount*sizeof(int16_t); - mOutput->write(curBuf, mixBufferSize); - mNumWrites++; - mInWrite = false; - mStandby = false; - nsecs_t temp = systemTime(); - standbyTime = temp + kStandbyTimeInNsecs; - nsecs_t delta = temp - mLastWriteTime; - nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2; - if (delta > maxPeriod) { - LOGW("write blocked for %llu msecs", ns2ms(delta)); - mNumDelayedWrites++; - } - sleepTime = kBufferRecoveryInUsecs; - } else { - // There was nothing to mix this round, which means all - // active tracks were late. Sleep a little bit to give - // them another chance. If we're too late, the audio - // hardware will zero-fill for us. - LOGV("no buffers - usleep(%lu)", sleepTime); - usleep(sleepTime); - if (sleepTime < kMaxBufferRecoveryInUsecs) { - sleepTime += kBufferRecoveryInUsecs; - } - } - - // finally let go of all our tracks, without the lock held - // since we can't guarantee the destructors won't acquire that - // same lock. - tracksToRemove.clear(); - } while (true); - - return false; -} - -status_t AudioFlinger::readyToRun() -{ - if (mSampleRate == 0) { - LOGE("No working audio driver found."); - return NO_INIT; - } - LOGI("AudioFlinger's main thread ready to run."); - return NO_ERROR; -} - -void AudioFlinger::onFirstRef() -{ - run("AudioFlinger", ANDROID_PRIORITY_URGENT_AUDIO); -} - -// IAudioFlinger interface -sp AudioFlinger::createTrack( - pid_t pid, - int streamType, - uint32_t sampleRate, - int format, - int channelCount, - int frameCount, - uint32_t flags, - const sp& sharedBuffer, - status_t *status) -{ - sp track; - sp trackHandle; - sp client; - wp wclient; - status_t lStatus; - - if (streamType >= AudioTrack::NUM_STREAM_TYPES) { - LOGE("invalid stream type"); - lStatus = BAD_VALUE; - goto Exit; - } - - // Resampler implementation limits input sampling rate to 2 x output sampling rate. - if (sampleRate > MAX_SAMPLE_RATE || sampleRate > mSampleRate*2) { - LOGE("Sample rate out of range: %d", sampleRate); - lStatus = BAD_VALUE; - goto Exit; - } - - { - Mutex::Autolock _l(mLock); - - if (mSampleRate == 0) { - LOGE("Audio driver not initialized."); - lStatus = NO_INIT; - goto Exit; - } - - wclient = mClients.valueFor(pid); - - if (wclient != NULL) { - client = wclient.promote(); - } else { - client = new Client(this, pid); - mClients.add(pid, client); - } - - track = new Track(this, client, streamType, sampleRate, format, - channelCount, frameCount, sharedBuffer); - mTracks.add(track); - trackHandle = new TrackHandle(track); - - lStatus = NO_ERROR; - } - -Exit: - if(status) { - *status = lStatus; - } - return trackHandle; -} - -uint32_t AudioFlinger::sampleRate() const -{ - return mSampleRate; -} - -int AudioFlinger::channelCount() const -{ - return mChannelCount; -} - -int AudioFlinger::format() const -{ - return mFormat; -} - -size_t AudioFlinger::frameCount() const +uint32_t AudioFlinger::latency(int output) const { - return mFrameCount; -} - -uint32_t AudioFlinger::latency() const -{ - if (mOutput) { - return mOutput->latency(); - } - else { - return 0; - } +#ifdef WITH_A2DP + if (output == AudioSystem::AUDIO_OUTPUT_A2DP) { + return mA2dpMixerThread->latency(); + } +#endif + return mHardwareMixerThread->latency(); } status_t AudioFlinger::setMasterVolume(float value) @@ -648,12 +455,14 @@ status_t AudioFlinger::setMasterVolume(float value) AutoMutex lock(mHardwareLock); mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; if (mAudioHardware->setMasterVolume(value) == NO_ERROR) { - mMasterVolume = 1.0f; - } - else { - mMasterVolume = value; + value = 1.0f; } mHardwareStatus = AUDIO_HW_IDLE; + mHardwareMixerThread->setMasterVolume(value); +#ifdef WITH_A2DP + mA2dpMixerThread->setMasterVolume(value); +#endif + return NO_ERROR; } @@ -671,20 +480,21 @@ status_t AudioFlinger::setRouting(int mode, uint32_t routes, uint32_t mask) } #ifdef WITH_A2DP - LOGD("setRouting %d %d %d\n", mode, routes, mask); + LOGD("setRouting %d %d %d, tid %d, calling tid %d\n", mode, routes, mask, gettid(), IPCThreadState::self()->getCallingPid()); if (mode == AudioSystem::MODE_NORMAL && (mask & AudioSystem::ROUTE_BLUETOOTH_A2DP)) { AutoMutex lock(&mLock); bool enableA2dp = false; if (routes & AudioSystem::ROUTE_BLUETOOTH_A2DP) { - if (mA2dpDisableCount > 0) - mA2dpSuppressed = true; - else - enableA2dp = true; + enableA2dp = true; + } + if (mA2dpDisableCount > 0) { + mA2dpSuppressed = enableA2dp; + } else { + setA2dpEnabled_l(enableA2dp); } - setA2dpEnabled(enableA2dp); - LOGD("setOutput done\n"); + LOGV("setOutput done\n"); } #endif @@ -697,6 +507,12 @@ status_t AudioFlinger::setRouting(int mode, uint32_t routes, uint32_t mask) err = mAudioHardware->getRouting(mode, &r); if (err == NO_ERROR) { r = (r & ~mask) | (routes & mask); + if (mode == AudioSystem::MODE_NORMAL || + (mode == AudioSystem::MODE_CURRENT && getMode() == AudioSystem::MODE_NORMAL)) { + mSavedRoute = r; + r |= mForcedRoute; + LOGV("setRouting mSavedRoute %08x mForcedRoute %08x\n", mSavedRoute, mForcedRoute); + } mHardwareStatus = AUDIO_HW_SET_ROUTING; err = mAudioHardware->setRouting(mode, r); } @@ -709,9 +525,14 @@ uint32_t AudioFlinger::getRouting(int mode) const { uint32_t routes = 0; if ((mode >= AudioSystem::MODE_CURRENT) && (mode < AudioSystem::NUM_MODES)) { - mHardwareStatus = AUDIO_HW_GET_ROUTING; - mAudioHardware->getRouting(mode, &routes); - mHardwareStatus = AUDIO_HW_IDLE; + if (mode == AudioSystem::MODE_NORMAL || + (mode == AudioSystem::MODE_CURRENT && getMode() == AudioSystem::MODE_NORMAL)) { + routes = mSavedRoute; + } else { + mHardwareStatus = AUDIO_HW_GET_ROUTING; + mAudioHardware->getRouting(mode, &routes); + mHardwareStatus = AUDIO_HW_IDLE; + } } else { LOGW("Illegal value: getRouting(%d)", mode); } @@ -774,19 +595,21 @@ status_t AudioFlinger::setMasterMute(bool muted) if (!settingsAllowed()) { return PERMISSION_DENIED; } - - mMasterMute = muted; + mHardwareMixerThread->setMasterMute(muted); +#ifdef WITH_A2DP + mA2dpMixerThread->setMasterMute(muted); +#endif return NO_ERROR; } float AudioFlinger::masterVolume() const { - return mMasterVolume; + return mHardwareMixerThread->masterVolume(); } bool AudioFlinger::masterMute() const { - return mMasterMute; + return mHardwareMixerThread->masterMute(); } status_t AudioFlinger::setStreamVolume(int stream, float value) @@ -796,26 +619,40 @@ status_t AudioFlinger::setStreamVolume(int stream, float value) return PERMISSION_DENIED; } - if (uint32_t(stream) >= AudioTrack::NUM_STREAM_TYPES) { + if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) { return BAD_VALUE; } status_t ret = NO_ERROR; - if (stream == AudioTrack::VOICE_CALL) { + + if (stream == AudioSystem::VOICE_CALL || + stream == AudioSystem::BLUETOOTH_SCO) { + float hwValue = value; + if (stream == AudioSystem::VOICE_CALL) { + hwValue = (float)AudioSystem::logToLinear(value)/100.0f; + // FIXME: This is a temporary fix to re-base the internally + // generated in-call audio so that it is never muted, which is + // already the case for the hardware routed in-call audio. + // When audio stream handling is reworked, this should be + // addressed more cleanly. Fixes #1324; see discussion at + // http://review.source.android.com/8224 + value = value * 0.99 + 0.01; + } else { // (type == AudioSystem::BLUETOOTH_SCO) + hwValue = 1.0f; + } + AutoMutex lock(mHardwareLock); mHardwareStatus = AUDIO_SET_VOICE_VOLUME; - ret = mAudioHardware->setVoiceVolume(value); + ret = mAudioHardware->setVoiceVolume(hwValue); mHardwareStatus = AUDIO_HW_IDLE; - // FIXME: This is a temporary fix to re-base the internally - // generated in-call audio so that it is never muted, which is - // already the case for the hardware routed in-call audio. - // When audio stream handling is reworked, this should be - // addressed more cleanly. Fixes #1324; see discussion at - // http://review.source.android.com/8224 - mStreamTypes[stream].volume = value * (1.0 - 1.0 / 6.0) + (1.0 / 6.0); - } else { - mStreamTypes[stream].volume = value; + } + + mHardwareMixerThread->setStreamVolume(stream, value); +#ifdef WITH_A2DP + mA2dpMixerThread->setStreamVolume(stream, value); +#endif + return ret; } @@ -826,45 +663,66 @@ status_t AudioFlinger::setStreamMute(int stream, bool muted) return PERMISSION_DENIED; } - if (uint32_t(stream) >= AudioTrack::NUM_STREAM_TYPES) { + if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) { return BAD_VALUE; } - mStreamTypes[stream].mute = muted; + +#ifdef WITH_A2DP + mA2dpMixerThread->setStreamMute(stream, muted); +#endif + if (stream == AudioSystem::MUSIC) + { + AutoMutex lock(&mHardwareLock); + if (mForcedRoute != 0) + mMusicMuteSaved = muted; + else + mHardwareMixerThread->setStreamMute(stream, muted); + } else { + mHardwareMixerThread->setStreamMute(stream, muted); + } + + + return NO_ERROR; } float AudioFlinger::streamVolume(int stream) const { - if (uint32_t(stream) >= AudioTrack::NUM_STREAM_TYPES) { + if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) { return 0.0f; } - if (stream == AudioTrack::VOICE_CALL) { + float value = mHardwareMixerThread->streamVolume(stream); + + if (stream == AudioSystem::VOICE_CALL) { // FIXME: Re-base internally generated in-call audio, // reverse of above in setStreamVolume. - return (mStreamTypes[stream].volume - (1.0 / 6.0)) / (1.0 - 1.0 / 6.0); + value = (value - 0.01) / 0.99; } - return mStreamTypes[stream].volume; + + return value; } bool AudioFlinger::streamMute(int stream) const { - if (uint32_t(stream) >= AudioTrack::NUM_STREAM_TYPES) { + if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) { return true; } - return mStreamTypes[stream].mute; + + if (stream == AudioSystem::MUSIC && mForcedRoute != 0) + { + return mMusicMuteSaved; + } + return mHardwareMixerThread->streamMute(stream); } bool AudioFlinger::isMusicActive() const { - size_t count = mActiveTracks.size(); - for (size_t i = 0 ; i < count ; ++i) { - sp t = mActiveTracks[i].promote(); - if (t == 0) continue; - Track* const track = t.get(); - if (t->mStreamType == AudioTrack::MUSIC) - return true; - } - return false; + #ifdef WITH_A2DP + if (isA2dpEnabled()) { + return mA2dpMixerThread->isMusicActive(); + } + #endif + return mHardwareMixerThread->isMusicActive(); } status_t AudioFlinger::setParameter(const char* key, const char* value) @@ -872,6 +730,8 @@ status_t AudioFlinger::setParameter(const char* key, const char* value) status_t result, result2; AutoMutex lock(mHardwareLock); mHardwareStatus = AUDIO_SET_PARAMETER; + + LOGV("setParameter() key %s, value %s, tid %d, calling tid %d", key, value, gettid(), IPCThreadState::self()->getCallingPid()); result = mAudioHardware->setParameter(key, value); if (mA2dpAudioInterface) { result2 = mA2dpAudioInterface->setParameter(key, value); @@ -882,160 +742,857 @@ status_t AudioFlinger::setParameter(const char* key, const char* value) return result; } -void AudioFlinger::removeClient(pid_t pid) +size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount) { - Mutex::Autolock _l(mLock); - mClients.removeItem(pid); + return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount); } -status_t AudioFlinger::addTrack(const sp& track) +void AudioFlinger::registerClient(const sp& client) { + + LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid()); Mutex::Autolock _l(mLock); - // here the track could be either new, or restarted - // in both cases "unstop" the track - if (track->isPaused()) { - track->mState = TrackBase::RESUMING; - LOGV("PAUSED => RESUMING (%d)", track->name()); - } else { - track->mState = TrackBase::ACTIVE; - LOGV("? => ACTIVE (%d)", track->name()); - } - // set retry count for buffer fill - track->mRetryCount = kMaxTrackStartupRetries; - LOGV("mWaitWorkCV.broadcast"); - mWaitWorkCV.broadcast(); - - if (mActiveTracks.indexOf(track) < 0) { - // the track is newly added, make sure it fills up all its - // buffers before playing. This is to ensure the client will - // effectively get the latency it requested. - track->mFillingUpStatus = Track::FS_FILLING; - track->mResetDone = false; - addActiveTrack(track); - return NO_ERROR; + sp binder = client->asBinder(); + if (mNotificationClients.indexOf(binder) < 0) { + LOGV("Adding notification client %p", binder.get()); + binder->linkToDeath(this); + mNotificationClients.add(binder); + client->a2dpEnabledChanged(isA2dpEnabled()); } - return ALREADY_EXISTS; } -void AudioFlinger::removeTrack(wp track, int name) -{ +void AudioFlinger::binderDied(const wp& who) { + + LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid()); Mutex::Autolock _l(mLock); - sp t = track.promote(); - if (t!=NULL && (t->mState <= TrackBase::STOPPED)) { - remove_track_l(track, name); - } -} -void AudioFlinger::remove_track_l(wp track, int name) -{ - sp t = track.promote(); - if (t!=NULL) { - t->reset(); + IBinder *binder = who.unsafe_get(); + + if (binder != NULL) { + int index = mNotificationClients.indexOf(binder); + if (index >= 0) { + LOGV("Removing notification client %p", binder); + mNotificationClients.removeAt(index); + } } - audioMixer()->deleteTrackName(name); - removeActiveTrack(track); - mWaitWorkCV.broadcast(); } -void AudioFlinger::destroyTrack(const sp& track) +void AudioFlinger::removeClient(pid_t pid) { - // NOTE: We're acquiring a strong reference on the track before - // acquiring the lock, this is to make sure removing it from - // mTracks won't cause the destructor to be called while the lock is - // held (note that technically, 'track' could be a reference to an item - // in mTracks, which is why we need to do this). - sp keep(track); + LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid()); Mutex::Autolock _l(mLock); - track->mState = TrackBase::TERMINATED; - if (mActiveTracks.indexOf(track) < 0) { - LOGV("remove track (%d) and delete from mixer", track->name()); - mTracks.remove(track); - audioMixer()->deleteTrackName(keep->name()); - } + mClients.removeItem(pid); } -void AudioFlinger::addActiveTrack(const wp& t) -{ - mActiveTracks.add(t); +bool AudioFlinger::isA2dpEnabled() const +{ + return mA2dpEnabled; +} + +void AudioFlinger::handleForcedSpeakerRoute(int command) +{ + switch(command) { + case ACTIVE_TRACK_ADDED: + { + AutoMutex lock(mHardwareLock); + if (mForcedSpeakerCount++ == 0) { + mRouteRestoreTime = 0; + mMusicMuteSaved = mHardwareMixerThread->streamMute(AudioSystem::MUSIC); + if (mForcedRoute == 0 && !(mSavedRoute & AudioSystem::ROUTE_SPEAKER)) { + LOGV("Route forced to Speaker ON %08x", mSavedRoute | AudioSystem::ROUTE_SPEAKER); + mHardwareMixerThread->setStreamMute(AudioSystem::MUSIC, true); + mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; + mAudioHardware->setMasterVolume(0); + usleep(mHardwareMixerThread->latency()*1000); + mHardwareStatus = AUDIO_HW_SET_ROUTING; + mAudioHardware->setRouting(AudioSystem::MODE_NORMAL, mSavedRoute | AudioSystem::ROUTE_SPEAKER); + mHardwareStatus = AUDIO_HW_IDLE; + // delay track start so that audio hardware has time to siwtch routes + usleep(kStartSleepTime); + mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; + mAudioHardware->setMasterVolume(mHardwareMixerThread->masterVolume()); + mHardwareStatus = AUDIO_HW_IDLE; + } + mForcedRoute = AudioSystem::ROUTE_SPEAKER; + } + LOGV("mForcedSpeakerCount incremented to %d", mForcedSpeakerCount); + } + break; + case ACTIVE_TRACK_REMOVED: + { + AutoMutex lock(mHardwareLock); + if (mForcedSpeakerCount > 0){ + if (--mForcedSpeakerCount == 0) { + mRouteRestoreTime = systemTime() + milliseconds(kStopSleepTime/1000); + } + LOGV("mForcedSpeakerCount decremented to %d", mForcedSpeakerCount); + } else { + LOGE("mForcedSpeakerCount is already zero"); + } + } + break; + case CHECK_ROUTE_RESTORE_TIME: + case FORCE_ROUTE_RESTORE: + if (mRouteRestoreTime) { + AutoMutex lock(mHardwareLock); + if (mRouteRestoreTime && + (systemTime() > mRouteRestoreTime || command == FORCE_ROUTE_RESTORE)) { + mHardwareMixerThread->setStreamMute(AudioSystem::MUSIC, mMusicMuteSaved); + mForcedRoute = 0; + if (!(mSavedRoute & AudioSystem::ROUTE_SPEAKER)) { + mHardwareStatus = AUDIO_HW_SET_ROUTING; + mAudioHardware->setRouting(AudioSystem::MODE_NORMAL, mSavedRoute); + mHardwareStatus = AUDIO_HW_IDLE; + LOGV("Route forced to Speaker OFF %08x", mSavedRoute); + } + mRouteRestoreTime = 0; + } + } + break; + } +} #ifdef WITH_A2DP - // disable A2DP for certain stream types - sp track = t.promote(); - if (streamDisablesA2dp(track->type())) { - if (mA2dpDisableCount++ == 0 && isA2dpEnabled()) { - setA2dpEnabled(false); - mA2dpSuppressed = true; - LOGD("mA2dpSuppressed = true\n"); +// handleStreamDisablesA2dp_l() must be called with AudioFlinger::mLock held +void AudioFlinger::handleStreamDisablesA2dp_l(int command) +{ + switch(command) { + case ACTIVE_TRACK_ADDED: + { + if (mA2dpDisableCount++ == 0) { + if (mA2dpEnabled) { + setA2dpEnabled_l(false); + mA2dpSuppressed = true; + } + } + LOGV("mA2dpDisableCount incremented to %d", mA2dpDisableCount); } - LOGD("mA2dpDisableCount incremented to %d\n", mA2dpDisableCount); + break; + case ACTIVE_TRACK_REMOVED: + { + if (mA2dpDisableCount > 0) { + if (--mA2dpDisableCount == 0) { + if (mA2dpSuppressed) { + setA2dpEnabled_l(true); + mA2dpSuppressed = false; + } + } + LOGV("mA2dpDisableCount decremented to %d", mA2dpDisableCount); + } else { + LOGE("mA2dpDisableCount is already zero"); + } + } + break; } +} #endif + +// ---------------------------------------------------------------------------- + +AudioFlinger::MixerThread::MixerThread(const sp& audioFlinger, AudioStreamOut* output, int outputType) + : Thread(false), + mAudioFlinger(audioFlinger), mAudioMixer(0), mOutput(output), mOutputType(outputType), + mSampleRate(0), mFrameCount(0), mChannelCount(0), mFormat(0), mMixBuffer(0), + mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mStandby(false), + mInWrite(false) +{ + mSampleRate = output->sampleRate(); + mChannelCount = output->channelCount(); + + // FIXME - Current mixer implementation only supports stereo output + if (mChannelCount == 1) { + LOGE("Invalid audio hardware channel count"); + } + + mFormat = output->format(); + mFrameCount = output->bufferSize() / output->channelCount() / sizeof(int16_t); + mAudioMixer = new AudioMixer(mFrameCount, output->sampleRate()); + + // FIXME - Current mixer implementation only supports stereo output: Always + // Allocate a stereo buffer even if HW output is mono. + mMixBuffer = new int16_t[mFrameCount * 2]; + memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t)); } -void AudioFlinger::removeActiveTrack(const wp& t) +AudioFlinger::MixerThread::~MixerThread() { - mActiveTracks.remove(t); + delete [] mMixBuffer; + delete mAudioMixer; +} + +status_t AudioFlinger::MixerThread::dump(int fd, const Vector& args) +{ + dumpInternals(fd, args); + dumpTracks(fd, args); + return NO_ERROR; +} + +status_t AudioFlinger::MixerThread::dumpTracks(int fd, const Vector& args) +{ + const size_t SIZE = 256; + char buffer[SIZE]; + String8 result; + + snprintf(buffer, SIZE, "Output %d mixer thread tracks\n", mOutputType); + result.append(buffer); + result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n"); + for (size_t i = 0; i < mTracks.size(); ++i) { + wp wTrack = mTracks[i]; + if (wTrack != 0) { + sp track = wTrack.promote(); + if (track != 0) { + track->dump(buffer, SIZE); + result.append(buffer); + } + } + } + + snprintf(buffer, SIZE, "Output %d mixer thread active tracks\n", mOutputType); + result.append(buffer); + result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n"); + for (size_t i = 0; i < mActiveTracks.size(); ++i) { + wp wTrack = mTracks[i]; + if (wTrack != 0) { + sp track = wTrack.promote(); + if (track != 0) { + track->dump(buffer, SIZE); + result.append(buffer); + } + } + } + write(fd, result.string(), result.size()); + return NO_ERROR; +} + +status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector& args) +{ + const size_t SIZE = 256; + char buffer[SIZE]; + String8 result; + + snprintf(buffer, SIZE, "Output %d mixer thread internals\n", mOutputType); + result.append(buffer); + snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); + result.append(buffer); + snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime)); + result.append(buffer); + snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); + result.append(buffer); + snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); + result.append(buffer); + snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); + result.append(buffer); + snprintf(buffer, SIZE, "standby: %d\n", mStandby); + result.append(buffer); + write(fd, result.string(), result.size()); + return NO_ERROR; +} + +// Thread virtuals +bool AudioFlinger::MixerThread::threadLoop() +{ + unsigned long sleepTime = kBufferRecoveryInUsecs; + int16_t* curBuf = mMixBuffer; + Vector< sp > tracksToRemove; + size_t enabledTracks = 0; + nsecs_t standbyTime = systemTime(); + size_t mixBufferSize = mFrameCount*mChannelCount*sizeof(int16_t); + nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2; + #ifdef WITH_A2DP - // disable A2DP for certain stream types - sp track = t.promote(); - if (streamDisablesA2dp(track->type())) { - if (mA2dpDisableCount > 0) { - mA2dpDisableCount--; - if (mA2dpDisableCount == 0 && mA2dpSuppressed) { - setA2dpEnabled(true); - mA2dpSuppressed = false; + bool outputTrackActive = false; +#endif + + do { + enabledTracks = 0; + { // scope for the AudioFlinger::mLock + + Mutex::Autolock _l(mAudioFlinger->mLock); + +#ifdef WITH_A2DP + if (mOutputTrack != NULL && !mAudioFlinger->isA2dpEnabled()) { + if (outputTrackActive) { + mAudioFlinger->mLock.unlock(); + mOutputTrack->stop(); + mAudioFlinger->mLock.lock(); + outputTrackActive = false; + } + } + mAudioFlinger->checkA2dpEnabledChange_l(); +#endif + + const SortedVector< wp >& activeTracks = mActiveTracks; + + // put audio hardware into standby after short delay + if UNLIKELY(!activeTracks.size() && systemTime() > standbyTime) { + // wait until we have something to do... + LOGV("Audio hardware entering standby, output %d\n", mOutputType); + if (!mStandby) { + mOutput->standby(); + mStandby = true; + } + +#ifdef WITH_A2DP + if (outputTrackActive) { + mAudioFlinger->mLock.unlock(); + mOutputTrack->stop(); + mAudioFlinger->mLock.lock(); + outputTrackActive = false; + } +#endif + if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) { + mAudioFlinger->handleForcedSpeakerRoute(FORCE_ROUTE_RESTORE); + } + // we're about to wait, flush the binder command buffer + IPCThreadState::self()->flushCommands(); + mAudioFlinger->mWaitWorkCV.wait(mAudioFlinger->mLock); + LOGV("Audio hardware exiting standby, output %d\n", mOutputType); + + if (mMasterMute == false) { + char value[PROPERTY_VALUE_MAX]; + property_get("ro.audio.silent", value, "0"); + if (atoi(value)) { + LOGD("Silence is golden"); + setMasterMute(true); + } + } + + standbyTime = systemTime() + kStandbyTimeInNsecs; + continue; + } + + // Forced route to speaker is handled by hardware mixer thread + if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) { + mAudioFlinger->handleForcedSpeakerRoute(CHECK_ROUTE_RESTORE_TIME); + } + + // find out which tracks need to be processed + size_t count = activeTracks.size(); + for (size_t i=0 ; i t = activeTracks[i].promote(); + if (t == 0) continue; + + Track* const track = t.get(); + audio_track_cblk_t* cblk = track->cblk(); + + // The first time a track is added we wait + // for all its buffers to be filled before processing it + mAudioMixer->setActiveTrack(track->name()); + if (cblk->framesReady() && (track->isReady() || track->isStopped()) && + !track->isPaused()) + { + //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server); + + // compute volume for this track + int16_t left, right; + if (track->isMuted() || mMasterMute || track->isPausing()) { + left = right = 0; + if (track->isPausing()) { + LOGV("paused(%d)", track->name()); + track->setPaused(); + } + } else { + float typeVolume = mStreamTypes[track->type()].volume; + float v = mMasterVolume * typeVolume; + float v_clamped = v * cblk->volume[0]; + if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; + left = int16_t(v_clamped); + v_clamped = v * cblk->volume[1]; + if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; + right = int16_t(v_clamped); + } + + // XXX: these things DON'T need to be done each time + mAudioMixer->setBufferProvider(track); + mAudioMixer->enable(AudioMixer::MIXING); + + int param; + if ( track->mFillingUpStatus == Track::FS_FILLED) { + // no ramp for the first volume setting + track->mFillingUpStatus = Track::FS_ACTIVE; + if (track->mState == TrackBase::RESUMING) { + track->mState = TrackBase::ACTIVE; + param = AudioMixer::RAMP_VOLUME; + } else { + param = AudioMixer::VOLUME; + } + } else { + param = AudioMixer::RAMP_VOLUME; + } + mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left); + mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right); + mAudioMixer->setParameter( + AudioMixer::TRACK, + AudioMixer::FORMAT, track->format()); + mAudioMixer->setParameter( + AudioMixer::TRACK, + AudioMixer::CHANNEL_COUNT, track->channelCount()); + mAudioMixer->setParameter( + AudioMixer::RESAMPLE, + AudioMixer::SAMPLE_RATE, + int(cblk->sampleRate)); + + // reset retry count + track->mRetryCount = kMaxTrackRetries; + enabledTracks++; + } else { + //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server); + if (track->isStopped()) { + track->reset(); + } + if (track->isTerminated() || track->isStopped() || track->isPaused()) { + // We have consumed all the buffers of this track. + // Remove it from the list of active tracks. + LOGV("remove(%d) from active list", track->name()); + tracksToRemove.add(track); + } else { + // No buffers for this track. Give it a few chances to + // fill a buffer, then remove it from active list. + if (--(track->mRetryCount) <= 0) { + LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); + tracksToRemove.add(track); + } + } + // LOGV("disable(%d)", track->name()); + mAudioMixer->disable(AudioMixer::MIXING); + } + } + + // remove all the tracks that need to be... + count = tracksToRemove.size(); + if (UNLIKELY(count)) { + for (size_t i=0 ; i& track = tracksToRemove[i]; + removeActiveTrack_l(track); + if (track->isTerminated()) { + mTracks.remove(track); + deleteTrackName_l(track->mName); + } + } + } + } + + if (LIKELY(enabledTracks)) { + // mix buffers... + mAudioMixer->process(curBuf); + +#ifdef WITH_A2DP + if (mOutputTrack != NULL && mAudioFlinger->isA2dpEnabled()) { + if (!outputTrackActive) { + LOGV("starting output track in mixer for output %d", mOutputType); + mOutputTrack->start(); + outputTrackActive = true; + } + mOutputTrack->write(curBuf, mFrameCount); + } +#endif + + // output audio to hardware + mLastWriteTime = systemTime(); + mInWrite = true; + mOutput->write(curBuf, mixBufferSize); + mNumWrites++; + mInWrite = false; + mStandby = false; + nsecs_t temp = systemTime(); + standbyTime = temp + kStandbyTimeInNsecs; + nsecs_t delta = temp - mLastWriteTime; + if (delta > maxPeriod) { + LOGW("write blocked for %llu msecs", ns2ms(delta)); + mNumDelayedWrites++; + } + sleepTime = kBufferRecoveryInUsecs; + } else { +#ifdef WITH_A2DP + if (mOutputTrack != NULL && mAudioFlinger->isA2dpEnabled()) { + if (outputTrackActive) { + mOutputTrack->write(curBuf, 0); + if (mOutputTrack->bufferQueueEmpty()) { + mOutputTrack->stop(); + outputTrackActive = false; + } else { + standbyTime = systemTime() + kStandbyTimeInNsecs; + } + } + } +#endif + // There was nothing to mix this round, which means all + // active tracks were late. Sleep a little bit to give + // them another chance. If we're too late, the audio + // hardware will zero-fill for us. + //LOGV("no buffers - usleep(%lu)", sleepTime); + usleep(sleepTime); + if (sleepTime < kMaxBufferRecoveryInUsecs) { + sleepTime += kBufferRecoveryInUsecs; } - LOGD("mA2dpDisableCount decremented to %d\n", mA2dpDisableCount); - } else - LOGE("mA2dpDisableCount is already zero"); + } + + // finally let go of all our tracks, without the lock held + // since we can't guarantee the destructors won't acquire that + // same lock. + tracksToRemove.clear(); + } while (true); + + return false; +} + +status_t AudioFlinger::MixerThread::readyToRun() +{ + if (mSampleRate == 0) { + LOGE("No working audio driver found."); + return NO_INIT; + } + LOGI("AudioFlinger's thread ready to run for output %d", mOutputType); + return NO_ERROR; +} + +void AudioFlinger::MixerThread::onFirstRef() +{ + const size_t SIZE = 256; + char buffer[SIZE]; + + snprintf(buffer, SIZE, "Mixer Thread for output %d", mOutputType); + + run(buffer, ANDROID_PRIORITY_URGENT_AUDIO); +} + +// MixerThread::createTrack_l() must be called with AudioFlinger::mLock held +sp AudioFlinger::MixerThread::createTrack_l( + const sp& client, + int streamType, + uint32_t sampleRate, + int format, + int channelCount, + int frameCount, + const sp& sharedBuffer, + status_t *status) +{ + sp track; + status_t lStatus; + + // Resampler implementation limits input sampling rate to 2 x output sampling rate. + if (sampleRate > MAX_SAMPLE_RATE || sampleRate > mSampleRate*2) { + LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate); + lStatus = BAD_VALUE; + goto Exit; + } + + + if (mSampleRate == 0) { + LOGE("Audio driver not initialized."); + lStatus = NO_INIT; + goto Exit; + } + + track = new Track(this, client, streamType, sampleRate, format, + channelCount, frameCount, sharedBuffer); + if (track->getCblk() == NULL) { + lStatus = NO_MEMORY; + goto Exit; + } + mTracks.add(track); + lStatus = NO_ERROR; + +Exit: + if(status) { + *status = lStatus; + } + return track; +} + +// getTracks_l() must be called with AudioFlinger::mLock held +void AudioFlinger::MixerThread::getTracks_l( + SortedVector < sp >& tracks, + SortedVector < wp >& activeTracks) +{ + size_t size = mTracks.size(); + LOGV ("MixerThread::getTracks_l() for output %d, mTracks.size %d, mActiveTracks.size %d", mOutputType, mTracks.size(), mActiveTracks.size()); + for (size_t i = 0; i < size; i++) { + sp t = mTracks[i]; + if (AudioSystem::routedToA2dpOutput(t->mStreamType)) { + tracks.add(t); + int j = mActiveTracks.indexOf(t); + if (j >= 0) { + t = mActiveTracks[j].promote(); + if (t != NULL) { + activeTracks.add(t); + } + } + } + } + + size = activeTracks.size(); + for (size_t i = 0; i < size; i++) { + removeActiveTrack_l(activeTracks[i]); + } + + size = tracks.size(); + for (size_t i = 0; i < size; i++) { + sp t = tracks[i]; + mTracks.remove(t); + deleteTrackName_l(t->name()); + } +} + +// putTracks_l() must be called with AudioFlinger::mLock held +void AudioFlinger::MixerThread::putTracks_l( + SortedVector < sp >& tracks, + SortedVector < wp >& activeTracks) +{ + + LOGV ("MixerThread::putTracks_l() for output %d, tracks.size %d, activeTracks.size %d", mOutputType, tracks.size(), activeTracks.size()); + + size_t size = tracks.size(); + for (size_t i = 0; i < size ; i++) { + sp t = tracks[i]; + int name = getTrackName_l(); + + if (name < 0) return; + + t->mName = name; + t->mMixerThread = this; + mTracks.add(t); + + int j = activeTracks.indexOf(t); + if (j >= 0) { + addActiveTrack_l(t); + } + } +} + +uint32_t AudioFlinger::MixerThread::sampleRate() const +{ + return mSampleRate; +} + +int AudioFlinger::MixerThread::channelCount() const +{ + return mChannelCount; +} + +int AudioFlinger::MixerThread::format() const +{ + return mFormat; +} + +size_t AudioFlinger::MixerThread::frameCount() const +{ + return mFrameCount; +} + +uint32_t AudioFlinger::MixerThread::latency() const +{ + if (mOutput) { + return mOutput->latency(); + } + else { + return 0; } +} + +status_t AudioFlinger::MixerThread::setMasterVolume(float value) +{ + mMasterVolume = value; + return NO_ERROR; +} + +status_t AudioFlinger::MixerThread::setMasterMute(bool muted) +{ + mMasterMute = muted; + return NO_ERROR; +} + +float AudioFlinger::MixerThread::masterVolume() const +{ + return mMasterVolume; +} + +bool AudioFlinger::MixerThread::masterMute() const +{ + return mMasterMute; +} + +status_t AudioFlinger::MixerThread::setStreamVolume(int stream, float value) +{ + mStreamTypes[stream].volume = value; + return NO_ERROR; +} + +status_t AudioFlinger::MixerThread::setStreamMute(int stream, bool muted) +{ + mStreamTypes[stream].mute = muted; + return NO_ERROR; +} + +float AudioFlinger::MixerThread::streamVolume(int stream) const +{ + return mStreamTypes[stream].volume; +} + +bool AudioFlinger::MixerThread::streamMute(int stream) const +{ + return mStreamTypes[stream].mute; +} + +bool AudioFlinger::MixerThread::isMusicActive() const +{ + size_t count = mActiveTracks.size(); + for (size_t i = 0 ; i < count ; ++i) { + sp t = mActiveTracks[i].promote(); + if (t == 0) continue; + Track* const track = t.get(); + if (t->mStreamType == AudioSystem::MUSIC) + return true; + } + return false; +} + +// addTrack_l() must be called with AudioFlinger::mLock held +status_t AudioFlinger::MixerThread::addTrack_l(const sp& track) +{ + status_t status = ALREADY_EXISTS; + + // here the track could be either new, or restarted + // in both cases "unstop" the track + if (track->isPaused()) { + track->mState = TrackBase::RESUMING; + LOGV("PAUSED => RESUMING (%d)", track->name()); + } else { + track->mState = TrackBase::ACTIVE; + LOGV("? => ACTIVE (%d)", track->name()); + } + // set retry count for buffer fill + track->mRetryCount = kMaxTrackStartupRetries; + if (mActiveTracks.indexOf(track) < 0) { + // the track is newly added, make sure it fills up all its + // buffers before playing. This is to ensure the client will + // effectively get the latency it requested. + track->mFillingUpStatus = Track::FS_FILLING; + track->mResetDone = false; + addActiveTrack_l(track); + status = NO_ERROR; + } + + LOGV("mWaitWorkCV.broadcast"); + mAudioFlinger->mWaitWorkCV.broadcast(); + + return status; +} + +// removeTrack_l() must be called with AudioFlinger::mLock held +void AudioFlinger::MixerThread::removeTrack_l(wp track, int name) +{ + sp t = track.promote(); + if (t!=NULL && (t->mState <= TrackBase::STOPPED)) { + t->reset(); + deleteTrackName_l(name); + removeActiveTrack_l(track); + mAudioFlinger->mWaitWorkCV.broadcast(); + } +} + +// destroyTrack_l() must be called with AudioFlinger::mLock held +void AudioFlinger::MixerThread::destroyTrack_l(const sp& track) +{ + track->mState = TrackBase::TERMINATED; + if (mActiveTracks.indexOf(track) < 0) { + LOGV("remove track (%d) and delete from mixer", track->name()); + mTracks.remove(track); + deleteTrackName_l(track->name()); + } +} + +// addActiveTrack_l() must be called with AudioFlinger::mLock held +void AudioFlinger::MixerThread::addActiveTrack_l(const wp& t) +{ + mActiveTracks.add(t); + + // Force routing to speaker for certain stream types + // The forced routing to speaker is managed by hardware mixer + if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) { + sp track = t.promote(); + if (track == NULL) return; + + if (streamForcedToSpeaker(track->type())) { + mAudioFlinger->handleForcedSpeakerRoute(ACTIVE_TRACK_ADDED); + } +#ifdef WITH_A2DP + // AudioFlinger::mLock must be locked before calling + // handleStreamDisablesA2dp_l because it calls setA2dpEnabled_l(). + if (streamDisablesA2dp(track->type())) { + mAudioFlinger->handleStreamDisablesA2dp_l(ACTIVE_TRACK_ADDED); + } #endif + } } -// ---------------------------------------------------------------------------- +// removeActiveTrack_l() must be called with AudioFlinger::mLock held +void AudioFlinger::MixerThread::removeActiveTrack_l(const wp& t) +{ + mActiveTracks.remove(t); -AudioFlinger::Client::Client(const sp& audioFlinger, pid_t pid) - : RefBase(), - mAudioFlinger(audioFlinger), - mMemoryDealer(new MemoryDealer(1024*1024)), - mPid(pid) + // Force routing to speaker for certain stream types + // The forced routing to speaker is managed by hardware mixer + if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) { + sp track = t.promote(); + if (track == NULL) return; + + if (streamForcedToSpeaker(track->type())) { + mAudioFlinger->handleForcedSpeakerRoute(ACTIVE_TRACK_REMOVED); + } +#ifdef WITH_A2DP + // AudioFlinger::mLock must be locked before calling + // handleStreamDisablesA2dp_l because it calls setA2dpEnabled_l(). + if (streamDisablesA2dp(track->type())) { + mAudioFlinger->handleStreamDisablesA2dp_l(ACTIVE_TRACK_REMOVED); + } +#endif + } +} + +// getTrackName_l() must be called with AudioFlinger::mLock held +int AudioFlinger::MixerThread::getTrackName_l() { - // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer + return mAudioMixer->getTrackName(); } -AudioFlinger::Client::~Client() +// deleteTrackName_l() must be called with AudioFlinger::mLock held +void AudioFlinger::MixerThread::deleteTrackName_l(int name) { - mAudioFlinger->removeClient(mPid); + mAudioMixer->deleteTrackName(name); } -const sp& AudioFlinger::Client::heap() const +size_t AudioFlinger::MixerThread::getOutputFrameCount() { - return mMemoryDealer; + return mOutput->bufferSize() / mOutput->channelCount() / sizeof(int16_t); } // ---------------------------------------------------------------------------- -AudioFlinger::TrackBase::TrackBase( - const sp& audioFlinger, +// TrackBase constructor must be called with AudioFlinger::mLock held +AudioFlinger::MixerThread::TrackBase::TrackBase( + const sp& mixerThread, const sp& client, int streamType, uint32_t sampleRate, int format, int channelCount, int frameCount, + uint32_t flags, const sp& sharedBuffer) : RefBase(), - mAudioFlinger(audioFlinger), + mMixerThread(mixerThread), mClient(client), mStreamType(streamType), mFrameCount(0), mState(IDLE), mClientTid(-1), mFormat(format), - mFlags(0) + mFlags(flags & ~SYSTEM_FLAGS_MASK) { - mName = audioFlinger->audioMixer()->getTrackName(); + mName = mixerThread->getTrackName_l(); + LOGV("TrackBase contructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid()); if (mName < 0) { LOGE("no more track names availlable"); return; @@ -1043,7 +1600,6 @@ AudioFlinger::TrackBase::TrackBase( LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size()); - // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize); size_t size = sizeof(audio_track_cblk_t); size_t bufferSize = frameCount*channelCount*sizeof(int16_t); @@ -1051,41 +1607,60 @@ AudioFlinger::TrackBase::TrackBase( size += bufferSize; } - mCblkMemory = client->heap()->allocate(size); - if (mCblkMemory != 0) { - mCblk = static_cast(mCblkMemory->pointer()); - if (mCblk) { // construct the shared structure in-place. - new(mCblk) audio_track_cblk_t(); - // clear all buffers - mCblk->frameCount = frameCount; - mCblk->sampleRate = sampleRate; - mCblk->channels = channelCount; - if (sharedBuffer == 0) { - mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); - memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t)); - // Force underrun condition to avoid false underrun callback until first data is - // written to buffer - mCblk->flowControlFlag = 1; - } else { - mBuffer = sharedBuffer->pointer(); + if (client != NULL) { + mCblkMemory = client->heap()->allocate(size); + if (mCblkMemory != 0) { + mCblk = static_cast(mCblkMemory->pointer()); + if (mCblk) { // construct the shared structure in-place. + new(mCblk) audio_track_cblk_t(); + // clear all buffers + mCblk->frameCount = frameCount; + mCblk->sampleRate = sampleRate; + mCblk->channels = channelCount; + if (sharedBuffer == 0) { + mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); + memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t)); + // Force underrun condition to avoid false underrun callback until first data is + // written to buffer + mCblk->flowControlFlag = 1; + } else { + mBuffer = sharedBuffer->pointer(); + } + mBufferEnd = (uint8_t *)mBuffer + bufferSize; } - mBufferEnd = (uint8_t *)mBuffer + bufferSize; - } - } else { - LOGE("not enough memory for AudioTrack size=%u", size); - client->heap()->dump("AudioTrack"); - return; - } + } else { + LOGE("not enough memory for AudioTrack size=%u", size); + client->heap()->dump("AudioTrack"); + return; + } + } else { + mCblk = (audio_track_cblk_t *)(new uint8_t[size]); + if (mCblk) { // construct the shared structure in-place. + new(mCblk) audio_track_cblk_t(); + // clear all buffers + mCblk->frameCount = frameCount; + mCblk->sampleRate = sampleRate; + mCblk->channels = channelCount; + mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); + memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t)); + // Force underrun condition to avoid false underrun callback until first data is + // written to buffer + mCblk->flowControlFlag = 1; + mBufferEnd = (uint8_t *)mBuffer + bufferSize; + } + } } -AudioFlinger::TrackBase::~TrackBase() +AudioFlinger::MixerThread::TrackBase::~TrackBase() { - mCblk->~audio_track_cblk_t(); // destroy our shared-structure. + if (mCblk) { + mCblk->~audio_track_cblk_t(); // destroy our shared-structure. + } mCblkMemory.clear(); // and free the shared memory mClient.clear(); } -void AudioFlinger::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) +void AudioFlinger::MixerThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) { buffer->raw = 0; mFrameCount = buffer->frameCount; @@ -1093,7 +1668,7 @@ void AudioFlinger::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) buffer->frameCount = 0; } -bool AudioFlinger::TrackBase::step() { +bool AudioFlinger::MixerThread::TrackBase::step() { bool result; audio_track_cblk_t* cblk = this->cblk(); @@ -1105,31 +1680,31 @@ bool AudioFlinger::TrackBase::step() { return result; } -void AudioFlinger::TrackBase::reset() { +void AudioFlinger::MixerThread::TrackBase::reset() { audio_track_cblk_t* cblk = this->cblk(); cblk->user = 0; cblk->server = 0; cblk->userBase = 0; cblk->serverBase = 0; - mFlags = 0; + mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK); LOGV("TrackBase::reset"); } -sp AudioFlinger::TrackBase::getCblk() const +sp AudioFlinger::MixerThread::TrackBase::getCblk() const { return mCblkMemory; } -int AudioFlinger::TrackBase::sampleRate() const { +int AudioFlinger::MixerThread::TrackBase::sampleRate() const { return mCblk->sampleRate; } -int AudioFlinger::TrackBase::channelCount() const { +int AudioFlinger::MixerThread::TrackBase::channelCount() const { return mCblk->channels; } -void* AudioFlinger::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const { +void* AudioFlinger::MixerThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const { audio_track_cblk_t* cblk = this->cblk(); int16_t *bufferStart = (int16_t *)mBuffer + (offset-cblk->serverBase)*cblk->channels; int16_t *bufferEnd = bufferStart + frames * cblk->channels; @@ -1148,8 +1723,9 @@ void* AudioFlinger::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const // ---------------------------------------------------------------------------- -AudioFlinger::Track::Track( - const sp& audioFlinger, +// Track constructor must be called with AudioFlinger::mLock held +AudioFlinger::MixerThread::Track::Track( + const sp& mixerThread, const sp& client, int streamType, uint32_t sampleRate, @@ -1157,7 +1733,7 @@ AudioFlinger::Track::Track( int channelCount, int frameCount, const sp& sharedBuffer) - : TrackBase(audioFlinger, client, streamType, sampleRate, format, channelCount, frameCount, sharedBuffer) + : TrackBase(mixerThread, client, streamType, sampleRate, format, channelCount, frameCount, 0, sharedBuffer) { mVolume[0] = 1.0f; mVolume[1] = 1.0f; @@ -1165,23 +1741,36 @@ AudioFlinger::Track::Track( mSharedBuffer = sharedBuffer; } -AudioFlinger::Track::~Track() +AudioFlinger::MixerThread::Track::~Track() { wp weak(this); // never create a strong ref from the dtor + Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock); mState = TERMINATED; - mAudioFlinger->removeTrack(weak, mName); + mMixerThread->removeTrack_l(weak, mName); } -void AudioFlinger::Track::destroy() +void AudioFlinger::MixerThread::Track::destroy() { - mAudioFlinger->destroyTrack(this); + // NOTE: destroyTrack_l() can remove a strong reference to this Track + // by removing it from mTracks vector, so there is a risk that this Tracks's + // desctructor is called. As the destructor needs to lock AudioFlinger::mLock, + // we must acquire a strong reference on this Track before locking AudioFlinger::mLock + // here so that the destructor is called only when exiting this function. + // On the other hand, as long as Track::destroy() is only called by + // TrackHandle destructor, the TrackHandle still holds a strong ref on + // this Track with its member mTrack. + sp keep(this); + { // scope for AudioFlinger::mLock + Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock); + mMixerThread->destroyTrack_l(this); + } } -void AudioFlinger::Track::dump(char* buffer, size_t size) +void AudioFlinger::MixerThread::Track::dump(char* buffer, size_t size) { snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n", mName - AudioMixer::TRACK0, - mClient->pid(), + (mClient == NULL) ? getpid() : mClient->pid(), mStreamType, mFormat, mCblk->channels, @@ -1196,7 +1785,7 @@ void AudioFlinger::Track::dump(char* buffer, size_t size) mCblk->user); } -status_t AudioFlinger::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer) +status_t AudioFlinger::MixerThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer) { audio_track_cblk_t* cblk = this->cblk(); uint32_t framesReady; @@ -1236,53 +1825,55 @@ getNextBuffer_exit: return NOT_ENOUGH_DATA; } -bool AudioFlinger::Track::isReady() const { +bool AudioFlinger::MixerThread::Track::isReady() const { if (mFillingUpStatus != FS_FILLING) return true; if (mCblk->framesReady() >= mCblk->frameCount || mCblk->forceReady) { mFillingUpStatus = FS_FILLED; mCblk->forceReady = 0; + LOGV("Track::isReady() track %d for output %d", mName, mMixerThread->mOutputType); return true; } return false; } -status_t AudioFlinger::Track::start() +status_t AudioFlinger::MixerThread::Track::start() { - LOGV("start(%d)", mName); - mAudioFlinger->addTrack(this); + LOGV("start(%d), calling thread %d for output %d", mName, IPCThreadState::self()->getCallingPid(), mMixerThread->mOutputType); + Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock); + mMixerThread->addTrack_l(this); return NO_ERROR; } -void AudioFlinger::Track::stop() +void AudioFlinger::MixerThread::Track::stop() { - LOGV("stop(%d)", mName); - Mutex::Autolock _l(mAudioFlinger->mLock); + LOGV("stop(%d), calling thread %d for output %d", mName, IPCThreadState::self()->getCallingPid(), mMixerThread->mOutputType); + Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock); if (mState > STOPPED) { mState = STOPPED; // If the track is not active (PAUSED and buffers full), flush buffers - if (mAudioFlinger->mActiveTracks.indexOf(this) < 0) { + if (mMixerThread->mActiveTracks.indexOf(this) < 0) { reset(); } LOGV("(> STOPPED) => STOPPED (%d)", mName); } } -void AudioFlinger::Track::pause() +void AudioFlinger::MixerThread::Track::pause() { - LOGV("pause(%d)", mName); - Mutex::Autolock _l(mAudioFlinger->mLock); + LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid()); + Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock); if (mState == ACTIVE || mState == RESUMING) { mState = PAUSING; LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName); } } -void AudioFlinger::Track::flush() +void AudioFlinger::MixerThread::Track::flush() { LOGV("flush(%d)", mName); - Mutex::Autolock _l(mAudioFlinger->mLock); + Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock); if (mState != STOPPED && mState != PAUSED && mState != PAUSING) { return; } @@ -1298,7 +1889,7 @@ void AudioFlinger::Track::flush() reset(); } -void AudioFlinger::Track::reset() +void AudioFlinger::MixerThread::Track::reset() { // Do not reset twice to avoid discarding data written just after a flush and before // the audioflinger thread detects the track is stopped. @@ -1313,12 +1904,12 @@ void AudioFlinger::Track::reset() } } -void AudioFlinger::Track::mute(bool muted) +void AudioFlinger::MixerThread::Track::mute(bool muted) { mMute = muted; } -void AudioFlinger::Track::setVolume(float left, float right) +void AudioFlinger::MixerThread::Track::setVolume(float left, float right) { mVolume[0] = left; mVolume[1] = right; @@ -1326,7 +1917,292 @@ void AudioFlinger::Track::setVolume(float left, float right) // ---------------------------------------------------------------------------- -AudioFlinger::TrackHandle::TrackHandle(const sp& track) +// RecordTrack constructor must be called with AudioFlinger::mLock held +AudioFlinger::MixerThread::RecordTrack::RecordTrack( + const sp& mixerThread, + const sp& client, + int streamType, + uint32_t sampleRate, + int format, + int channelCount, + int frameCount, + uint32_t flags) + : TrackBase(mixerThread, client, streamType, sampleRate, format, + channelCount, frameCount, flags, 0), + mOverflow(false) +{ +} + +AudioFlinger::MixerThread::RecordTrack::~RecordTrack() +{ + Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock); + mMixerThread->deleteTrackName_l(mName); +} + +status_t AudioFlinger::MixerThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer) +{ + audio_track_cblk_t* cblk = this->cblk(); + uint32_t framesAvail; + uint32_t framesReq = buffer->frameCount; + + // Check if last stepServer failed, try to step now + if (mFlags & TrackBase::STEPSERVER_FAILED) { + if (!step()) goto getNextBuffer_exit; + LOGV("stepServer recovered"); + mFlags &= ~TrackBase::STEPSERVER_FAILED; + } + + framesAvail = cblk->framesAvailable_l(); + + if (LIKELY(framesAvail)) { + uint32_t s = cblk->server; + uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; + + if (framesReq > framesAvail) { + framesReq = framesAvail; + } + if (s + framesReq > bufferEnd) { + framesReq = bufferEnd - s; + } + + buffer->raw = getBuffer(s, framesReq); + if (buffer->raw == 0) goto getNextBuffer_exit; + + buffer->frameCount = framesReq; + return NO_ERROR; + } + +getNextBuffer_exit: + buffer->raw = 0; + buffer->frameCount = 0; + return NOT_ENOUGH_DATA; +} + +status_t AudioFlinger::MixerThread::RecordTrack::start() +{ + return mMixerThread->mAudioFlinger->startRecord(this); +} + +void AudioFlinger::MixerThread::RecordTrack::stop() +{ + mMixerThread->mAudioFlinger->stopRecord(this); + TrackBase::reset(); + // Force overerrun condition to avoid false overrun callback until first data is + // read from buffer + mCblk->flowControlFlag = 1; +} + + +// ---------------------------------------------------------------------------- + +AudioFlinger::MixerThread::OutputTrack::OutputTrack( + const sp& mixerThread, + uint32_t sampleRate, + int format, + int channelCount, + int frameCount) + : Track(mixerThread, NULL, AudioSystem::SYSTEM, sampleRate, format, channelCount, frameCount, NULL), + mOutputMixerThread(mixerThread) +{ + + mCblk->out = 1; + mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t); + mCblk->volume[0] = mCblk->volume[1] = 0x1000; + mOutBuffer.frameCount = 0; + mCblk->bufferTimeoutMs = 10; + + LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p", + mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd); + +} + +AudioFlinger::MixerThread::OutputTrack::~OutputTrack() +{ + stop(); +} + +status_t AudioFlinger::MixerThread::OutputTrack::start() +{ + status_t status = Track::start(); + + mRetryCount = 127; + return status; +} + +void AudioFlinger::MixerThread::OutputTrack::stop() +{ + Track::stop(); + clearBufferQueue(); + mOutBuffer.frameCount = 0; +} + +void AudioFlinger::MixerThread::OutputTrack::write(int16_t* data, uint32_t frames) +{ + Buffer *pInBuffer; + Buffer inBuffer; + uint32_t channels = mCblk->channels; + + inBuffer.frameCount = frames; + inBuffer.i16 = data; + + if (mCblk->user == 0) { + if (mOutputMixerThread->isMusicActive()) { + mCblk->forceReady = 1; + LOGV("OutputTrack::start() force ready"); + } else if (mCblk->frameCount > frames){ + if (mBufferQueue.size() < kMaxOutputTrackBuffers) { + uint32_t startFrames = (mCblk->frameCount - frames); + LOGV("OutputTrack::start() write %d frames", startFrames); + pInBuffer = new Buffer; + pInBuffer->mBuffer = new int16_t[startFrames * channels]; + pInBuffer->frameCount = startFrames; + pInBuffer->i16 = pInBuffer->mBuffer; + memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t)); + mBufferQueue.add(pInBuffer); + } else { + LOGW ("OutputTrack::write() no more buffers"); + } + } + } + + while (1) { + // First write pending buffers, then new data + if (mBufferQueue.size()) { + pInBuffer = mBufferQueue.itemAt(0); + } else { + pInBuffer = &inBuffer; + } + + if (pInBuffer->frameCount == 0) { + break; + } + + if (mOutBuffer.frameCount == 0) { + mOutBuffer.frameCount = pInBuffer->frameCount; + if (obtainBuffer(&mOutBuffer) == (status_t)AudioTrack::NO_MORE_BUFFERS) { + break; + } + } + + uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount; + memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t)); + mCblk->stepUser(outFrames); + pInBuffer->frameCount -= outFrames; + pInBuffer->i16 += outFrames * channels; + mOutBuffer.frameCount -= outFrames; + mOutBuffer.i16 += outFrames * channels; + + if (pInBuffer->frameCount == 0) { + if (mBufferQueue.size()) { + mBufferQueue.removeAt(0); + delete [] pInBuffer->mBuffer; + delete pInBuffer; + } else { + break; + } + } + } + + // If we could not write all frames, allocate a buffer and queue it for next time. + if (inBuffer.frameCount) { + if (mBufferQueue.size() < kMaxOutputTrackBuffers) { + pInBuffer = new Buffer; + pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels]; + pInBuffer->frameCount = inBuffer.frameCount; + pInBuffer->i16 = pInBuffer->mBuffer; + memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t)); + mBufferQueue.add(pInBuffer); + } else { + LOGW("OutputTrack::write() no more buffers"); + } + } + + // Calling write() with a 0 length buffer, means that no more data will be written: + // If no more buffers are pending, fill output track buffer to make sure it is started + // by output mixer. + if (frames == 0 && mBufferQueue.size() == 0 && mCblk->user < mCblk->frameCount) { + frames = mCblk->frameCount - mCblk->user; + pInBuffer = new Buffer; + pInBuffer->mBuffer = new int16_t[frames * channels]; + pInBuffer->frameCount = frames; + pInBuffer->i16 = pInBuffer->mBuffer; + memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t)); + mBufferQueue.add(pInBuffer); + } + +} + +status_t AudioFlinger::MixerThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer) +{ + int active; + int timeout = 0; + status_t result; + audio_track_cblk_t* cblk = mCblk; + uint32_t framesReq = buffer->frameCount; + + LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server); + buffer->frameCount = 0; + + uint32_t framesAvail = cblk->framesAvailable(); + + if (framesAvail == 0) { + return AudioTrack::NO_MORE_BUFFERS; + } + + if (framesReq > framesAvail) { + framesReq = framesAvail; + } + + uint32_t u = cblk->user; + uint32_t bufferEnd = cblk->userBase + cblk->frameCount; + + if (u + framesReq > bufferEnd) { + framesReq = bufferEnd - u; + } + + buffer->frameCount = framesReq; + buffer->raw = (void *)cblk->buffer(u); + return NO_ERROR; +} + + +void AudioFlinger::MixerThread::OutputTrack::clearBufferQueue() +{ + size_t size = mBufferQueue.size(); + Buffer *pBuffer; + + for (size_t i = 0; i < size; i++) { + pBuffer = mBufferQueue.itemAt(i); + delete [] pBuffer->mBuffer; + delete pBuffer; + } + mBufferQueue.clear(); +} + +// ---------------------------------------------------------------------------- + +AudioFlinger::Client::Client(const sp& audioFlinger, pid_t pid) + : RefBase(), + mAudioFlinger(audioFlinger), + mMemoryDealer(new MemoryDealer(1024*1024)), + mPid(pid) +{ + // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer +} + +AudioFlinger::Client::~Client() +{ + mAudioFlinger->removeClient(mPid); +} + +const sp& AudioFlinger::Client::heap() const +{ + return mMemoryDealer; +} + +// ---------------------------------------------------------------------------- + +AudioFlinger::TrackHandle::TrackHandle(const sp& track) : BnAudioTrack(), mTrack(track) { @@ -1386,8 +2262,7 @@ sp AudioFlinger::openRecord( uint32_t flags, status_t *status) { - sp thread; - sp recordTrack; + sp recordTrack; sp recordHandle; sp client; wp wclient; @@ -1414,12 +2289,6 @@ sp AudioFlinger::openRecord( goto Exit; } - if (mSampleRate == 0) { - LOGE("Audio driver not initialized"); - lStatus = NO_INIT; - goto Exit; - } - if (mAudioRecordThread == 0) { LOGE("Audio record thread not started"); lStatus = NO_INIT; @@ -1436,7 +2305,7 @@ sp AudioFlinger::openRecord( } // add client to list - { + { // scope for mLock Mutex::Autolock _l(mLock); wclient = mClients.valueFor(pid); if (wclient != NULL) { @@ -1445,15 +2314,20 @@ sp AudioFlinger::openRecord( client = new Client(this, pid); mClients.add(pid, client); } - } - - // frameCount must be a multiple of input buffer size - inFrameCount = inputBufferSize/channelCount/sizeof(short); - frameCount = ((frameCount - 1)/inFrameCount + 1) * inFrameCount; - // create new record track and pass to record thread - recordTrack = new RecordTrack(this, client, streamType, sampleRate, - format, channelCount, frameCount); + // frameCount must be a multiple of input buffer size + inFrameCount = inputBufferSize/channelCount/sizeof(short); + frameCount = ((frameCount - 1)/inFrameCount + 1) * inFrameCount; + + // create new record track. The record track uses one track in mHardwareMixerThread by convention. + recordTrack = new MixerThread::RecordTrack(mHardwareMixerThread, client, streamType, sampleRate, + format, channelCount, frameCount, flags); + } + if (recordTrack->getCblk() == NULL) { + recordTrack.clear(); + lStatus = NO_MEMORY; + goto Exit; + } // return to handle to client recordHandle = new RecordHandle(recordTrack); @@ -1466,97 +2340,22 @@ Exit: return recordHandle; } -status_t AudioFlinger::startRecord(RecordTrack* recordTrack) { +status_t AudioFlinger::startRecord(MixerThread::RecordTrack* recordTrack) { if (mAudioRecordThread != 0) { return mAudioRecordThread->start(recordTrack); } return NO_INIT; } -void AudioFlinger::stopRecord(RecordTrack* recordTrack) { +void AudioFlinger::stopRecord(MixerThread::RecordTrack* recordTrack) { if (mAudioRecordThread != 0) { mAudioRecordThread->stop(recordTrack); } } - -// ---------------------------------------------------------------------------- - -AudioFlinger::RecordTrack::RecordTrack( - const sp& audioFlinger, - const sp& client, - int streamType, - uint32_t sampleRate, - int format, - int channelCount, - int frameCount) - : TrackBase(audioFlinger, client, streamType, sampleRate, format, - channelCount, frameCount, 0), - mOverflow(false) -{ -} - -AudioFlinger::RecordTrack::~RecordTrack() -{ - mAudioFlinger->audioMixer()->deleteTrackName(mName); -} - -status_t AudioFlinger::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer) -{ - audio_track_cblk_t* cblk = this->cblk(); - uint32_t framesAvail; - uint32_t framesReq = buffer->frameCount; - - // Check if last stepServer failed, try to step now - if (mFlags & TrackBase::STEPSERVER_FAILED) { - if (!step()) goto getNextBuffer_exit; - LOGV("stepServer recovered"); - mFlags &= ~TrackBase::STEPSERVER_FAILED; - } - - framesAvail = cblk->framesAvailable_l(); - - if (LIKELY(framesAvail)) { - uint32_t s = cblk->server; - uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; - - if (framesReq > framesAvail) { - framesReq = framesAvail; - } - if (s + framesReq > bufferEnd) { - framesReq = bufferEnd - s; - } - - buffer->raw = getBuffer(s, framesReq); - if (buffer->raw == 0) goto getNextBuffer_exit; - - buffer->frameCount = framesReq; - return NO_ERROR; - } - -getNextBuffer_exit: - buffer->raw = 0; - buffer->frameCount = 0; - return NOT_ENOUGH_DATA; -} - -status_t AudioFlinger::RecordTrack::start() -{ - return mAudioFlinger->startRecord(this); -} - -void AudioFlinger::RecordTrack::stop() -{ - mAudioFlinger->stopRecord(this); - TrackBase::reset(); - // Force overerrun condition to avoid false overrun callback until first data is - // read from buffer - mCblk->flowControlFlag = 1; -} - // ---------------------------------------------------------------------------- -AudioFlinger::RecordHandle::RecordHandle(const sp& recordTrack) +AudioFlinger::RecordHandle::RecordHandle(const sp& recordTrack) : BnAudioRecord(), mRecordTrack(recordTrack) { @@ -1588,8 +2387,10 @@ status_t AudioFlinger::RecordHandle::onTransact( // ---------------------------------------------------------------------------- -AudioFlinger::AudioRecordThread::AudioRecordThread(AudioHardwareInterface* audioHardware) : +AudioFlinger::AudioRecordThread::AudioRecordThread(AudioHardwareInterface* audioHardware, + const sp& audioFlinger) : mAudioHardware(audioHardware), + mAudioFlinger(audioFlinger), mActive(false) { } @@ -1619,15 +2420,17 @@ bool AudioFlinger::AudioRecordThread::threadLoop() input = 0; } mRecordTrack.clear(); + mStopped.signal(); mWaitWorkCV.wait(mLock); LOGV("AudioRecordThread: loop starting"); if (mRecordTrack != 0) { input = mAudioHardware->openInputStream(mRecordTrack->format(), - mRecordTrack->channelCount(), - mRecordTrack->sampleRate(), - &mStartStatus); + mRecordTrack->channelCount(), + mRecordTrack->sampleRate(), + &mStartStatus, + (AudioSystem::audio_in_acoustics)(mRecordTrack->mFlags >> 16)); if (input != 0) { inBufferSize = input->bufferSize(); inFrameCount = inBufferSize/input->frameSize(); @@ -1643,12 +2446,14 @@ bool AudioFlinger::AudioRecordThread::threadLoop() mWaitWorkCV.signal(); } mLock.unlock(); - } else if (mRecordTrack != 0){ + } else if (mRecordTrack != 0) { buffer.frameCount = inFrameCount; - if (LIKELY(mRecordTrack->getNextBuffer(&buffer) == NO_ERROR)) { + if (LIKELY(mRecordTrack->getNextBuffer(&buffer) == NO_ERROR && + (int)buffer.frameCount == inFrameCount)) { LOGV("AudioRecordThread read: %d frames", buffer.frameCount); - if (input->read(buffer.raw, inBufferSize) < 0) { + ssize_t bytesRead = input->read(buffer.raw, inBufferSize); + if (bytesRead < 0) { LOGE("Error reading audio input"); sleep(1); } @@ -1677,7 +2482,7 @@ bool AudioFlinger::AudioRecordThread::threadLoop() return false; } -status_t AudioFlinger::AudioRecordThread::start(RecordTrack* recordTrack) +status_t AudioFlinger::AudioRecordThread::start(MixerThread::RecordTrack* recordTrack) { LOGV("AudioRecordThread::start"); AutoMutex lock(&mLock); @@ -1690,6 +2495,19 @@ status_t AudioFlinger::AudioRecordThread::start(RecordTrack* recordTrack) mRecordTrack = recordTrack; +#ifdef WITH_A2DP + { // scope for lock2 + + // AudioFlinger::mLock must be locked before calling + // handleStreamDisablesA2dp_l because it calls setA2dpEnabled_l(). + AutoMutex lock2(&mAudioFlinger->mLock); + + // Currently there is no way to detect if we are recording over SCO, + // so we disable A2DP during any recording. + mAudioFlinger->handleStreamDisablesA2dp_l(ACTIVE_TRACK_ADDED); + } +#endif + // signal thread to start LOGV("Signal record thread"); mWaitWorkCV.signal(); @@ -1698,11 +2516,24 @@ status_t AudioFlinger::AudioRecordThread::start(RecordTrack* recordTrack) return mStartStatus; } -void AudioFlinger::AudioRecordThread::stop(RecordTrack* recordTrack) { +void AudioFlinger::AudioRecordThread::stop(MixerThread::RecordTrack* recordTrack) { LOGV("AudioRecordThread::stop"); AutoMutex lock(&mLock); if (mActive && (recordTrack == mRecordTrack.get())) { +#ifdef WITH_A2DP + { // scope for lock2 + + // AudioFlinger::mLock must be locked before calling + // handleStreamDisablesA2dp_l because it calls setA2dpEnabled_l(). + AutoMutex lock2(&mAudioFlinger->mLock); + + // Currently there is no way to detect if we are recording over SCO, + // so we disable A2DP during any recording. + mAudioFlinger->handleStreamDisablesA2dp_l(ACTIVE_TRACK_REMOVED); + } +#endif mActive = false; + mStopped.wait(mLock); } } @@ -1717,6 +2548,22 @@ void AudioFlinger::AudioRecordThread::exit() requestExitAndWait(); } +status_t AudioFlinger::AudioRecordThread::dump(int fd, const Vector& args) +{ + const size_t SIZE = 256; + char buffer[SIZE]; + String8 result; + pid_t pid = 0; + + if (mRecordTrack != 0 && mRecordTrack->mClient != 0) { + snprintf(buffer, SIZE, "Record client pid: %d\n", mRecordTrack->mClient->pid()); + result.append(buffer); + } else { + result.append("No record client\n"); + } + write(fd, result.string(), result.size()); + return NO_ERROR; +} status_t AudioFlinger::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) diff --git a/libs/audioflinger/AudioFlinger.h b/libs/audioflinger/AudioFlinger.h index 9ab362a39ddd1d82bded2922e07bd646876b8781..ab15947f866db6cdeb4e6562dfef71b310c8448d 100644 --- a/libs/audioflinger/AudioFlinger.h +++ b/libs/audioflinger/AudioFlinger.h @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -32,6 +33,7 @@ #include #include #include +#include #include @@ -54,18 +56,13 @@ class AudioBuffer; static const nsecs_t kStandbyTimeInNsecs = seconds(3); -class AudioFlinger : public BnAudioFlinger, protected Thread +class AudioFlinger : public BnAudioFlinger, public IBinder::DeathRecipient { public: static void instantiate(); virtual status_t dump(int fd, const Vector& args); - // Thread virtuals - virtual bool threadLoop(); - virtual status_t readyToRun(); - virtual void onFirstRef(); - // IAudioFlinger interface virtual sp createTrack( pid_t pid, @@ -78,11 +75,11 @@ public: const sp& sharedBuffer, status_t *status); - virtual uint32_t sampleRate() const; - virtual int channelCount() const; - virtual int format() const; - virtual size_t frameCount() const; - virtual size_t latency() const; + virtual uint32_t sampleRate(int output) const; + virtual int channelCount(int output) const; + virtual int format(int output) const; + virtual size_t frameCount(int output) const; + virtual uint32_t latency(int output) const; virtual status_t setMasterVolume(float value); virtual status_t setMasterMute(bool muted); @@ -107,8 +104,19 @@ public: virtual bool isMusicActive() const; + virtual bool isA2dpEnabled() const; + virtual status_t setParameter(const char* key, const char* value); + virtual void registerClient(const sp& client); + + virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount); + + virtual void wakeUp() { mWaitWorkCV.broadcast(); } + + // IBinder::DeathRecipient + virtual void binderDied(const wp& who); + enum hardware_call_state { AUDIO_HW_IDLE = 0, AUDIO_HW_INIT, @@ -149,23 +157,31 @@ private: AudioFlinger(); virtual ~AudioFlinger(); - void setOutput(AudioStreamOut* output); - void doSetOutput(AudioStreamOut* output); - size_t getOutputFrameCount(AudioStreamOut* output); + void setOutput(int outputType); + void doSetOutput(int outputType); #ifdef WITH_A2DP + void setA2dpEnabled_l(bool enable); + void checkA2dpEnabledChange_l(); +#endif + static bool streamForcedToSpeaker(int streamType); static bool streamDisablesA2dp(int streamType); - inline bool isA2dpEnabled() const { - return (mRequestedOutput == mA2dpOutput || - (mOutput && mOutput == mA2dpOutput)); - } - void setA2dpEnabled(bool enable); + + // Management of forced route to speaker for certain track types. + enum force_speaker_command { + ACTIVE_TRACK_ADDED = 0, + ACTIVE_TRACK_REMOVED, + CHECK_ROUTE_RESTORE_TIME, + FORCE_ROUTE_RESTORE + }; + void handleForcedSpeakerRoute(int command); +#ifdef WITH_A2DP + void handleStreamDisablesA2dp_l(int command); #endif // Internal dump utilites. status_t dumpPermissionDenial(int fd, const Vector& args); status_t dumpClients(int fd, const Vector& args); - status_t dumpTracks(int fd, const Vector& args); status_t dumpInternals(int fd, const Vector& args); // --- Client --- @@ -184,168 +200,347 @@ private: }; - // --- Track --- class TrackHandle; class RecordHandle; class AudioRecordThread; - // base for record and playback - class TrackBase : public AudioBufferProvider, public RefBase { - + + // --- MixerThread --- + class MixerThread : public Thread { public: - enum track_state { - IDLE, - TERMINATED, - STOPPED, - RESUMING, - ACTIVE, - PAUSING, - PAUSED + + // --- Track --- + + // base for record and playback + class TrackBase : public AudioBufferProvider, public RefBase { + + public: + enum track_state { + IDLE, + TERMINATED, + STOPPED, + RESUMING, + ACTIVE, + PAUSING, + PAUSED + }; + + enum track_flags { + STEPSERVER_FAILED = 0x01, // StepServer could not acquire cblk->lock mutex + SYSTEM_FLAGS_MASK = 0x0000ffffUL, + // The upper 16 bits are used for track-specific flags. + }; + + TrackBase(const sp& mixerThread, + const sp& client, + int streamType, + uint32_t sampleRate, + int format, + int channelCount, + int frameCount, + uint32_t flags, + const sp& sharedBuffer); + ~TrackBase(); + + virtual status_t start() = 0; + virtual void stop() = 0; + sp getCblk() const; + + protected: + friend class MixerThread; + friend class RecordHandle; + friend class AudioRecordThread; + + TrackBase(const TrackBase&); + TrackBase& operator = (const TrackBase&); + + virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) = 0; + virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer); + + audio_track_cblk_t* cblk() const { + return mCblk; + } + + int type() const { + return mStreamType; + } + + int format() const { + return mFormat; + } + + int channelCount() const ; + + int sampleRate() const; + + void* getBuffer(uint32_t offset, uint32_t frames) const; + + int name() const { + return mName; + } + + bool isStopped() const { + return mState == STOPPED; + } + + bool isTerminated() const { + return mState == TERMINATED; + } + + bool step(); + void reset(); + + sp mMixerThread; + sp mClient; + sp mCblkMemory; + audio_track_cblk_t* mCblk; + int mStreamType; + void* mBuffer; + void* mBufferEnd; + uint32_t mFrameCount; + int mName; + // we don't really need a lock for these + int mState; + int mClientTid; + uint8_t mFormat; + uint32_t mFlags; }; - enum track_flags { - STEPSERVER_FAILED = 0x01 // StepServer could not acquire cblk->lock mutex + // playback track + class Track : public TrackBase { + public: + Track( const sp& mixerThread, + const sp& client, + int streamType, + uint32_t sampleRate, + int format, + int channelCount, + int frameCount, + const sp& sharedBuffer); + ~Track(); + + void dump(char* buffer, size_t size); + virtual status_t start(); + virtual void stop(); + void pause(); + + void flush(); + void destroy(); + void mute(bool); + void setVolume(float left, float right); + + protected: + friend class MixerThread; + friend class AudioFlinger; + friend class AudioFlinger::TrackHandle; + + Track(const Track&); + Track& operator = (const Track&); + + virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer); + + bool isMuted() const { + return (mMute || mMixerThread->mStreamTypes[mStreamType].mute); + } + + bool isPausing() const { + return mState == PAUSING; + } + + bool isPaused() const { + return mState == PAUSED; + } + + bool isReady() const; + + void setPaused() { mState = PAUSED; } + void reset(); + + // we don't really need a lock for these + float mVolume[2]; + volatile bool mMute; + // FILLED state is used for suppressing volume ramp at begin of playing + enum {FS_FILLING, FS_FILLED, FS_ACTIVE}; + mutable uint8_t mFillingUpStatus; + int8_t mRetryCount; + sp mSharedBuffer; + bool mResetDone; + }; // end of Track + + // record track + class RecordTrack : public TrackBase { + public: + RecordTrack(const sp& mixerThread, + const sp& client, + int streamType, + uint32_t sampleRate, + int format, + int channelCount, + int frameCount, + uint32_t flags); + ~RecordTrack(); + + virtual status_t start(); + virtual void stop(); + + bool overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; } + bool setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; } + + private: + friend class AudioFlinger; + friend class AudioFlinger::RecordHandle; + friend class AudioFlinger::AudioRecordThread; + friend class MixerThread; + + RecordTrack(const Track&); + RecordTrack& operator = (const Track&); + + virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer); + + bool mOverflow; }; - TrackBase( const sp& audioFlinger, - const sp& client, - int streamType, - uint32_t sampleRate, - int format, - int channelCount, - int frameCount, - const sp& sharedBuffer); - ~TrackBase(); - - virtual status_t start() = 0; - virtual void stop() = 0; - sp getCblk() const; - - protected: - friend class AudioFlinger; - friend class RecordHandle; - friend class AudioRecordThread; - - TrackBase(const TrackBase&); - TrackBase& operator = (const TrackBase&); - - virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) = 0; - virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer); - - audio_track_cblk_t* cblk() const { - return mCblk; - } - - int type() const { - return mStreamType; - } - - int format() const { - return mFormat; - } - - int channelCount() const ; - - int sampleRate() const; - - void* getBuffer(uint32_t offset, uint32_t frames) const; - - int name() const { - return mName; - } - - bool isStopped() const { - return mState == STOPPED; - } - - bool isTerminated() const { - return mState == TERMINATED; - } - - bool step(); - void reset(); - - sp mAudioFlinger; - sp mClient; - sp mCblkMemory; - audio_track_cblk_t* mCblk; - int mStreamType; - void* mBuffer; - void* mBufferEnd; - uint32_t mFrameCount; - int mName; - // we don't really need a lock for these - int mState; - int mClientTid; - uint8_t mFormat; - uint8_t mFlags; - }; - - // playback track - class Track : public TrackBase { - public: - Track( const sp& audioFlinger, - const sp& client, + // playback track + class OutputTrack : public Track { + public: + + class Buffer: public AudioBufferProvider::Buffer { + public: + int16_t *mBuffer; + }; + + OutputTrack( const sp& mixerThread, + uint32_t sampleRate, + int format, + int channelCount, + int frameCount); + ~OutputTrack(); + + virtual status_t start(); + virtual void stop(); + void write(int16_t* data, uint32_t frames); + bool bufferQueueEmpty() { return (mBufferQueue.size() == 0) ? true : false; } + + private: + + status_t obtainBuffer(AudioBufferProvider::Buffer* buffer); + void clearBufferQueue(); + + sp mOutputMixerThread; + Vector < Buffer* > mBufferQueue; + AudioBufferProvider::Buffer mOutBuffer; + uint32_t mFramesWritten; + + }; // end of OutputTrack + + MixerThread (const sp& audioFlinger, AudioStreamOut* output, int outputType); + virtual ~MixerThread(); + + virtual status_t dump(int fd, const Vector& args); + + // Thread virtuals + virtual bool threadLoop(); + virtual status_t readyToRun(); + virtual void onFirstRef(); + + virtual uint32_t sampleRate() const; + virtual int channelCount() const; + virtual int format() const; + virtual size_t frameCount() const; + virtual uint32_t latency() const; + + virtual status_t setMasterVolume(float value); + virtual status_t setMasterMute(bool muted); + + virtual float masterVolume() const; + virtual bool masterMute() const; + + virtual status_t setStreamVolume(int stream, float value); + virtual status_t setStreamMute(int stream, bool muted); + + virtual float streamVolume(int stream) const; + virtual bool streamMute(int stream) const; + + bool isMusicActive() const; + + + sp createTrack_l( + const sp& client, int streamType, uint32_t sampleRate, int format, int channelCount, int frameCount, - const sp& sharedBuffer); - ~Track(); - - void dump(char* buffer, size_t size); - virtual status_t start(); - virtual void stop(); - void pause(); - - void flush(); - void destroy(); - void mute(bool); - void setVolume(float left, float right); + const sp& sharedBuffer, + status_t *status); + + void getTracks_l(SortedVector < sp >& tracks, + SortedVector < wp >& activeTracks); + void putTracks_l(SortedVector < sp >& tracks, + SortedVector < wp >& activeTracks); + void setOuputTrack(OutputTrack *track) { mOutputTrack = track; } + + struct stream_type_t { + stream_type_t() + : volume(1.0f), + mute(false) + { + } + float volume; + bool mute; + }; private: - friend class AudioFlinger; - friend class TrackHandle; - - Track(const Track&); - Track& operator = (const Track&); - - virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer); - - bool isMuted() const { - return mMute; - } - - bool isPausing() const { - return mState == PAUSING; - } - bool isPaused() const { - return mState == PAUSED; - } - bool isReady() const; - - void setPaused() { mState = PAUSED; } - void reset(); - - // we don't really need a lock for these - float mVolume[2]; - volatile bool mMute; - // FILLED state is used for suppressing volume ramp at begin of playing - enum {FS_FILLING, FS_FILLED, FS_ACTIVE}; - mutable uint8_t mFillingUpStatus; - int8_t mRetryCount; - sp mSharedBuffer; - bool mResetDone; - }; // end of Track + friend class AudioFlinger; + friend class Track; + friend class TrackBase; + friend class RecordTrack; + + MixerThread(const Client&); + MixerThread& operator = (const MixerThread&); + + status_t addTrack_l(const sp& track); + void removeTrack_l(wp track, int name); + void destroyTrack_l(const sp& track); + int getTrackName_l(); + void deleteTrackName_l(int name); + void addActiveTrack_l(const wp& t); + void removeActiveTrack_l(const wp& t); + size_t getOutputFrameCount(); + + status_t dumpInternals(int fd, const Vector& args); + status_t dumpTracks(int fd, const Vector& args); + + sp mAudioFlinger; + SortedVector< wp > mActiveTracks; + SortedVector< sp > mTracks; + stream_type_t mStreamTypes[AudioSystem::NUM_STREAM_TYPES]; + AudioMixer* mAudioMixer; + AudioStreamOut* mOutput; + int mOutputType; + uint32_t mSampleRate; + size_t mFrameCount; + int mChannelCount; + int mFormat; + int16_t* mMixBuffer; + float mMasterVolume; + bool mMasterMute; + nsecs_t mLastWriteTime; + int mNumWrites; + int mNumDelayedWrites; + bool mStandby; + bool mInWrite; + sp mOutputTrack; + }; + friend class AudioBuffer; class TrackHandle : public android::BnAudioTrack { public: - TrackHandle(const sp& track); + TrackHandle(const sp& track); virtual ~TrackHandle(); virtual status_t start(); virtual void stop(); @@ -357,70 +552,20 @@ private: virtual status_t onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); private: - sp mTrack; - }; - - struct stream_type_t { - stream_type_t() - : volume(1.0f), - mute(false) - { - } - float volume; - bool mute; + sp mTrack; }; friend class Client; - friend class Track; + friend class MixerThread::Track; void removeClient(pid_t pid); - status_t addTrack(const sp& track); - void removeTrack(wp track, int name); - void remove_track_l(wp track, int name); - void destroyTrack(const sp& track); - void addActiveTrack(const wp& track); - void removeActiveTrack(const wp& track); - AudioMixer* audioMixer() { - return mAudioMixer; - } - - // record track - class RecordTrack : public TrackBase { - public: - RecordTrack( const sp& audioFlinger, - const sp& client, - int streamType, - uint32_t sampleRate, - int format, - int channelCount, - int frameCount); - ~RecordTrack(); - - virtual status_t start(); - virtual void stop(); - - bool overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; } - bool setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; } - - private: - friend class AudioFlinger; - friend class RecordHandle; - friend class AudioRecordThread; - - RecordTrack(const Track&); - RecordTrack& operator = (const Track&); - - virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer); - - bool mOverflow; - }; class RecordHandle : public android::BnAudioRecord { public: - RecordHandle(const sp& recordTrack); + RecordHandle(const sp& recordTrack); virtual ~RecordHandle(); virtual status_t start(); virtual void stop(); @@ -428,72 +573,66 @@ private: virtual status_t onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); private: - sp mRecordTrack; + sp mRecordTrack; }; // record thread class AudioRecordThread : public Thread { public: - AudioRecordThread(AudioHardwareInterface* audioHardware); + AudioRecordThread(AudioHardwareInterface* audioHardware, const sp& audioFlinger); virtual ~AudioRecordThread(); virtual bool threadLoop(); virtual status_t readyToRun() { return NO_ERROR; } virtual void onFirstRef() {} - status_t start(RecordTrack* recordTrack); - void stop(RecordTrack* recordTrack); + status_t start(MixerThread::RecordTrack* recordTrack); + void stop(MixerThread::RecordTrack* recordTrack); void exit(); + status_t dump(int fd, const Vector& args); private: AudioRecordThread(); AudioHardwareInterface *mAudioHardware; - sp mRecordTrack; + sp mAudioFlinger; + sp mRecordTrack; Mutex mLock; Condition mWaitWorkCV; + Condition mStopped; volatile bool mActive; status_t mStartStatus; }; friend class AudioRecordThread; + friend class MixerThread; + + status_t startRecord(MixerThread::RecordTrack* recordTrack); + void stopRecord(MixerThread::RecordTrack* recordTrack); - status_t startRecord(RecordTrack* recordTrack); - void stopRecord(RecordTrack* recordTrack); + mutable Mutex mHardwareLock; + mutable Mutex mLock; + mutable Condition mWaitWorkCV; - mutable Mutex mHardwareLock; - mutable Mutex mLock; - mutable Condition mWaitWorkCV; DefaultKeyedVector< pid_t, wp > mClients; - SortedVector< wp > mActiveTracks; - SortedVector< sp > mTracks; - float mMasterVolume; - uint32_t mMasterRouting; - bool mMasterMute; - stream_type_t mStreamTypes[AudioTrack::NUM_STREAM_TYPES]; - - AudioMixer* mHardwareAudioMixer; - AudioMixer* mA2dpAudioMixer; - AudioMixer* mAudioMixer; + + sp mA2dpMixerThread; + sp mHardwareMixerThread; AudioHardwareInterface* mAudioHardware; AudioHardwareInterface* mA2dpAudioInterface; - AudioStreamOut* mHardwareOutput; - AudioStreamOut* mA2dpOutput; - AudioStreamOut* mOutput; - AudioStreamOut* mRequestedOutput; sp mAudioRecordThread; - uint32_t mSampleRate; - size_t mFrameCount; - int mChannelCount; - int mFormat; - int16_t* mMixBuffer; + bool mA2dpEnabled; + bool mNotifyA2dpChange; mutable int mHardwareStatus; - nsecs_t mLastWriteTime; - int mNumWrites; - int mNumDelayedWrites; - bool mStandby; - bool mInWrite; + SortedVector< wp > mNotificationClients; + int mForcedSpeakerCount; int mA2dpDisableCount; + + // true if A2DP should resume when mA2dpDisableCount returns to zero bool mA2dpSuppressed; + uint32_t mSavedRoute; + uint32_t mForcedRoute; + nsecs_t mRouteRestoreTime; + bool mMusicMuteSaved; }; // ---------------------------------------------------------------------------- diff --git a/libs/audioflinger/AudioHardwareGeneric.cpp b/libs/audioflinger/AudioHardwareGeneric.cpp index e455186ecf07889f096ceeb46b7508ce8783acc0..62beadabddcb5d5f88c3f345ca15725350efdcd8 100644 --- a/libs/audioflinger/AudioHardwareGeneric.cpp +++ b/libs/audioflinger/AudioHardwareGeneric.cpp @@ -93,7 +93,8 @@ void AudioHardwareGeneric::closeOutputStream(AudioStreamOutGeneric* out) { } AudioStreamIn* AudioHardwareGeneric::openInputStream( - int format, int channelCount, uint32_t sampleRate, status_t *status) + int format, int channelCount, uint32_t sampleRate, status_t *status, + AudioSystem::audio_in_acoustics acoustics) { AutoMutex lock(mLock); @@ -107,7 +108,7 @@ AudioStreamIn* AudioHardwareGeneric::openInputStream( // create new output stream AudioStreamInGeneric* in = new AudioStreamInGeneric(); - status_t lStatus = in->set(this, mFd, format, channelCount, sampleRate); + status_t lStatus = in->set(this, mFd, format, channelCount, sampleRate, acoustics); if (status) { *status = lStatus; } @@ -246,7 +247,8 @@ status_t AudioStreamInGeneric::set( int fd, int format, int channels, - uint32_t rate) + uint32_t rate, + AudioSystem::audio_in_acoustics acoustics) { // FIXME: remove logging LOGD("AudioStreamInGeneric::set(%p, %d, %d, %d, %u)", hw, fd, format, channels, rate); diff --git a/libs/audioflinger/AudioHardwareGeneric.h b/libs/audioflinger/AudioHardwareGeneric.h index a7822e11ae5669c8b73df9aa22b239caf84db325..c949aa12a49f07a4088df6922b585fef3aac1bb3 100644 --- a/libs/audioflinger/AudioHardwareGeneric.h +++ b/libs/audioflinger/AudioHardwareGeneric.h @@ -47,7 +47,7 @@ public: virtual size_t bufferSize() const { return 4096; } virtual int channelCount() const { return 2; } virtual int format() const { return AudioSystem::PCM_16_BIT; } - virtual uint32_t latency() const { return 0; } + virtual uint32_t latency() const { return 20; } virtual status_t setVolume(float volume) { return INVALID_OPERATION; } virtual ssize_t write(const void* buffer, size_t bytes); virtual status_t standby(); @@ -69,7 +69,8 @@ public: int mFd, int format, int channelCount, - uint32_t sampleRate); + uint32_t sampleRate, + AudioSystem::audio_in_acoustics acoustics); uint32_t sampleRate() const { return 8000; } virtual size_t bufferSize() const { return 320; } @@ -114,7 +115,8 @@ public: int format, int channelCount, uint32_t sampleRate, - status_t *status); + status_t *status, + AudioSystem::audio_in_acoustics acoustics); void closeOutputStream(AudioStreamOutGeneric* out); void closeInputStream(AudioStreamInGeneric* in); diff --git a/libs/audioflinger/AudioHardwareStub.cpp b/libs/audioflinger/AudioHardwareStub.cpp index e9f3d690f638d49149573e97c79ec379b08b882e..b13cb1c072a85a4ceab01f71d6914428e49b1ecd 100644 --- a/libs/audioflinger/AudioHardwareStub.cpp +++ b/libs/audioflinger/AudioHardwareStub.cpp @@ -56,10 +56,11 @@ AudioStreamOut* AudioHardwareStub::openOutputStream( } AudioStreamIn* AudioHardwareStub::openInputStream( - int format, int channelCount, uint32_t sampleRate, status_t *status) + int format, int channelCount, uint32_t sampleRate, + status_t *status, AudioSystem::audio_in_acoustics acoustics) { AudioStreamInStub* in = new AudioStreamInStub(); - status_t lStatus = in->set(format, channelCount, sampleRate); + status_t lStatus = in->set(format, channelCount, sampleRate, acoustics); if (status) { *status = lStatus; } @@ -142,7 +143,8 @@ status_t AudioStreamOutStub::dump(int fd, const Vector& args) // ---------------------------------------------------------------------------- -status_t AudioStreamInStub::set(int format, int channels, uint32_t rate) +status_t AudioStreamInStub::set(int format, int channels, uint32_t rate, + AudioSystem::audio_in_acoustics acoustics) { if ((format == AudioSystem::PCM_16_BIT) && (channels == channelCount()) && diff --git a/libs/audioflinger/AudioHardwareStub.h b/libs/audioflinger/AudioHardwareStub.h index 24736eda682756da74a3b2664de46bfb399b2623..d40642465b8a8e5f7732d55557b9c697a6de1f61 100644 --- a/libs/audioflinger/AudioHardwareStub.h +++ b/libs/audioflinger/AudioHardwareStub.h @@ -43,7 +43,7 @@ public: class AudioStreamInStub : public AudioStreamIn { public: - virtual status_t set(int format, int channelCount, uint32_t sampleRate); + virtual status_t set(int format, int channelCount, uint32_t sampleRate, AudioSystem::audio_in_acoustics acoustics); virtual uint32_t sampleRate() const { return 8000; } virtual size_t bufferSize() const { return 320; } virtual int channelCount() const { return 1; } @@ -81,7 +81,8 @@ public: int format, int channelCount, uint32_t sampleRate, - status_t *status); + status_t *status, + AudioSystem::audio_in_acoustics acoustics); protected: virtual status_t doRouting() { return NO_ERROR; } diff --git a/libs/surfaceflinger/Android.mk b/libs/surfaceflinger/Android.mk index d14cebf5dbe36434e0317940680d08c2c7fee0bb..496e2717fb4a93459c8efb1af83dd7d81913be09 100644 --- a/libs/surfaceflinger/Android.mk +++ b/libs/surfaceflinger/Android.mk @@ -15,8 +15,8 @@ LOCAL_SRC_FILES:= \ LayerBlur.cpp \ LayerBitmap.cpp \ LayerDim.cpp \ - LayerScreenshot.cpp \ - RFBServer.cpp \ + LayerOrientationAnim.cpp \ + OrientationAnimation.cpp \ SurfaceFlinger.cpp \ Tokenizer.cpp \ Transform.cpp \ @@ -38,7 +38,8 @@ LOCAL_SHARED_LIBRARIES := \ libcorecg \ libsgl \ libpixelflinger \ - libGLES_CM + libEGL \ + libGLESv1_CM LOCAL_C_INCLUDES := \ $(call include-path-for, corecg graphics) diff --git a/libs/surfaceflinger/BootAnimation.cpp b/libs/surfaceflinger/BootAnimation.cpp index d18f59abac52dc61527380a5f3db41cf1f26390b..2b30336b78b136eff5b042ad4744d098436d8d68 100644 --- a/libs/surfaceflinger/BootAnimation.cpp +++ b/libs/surfaceflinger/BootAnimation.cpp @@ -39,7 +39,9 @@ #include #include -#include +#include +#include +#include #include "BootAnimation.h" @@ -47,32 +49,28 @@ namespace android { // --------------------------------------------------------------------------- -BootAnimation::BootAnimation(const sp& composer) -: Thread(false) -{ +BootAnimation::BootAnimation(const sp& composer) : + Thread(false) { mSession = SurfaceComposerClient::clientForConnection( composer->createConnection()->asBinder()); } -BootAnimation::~BootAnimation() -{ +BootAnimation::~BootAnimation() { } -void BootAnimation::onFirstRef() -{ +void BootAnimation::onFirstRef() { run("BootAnimation", PRIORITY_DISPLAY); } -const sp& BootAnimation::session() const -{ +const sp& BootAnimation::session() const { return mSession; } -status_t BootAnimation::initTexture( - Texture* texture, AssetManager& assets, const char* name) -{ +status_t BootAnimation::initTexture(Texture* texture, AssetManager& assets, + const char* name) { Asset* asset = assets.open(name, Asset::ACCESS_BUFFER); - if (!asset) return NO_INIT; + if (!asset) + return NO_INIT; SkBitmap bitmap; SkImageDecoder::DecodeMemory(asset->getBuffer(false), asset->getLength(), &bitmap, SkBitmap::kNo_Config, SkImageDecoder::kDecodePixels_Mode); @@ -84,32 +82,32 @@ status_t BootAnimation::initTexture( bitmap.lockPixels(); const int w = bitmap.width(); - const int h = bitmap.height(); + const int h = bitmap.height(); const void* p = bitmap.getPixels(); - + GLint crop[4] = { 0, h, w, -h }; texture->w = w; texture->h = h; glGenTextures(1, &texture->name); glBindTexture(GL_TEXTURE_2D, texture->name); - - switch(bitmap.getConfig()) { + + switch (bitmap.getConfig()) { case SkBitmap::kA8_Config: - glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, - GL_ALPHA, GL_UNSIGNED_BYTE, p); + glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA, + GL_UNSIGNED_BYTE, p); break; case SkBitmap::kARGB_4444_Config: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, - GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, p); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, + GL_UNSIGNED_SHORT_4_4_4_4, p); break; case SkBitmap::kARGB_8888_Config: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, - GL_RGBA, GL_UNSIGNED_BYTE, p); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, + GL_UNSIGNED_BYTE, p); break; case SkBitmap::kRGB_565_Config: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, - GL_RGB, GL_UNSIGNED_SHORT_5_6_5, p); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, + GL_UNSIGNED_SHORT_5_6_5, p); break; default: break; @@ -123,8 +121,7 @@ status_t BootAnimation::initTexture( return NO_ERROR; } -status_t BootAnimation::readyToRun() -{ +status_t BootAnimation::readyToRun() { mAssets.addDefaultAssets(); DisplayInfo dinfo; @@ -133,32 +130,27 @@ status_t BootAnimation::readyToRun() return -1; // create the native surface - sp s = session()->createSurface(getpid(), 0, - dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565); + sp s = session()->createSurface(getpid(), 0, dinfo.w, dinfo.h, + PIXEL_FORMAT_RGB_565); session()->openTransaction(); s->setLayer(0x40000000); session()->closeTransaction(); // initialize opengl and egl - const EGLint attribs[] = { - EGL_RED_SIZE, 5, - EGL_GREEN_SIZE, 6, - EGL_BLUE_SIZE, 5, - EGL_DEPTH_SIZE, 0, - EGL_NONE - }; + const EGLint attribs[] = { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6, + EGL_BLUE_SIZE, 5, EGL_DEPTH_SIZE, 0, EGL_NONE }; EGLint w, h, dummy; EGLint numConfigs; EGLConfig config; EGLSurface surface; EGLContext context; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - eglInitialize(display, NULL, NULL); eglChooseConfig(display, attribs, &config, 1, &numConfigs); - surface = eglCreateWindowSurface( - display, config, new EGLNativeWindowSurface(s), NULL); - + mNativeWindowSurface = new EGLNativeWindowSurface(s); + surface = eglCreateWindowSurface(display, config, + mNativeWindowSurface.get(), NULL); + context = eglCreateContext(display, config, NULL, NULL); eglQuerySurface(display, surface, EGL_WIDTH, &w); eglQuerySurface(display, surface, EGL_HEIGHT, &h); @@ -167,7 +159,7 @@ status_t BootAnimation::readyToRun() mContext = context; mSurface = surface; mWidth = w; - mHeight= h; + mHeight = h; mFlingerSurface = s; // initialize GL @@ -180,25 +172,21 @@ status_t BootAnimation::readyToRun() return NO_ERROR; } -void BootAnimation::requestExit() -{ +void BootAnimation::requestExit() { mBarrier.open(); Thread::requestExit(); } -bool BootAnimation::threadLoop() -{ +bool BootAnimation::threadLoop() { bool r = android(); - eglMakeCurrent(mDisplay, 0, 0, 0); - eglDestroyContext(mDisplay, mContext); + eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + eglDestroyContext(mDisplay, mContext); eglDestroySurface(mDisplay, mSurface); - eglTerminate(mDisplay); + mNativeWindowSurface.clear(); return r; } - -bool BootAnimation::android() -{ +bool BootAnimation::android() { initTexture(&mAndroid[0], mAssets, "images/android_320x480.png"); initTexture(&mAndroid[1], mAssets, "images/boot_robot.png"); initTexture(&mAndroid[2], mAssets, "images/boot_robot_glow.png"); @@ -219,9 +207,9 @@ bool BootAnimation::android() glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); const int steps = 8; - for (int i=1 ; isetSwapRectangle(updateRect.left, + updateRect.top, updateRect.width(), updateRect.height()); glEnable(GL_SCISSOR_TEST); - glScissor(updateRect.left, mHeight-updateRect.bottom, - updateRect.width(), updateRect.height()); + glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(), + updateRect.height()); const nsecs_t startTime = systemTime(); - do - { + do { // glow speed and shape nsecs_t time = systemTime() - startTime; - float t = ((4.0f/(360.0f*us2ns(16667))) * time); + float t = ((4.0f / (360.0f * us2ns(16667))) * time); t = t - floorf(t); - const float fade = 0.5f + 0.5f*sinf(t * 2*M_PI); + const float fade = 0.5f + 0.5f * sinf(t * 2 * M_PI); // fade the glow in and out glDisable(GL_BLEND); glBindTexture(GL_TEXTURE_2D, mAndroid[2].name); glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glColor4f(fade, fade, fade, fade); - glDrawTexiOES(updateRect.left, mHeight-updateRect.bottom, 0, + glDrawTexiOES(updateRect.left, mHeight - updateRect.bottom, 0, updateRect.width(), updateRect.height()); // draw the robot glEnable(GL_BLEND); glBindTexture(GL_TEXTURE_2D, mAndroid[1].name); glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glDrawTexiOES(updateRect.left, mHeight-updateRect.bottom, 0, + glDrawTexiOES(updateRect.left, mHeight - updateRect.bottom, 0, updateRect.width(), updateRect.height()); // make sure sleep a lot to not take too much CPU away from // the boot process. With this "glow" animation there is no // visible difference. - usleep(16667*4); + usleep(16667 * 4); eglSwapBuffers(mDisplay, mSurface); } while (!exitPending()); - - + glDeleteTextures(1, &mAndroid[0].name); glDeleteTextures(1, &mAndroid[1].name); glDeleteTextures(1, &mAndroid[2].name); return false; } - -bool BootAnimation::cylon() -{ +bool BootAnimation::cylon() { // initialize the textures... - initTexture(&mLeftTrail, mAssets, "images/cylon_left.png"); + initTexture(&mLeftTrail, mAssets, "images/cylon_left.png"); initTexture(&mRightTrail, mAssets, "images/cylon_right.png"); initTexture(&mBrightSpot, mAssets, "images/cylon_dot.png"); int w = mWidth; int h = mHeight; - const Point c(w/2 , h/2); + const Point c(w / 2, h / 2); const GLint amplitude = 60; - const int scx = c.x - amplitude - mBrightSpot.w/2; - const int scy = c.y - mBrightSpot.h/2; - const int scw = amplitude*2 + mBrightSpot.w; + const int scx = c.x - amplitude - mBrightSpot.w / 2; + const int scy = c.y - mBrightSpot.h / 2; + const int scw = amplitude * 2 + mBrightSpot.w; const int sch = mBrightSpot.h; - const Rect updateRect(scx, h-scy-sch, scx+scw, h-scy); + const Rect updateRect(scx, h - scy - sch, scx + scw, h - scy); // erase screen glDisable(GL_SCISSOR_TEST); @@ -314,33 +296,29 @@ bool BootAnimation::cylon() glClear(GL_COLOR_BUFFER_BIT); - eglSwapRectangleANDROID(mDisplay, mSurface, - updateRect.left, updateRect.top, - updateRect.width(), updateRect.height()); + mNativeWindowSurface->setSwapRectangle(updateRect.left, + updateRect.top, updateRect.width(), updateRect.height()); glEnable(GL_SCISSOR_TEST); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - // clear the screen to white Point p; float t = 0; float alpha = 1.0f; const nsecs_t startTime = systemTime(); nsecs_t fadeTime = 0; - - do - { + + do { // Set scissor in interesting area - glScissor(scx, scy, scw, sch); + glScissor(scx, scy, scw, sch); // erase screen glClear(GL_COLOR_BUFFER_BIT); - // compute wave - const float a = (t * 2*M_PI) - M_PI/2; + const float a = (t * 2 * M_PI) - M_PI / 2; const float sn = sinf(a); const float cs = cosf(a); GLint x = GLint(amplitude * sn); @@ -350,50 +328,50 @@ bool BootAnimation::cylon() if (derivative > 0) { // vanishing trail... - p.x = (-amplitude + c.x) - mBrightSpot.w/2; - p.y = c.y-mLeftTrail.h/2; - float fade = 2.0f*(0.5f-t); + p.x = (-amplitude + c.x) - mBrightSpot.w / 2; + p.y = c.y - mLeftTrail.h / 2; + float fade = 2.0f * (0.5f - t); //fade *= fade; glColor4f(fade, fade, fade, fade); glBindTexture(GL_TEXTURE_2D, mLeftTrail.name); glDrawTexiOES(p.x, p.y, 0, mLeftTrail.w, mLeftTrail.h); // trail... - p.x = (x + c.x) - (mRightTrail.w + mBrightSpot.w/2) + 16; - p.y = c.y-mRightTrail.h/2; - fade = t<0.25f ? t*4.0f : 1.0f; + p.x = (x + c.x) - (mRightTrail.w + mBrightSpot.w / 2) + 16; + p.y = c.y - mRightTrail.h / 2; + fade = t < 0.25f ? t * 4.0f : 1.0f; fade *= fade; glColor4f(fade, fade, fade, fade); glBindTexture(GL_TEXTURE_2D, mRightTrail.name); glDrawTexiOES(p.x, p.y, 0, mRightTrail.w, mRightTrail.h); - } else { + } else { // vanishing trail.. - p.x = (amplitude + c.x) - (mRightTrail.w + mBrightSpot.w/2) + 16; - p.y = c.y-mRightTrail.h/2; - float fade = 2.0f*(0.5f-(t-0.5f)); + p.x = (amplitude + c.x) - (mRightTrail.w + mBrightSpot.w / 2) + 16; + p.y = c.y - mRightTrail.h / 2; + float fade = 2.0f * (0.5f - (t - 0.5f)); //fade *= fade; glColor4f(fade, fade, fade, fade); glBindTexture(GL_TEXTURE_2D, mRightTrail.name); glDrawTexiOES(p.x, p.y, 0, mRightTrail.w, mRightTrail.h); // trail... - p.x = (x + c.x) - mBrightSpot.w/2; - p.y = c.y-mLeftTrail.h/2; - fade = t<0.5f+0.25f ? (t-0.5f)*4.0f : 1.0f; + p.x = (x + c.x) - mBrightSpot.w / 2; + p.y = c.y - mLeftTrail.h / 2; + fade = t < 0.5f + 0.25f ? (t - 0.5f) * 4.0f : 1.0f; fade *= fade; glColor4f(fade, fade, fade, fade); glBindTexture(GL_TEXTURE_2D, mLeftTrail.name); glDrawTexiOES(p.x, p.y, 0, mLeftTrail.w, mLeftTrail.h); } - const Point p( x + c.x-mBrightSpot.w/2, c.y-mBrightSpot.h/2 ); + const Point p(x + c.x - mBrightSpot.w / 2, c.y - mBrightSpot.h / 2); glBindTexture(GL_TEXTURE_2D, mBrightSpot.name); - glColor4f(1,0.5,0.5,1); + glColor4f(1, 0.5, 0.5, 1); glDrawTexiOES(p.x, p.y, 0, mBrightSpot.w, mBrightSpot.h); // update animation nsecs_t time = systemTime() - startTime; - t = ((4.0f/(360.0f*us2ns(16667))) * time); + t = ((4.0f / (360.0f * us2ns(16667))) * time); t = t - floorf(t); eglSwapBuffers(mDisplay, mSurface); @@ -406,7 +384,7 @@ bool BootAnimation::cylon() alpha = 1.0f - ((float(time) * 6.0f) / float(s2ns(1))); session()->openTransaction(); - mFlingerSurface->setAlpha(alpha*alpha); + mFlingerSurface->setAlpha(alpha * alpha); session()->closeTransaction(); } } while (alpha > 0); @@ -421,4 +399,5 @@ bool BootAnimation::cylon() // --------------------------------------------------------------------------- -}; // namespace android +} +; // namespace android diff --git a/libs/surfaceflinger/BootAnimation.h b/libs/surfaceflinger/BootAnimation.h index a4a6d49ded7a2fdadfc43cbc47dade15b5ed92e7..b20cea09a4911343d544f52bac1f38253337bc49 100644 --- a/libs/surfaceflinger/BootAnimation.h +++ b/libs/surfaceflinger/BootAnimation.h @@ -26,7 +26,8 @@ #include #include -#include +#include +#include #include "Barrier.h" @@ -35,6 +36,7 @@ class SkBitmap; namespace android { class AssetManager; +class EGLNativeWindowSurface; // --------------------------------------------------------------------------- @@ -74,6 +76,7 @@ private: EGLDisplay mContext; EGLDisplay mSurface; sp mFlingerSurface; + sp mNativeWindowSurface; Barrier mBarrier; }; diff --git a/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp b/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp index 92588fa0d134c1f84d0cd515f6cab0f2539fbcf0..f14d7e99c2d3bea6c001d735e1629b4a88f46903 100644 --- a/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp +++ b/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp @@ -21,14 +21,16 @@ #include #include -#include - #include #include #include +#include +#include + + #include "DisplayHardware/DisplayHardware.h" #include @@ -136,26 +138,19 @@ void DisplayHardware::init(uint32_t dpy) const char* const egl_extensions = eglQueryString( display, EGL_EXTENSIONS); - const char* egl_extensions_config = egl_extensions; - - if (strstr(egl_extensions, "EGL_ANDROID_query_string_config")) { - egl_extensions_config = eglQueryStringConfigANDROID( - display, config, EGL_EXTENSIONS); - } - LOGI("EGL informations:"); LOGI("# of configs : %d", numConfigs); LOGI("vendor : %s", eglQueryString(display, EGL_VENDOR)); LOGI("version : %s", eglQueryString(display, EGL_VERSION)); LOGI("extensions: %s", egl_extensions); - LOGI("ext/config: %s", egl_extensions_config); LOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported"); - if (strstr(egl_extensions_config, "EGL_ANDROID_swap_rectangle")) { - mFlags |= SWAP_RECTANGLE_EXTENSION; - // TODO: get the real "update_on_demand" behavior - mFlags |= UPDATE_ON_DEMAND; - } + // TODO: get this from the devfb driver (probably should be HAL module) + mFlags |= SWAP_RECTANGLE_EXTENSION; + + // TODO: get the real "update_on_demand" behavior (probably should be HAL module) + mFlags |= UPDATE_ON_DEMAND; + if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) { if (dummy == EGL_SLOW_CONFIG) mFlags |= SLOW_CONFIG; @@ -173,9 +168,6 @@ void DisplayHardware::init(uint32_t dpy) if (eglQuerySurface(display, surface, EGL_SWAP_BEHAVIOR, &dummy) == EGL_TRUE) { if (dummy == EGL_BUFFER_PRESERVED) { mFlags |= BUFFER_PRESERVED; - if (strstr(egl_extensions_config, "EGL_ANDROID_copy_front_to_back")) { - mFlags |= COPY_BACK_EXTENSION; - } } } @@ -330,8 +322,7 @@ void DisplayHardware::flip(const Region& dirty) const if (mFlags & SWAP_RECTANGLE_EXTENSION) { const Rect& b(newDirty.bounds()); - eglSwapRectangleANDROID( - dpy, surface, + mDisplaySurface->setSwapRectangle( b.left, b.top, b.width(), b.height()); } @@ -352,3 +343,11 @@ void DisplayHardware::makeCurrent() const { eglMakeCurrent(mDisplay, mSurface, mSurface, mContext); } + +void DisplayHardware::copyFrontToImage(const copybit_image_t& front) const { + mDisplaySurface->copyFrontToImage(front); +} + +void DisplayHardware::copyBackToImage(const copybit_image_t& front) const { + mDisplaySurface->copyBackToImage(front); +} diff --git a/libs/surfaceflinger/DisplayHardware/DisplayHardware.h b/libs/surfaceflinger/DisplayHardware/DisplayHardware.h index df97b60d98d0625f017c95af77048e5273b6950a..550a4d12702c9e6a79930490180b6d0a57645cce 100644 --- a/libs/surfaceflinger/DisplayHardware/DisplayHardware.h +++ b/libs/surfaceflinger/DisplayHardware/DisplayHardware.h @@ -22,7 +22,7 @@ #include #include -#include +#include #include "DisplayHardware/DisplayHardwareBase.h" @@ -39,7 +39,6 @@ class DisplayHardware : public DisplayHardwareBase { public: enum { - COPY_BACK_EXTENSION = 0x00000001, DIRECT_TEXTURE = 0x00000002, SWAP_RECTANGLE_EXTENSION= 0x00000004, COPY_BITS_EXTENSION = 0x00000008, @@ -80,6 +79,9 @@ public: copybit_device_t* getBlitEngine() const { return mBlitEngine; } overlay_control_device_t* getOverlayEngine() const { return mOverlayEngine; } + void copyFrontToImage(const copybit_image_t& front) const; + void copyBackToImage(const copybit_image_t& front) const; + Rect bounds() const { return Rect(mWidth, mHeight); } diff --git a/libs/surfaceflinger/LayerBase.cpp b/libs/surfaceflinger/LayerBase.cpp index bdefba34e23377ed86baf95ed2c511d0bcf17136..0cf53f796b6b225d9812d17c9d9a771df37dfa8e 100644 --- a/libs/surfaceflinger/LayerBase.cpp +++ b/libs/surfaceflinger/LayerBase.cpp @@ -23,6 +23,11 @@ #include #include +#include +#include + +#include + #include "clz.h" #include "LayerBase.h" #include "LayerBlur.h" @@ -111,6 +116,12 @@ void LayerBase::commitTransaction(bool skipSize) { mDrawingState.h = h; } } +void LayerBase::forceVisibilityTransaction() { + // this can be called without SurfaceFlinger.mStateLock, but if we + // can atomically increment the sequence number, it doesn't matter. + android_atomic_inc(&mCurrentState.sequence); + requestTransaction(); +} bool LayerBase::requestTransaction() { int32_t old = setTransactionFlags(eTransactionNeeded); return ((old & eTransactionNeeded) == 0); @@ -350,6 +361,10 @@ void LayerBase::draw(const Region& inClip) const return; } } + + // reset GL state + glEnable(GL_SCISSOR_TEST); + onDraw(clip); /* @@ -391,6 +406,7 @@ void LayerBase::clearWithOpenGL(const Region& clip) const Rect r; Region::iterator iterator(clip); if (iterator) { + glEnable(GL_SCISSOR_TEST); glVertexPointer(2, GL_FIXED, 0, mVertices); while (iterator.iterate(&r)) { const GLint sy = fbHeight - (r.top + r.height()); @@ -401,7 +417,7 @@ void LayerBase::clearWithOpenGL(const Region& clip) const } void LayerBase::drawWithOpenGL(const Region& clip, - GLint textureName, const GGLSurface& t) const + GLint textureName, const GGLSurface& t, int transform) const { const DisplayHardware& hw(graphicPlane(0).displayHardware()); const uint32_t fbHeight = hw.getHeight(); @@ -473,6 +489,12 @@ void LayerBase::drawWithOpenGL(const Region& clip, glMatrixMode(GL_TEXTURE); glLoadIdentity(); + + if (transform == HAL_TRANSFORM_ROT_90) { + glTranslatef(0, 1, 0); + glRotatef(-90, 0, 0, 1); + } + if (!(mFlags & DisplayHardware::NPOT_EXTENSION)) { // find the smallest power-of-two that will accommodate our surface GLuint tw = 1 << (31 - clz(t.width)); diff --git a/libs/surfaceflinger/LayerBase.h b/libs/surfaceflinger/LayerBase.h index 5e14dc85c7acc033eb3e5fcfe3961f3cfedf9765..a020f44e8746a9b966cdc60a4c095903030e0edb 100644 --- a/libs/surfaceflinger/LayerBase.h +++ b/libs/surfaceflinger/LayerBase.h @@ -86,8 +86,8 @@ public: uint32_t z; uint8_t alpha; uint8_t flags; - uint8_t sequence; // changes when visible regions can change - uint8_t reserved; + uint8_t reserved[2]; + int32_t sequence; // changes when visible regions can change uint32_t tint; Transform transform; Region transparentRegion; @@ -104,11 +104,11 @@ public: void commitTransaction(bool skipSize); bool requestTransaction(); - + void forceVisibilityTransaction(); + uint32_t getTransactionFlags(uint32_t flags); uint32_t setTransactionFlags(uint32_t flags); - void validateVisibility(const Transform& globalTransform); Rect visibleBounds() const; void drawRegion(const Region& reg) const; @@ -162,7 +162,12 @@ public: * the bitmap (as opposed to the size of the drawing state). */ virtual Point getPhysicalSize() const; - + + /** + * validateVisibility - cache a bunch of things + */ + virtual void validateVisibility(const Transform& globalTransform); + /** * lockPageFlip - called each time the screen is redrawn and returns whether * the visible regions need to be recomputed (this is a fairly heavy @@ -188,10 +193,15 @@ public: * needsBlending - true if this surface needs blending */ virtual bool needsBlending() const { return false; } - + + /** + * transformed -- true is this surface needs a to be transformed + */ + virtual bool transformed() const { return mTransformed; } + /** - * isSecure - true if this surface is secure, that is if it prevents a - * screenshot to be taken, + * isSecure - true if this surface is secure, that is if it prevents + * screenshots or vns servers. */ virtual bool isSecure() const { return false; } @@ -210,7 +220,6 @@ public: } int32_t getOrientation() const { return mOrientation; } - bool transformed() const { return mTransformed; } int tx() const { return mLeft; } int ty() const { return mTop; } @@ -221,7 +230,9 @@ protected: GLuint createTexture() const; void drawWithOpenGL(const Region& clip, - GLint textureName, const GGLSurface& surface) const; + GLint textureName, + const GGLSurface& surface, + int transform = 0) const; void clearWithOpenGL(const Region& clip) const; @@ -320,8 +331,7 @@ public: *params = mParams; } - virtual status_t registerBuffers(int w, int h, int hstride, int vstride, - PixelFormat format, const sp& heap) + virtual status_t registerBuffers(const ISurface::BufferHeap& buffers) { return INVALID_OPERATION; } virtual void postBuffer(ssize_t offset) { } virtual void unregisterBuffers() { }; diff --git a/libs/surfaceflinger/LayerBitmap.cpp b/libs/surfaceflinger/LayerBitmap.cpp index 7c98857fc283613ab80493c000db13058adde7de..e84435088a7c40481a6a14d7a3b94f3fca7f1545 100644 --- a/libs/surfaceflinger/LayerBitmap.cpp +++ b/libs/surfaceflinger/LayerBitmap.cpp @@ -69,18 +69,15 @@ status_t LayerBitmap::setBits(uint32_t w, uint32_t h, uint32_t alignment, return NO_ERROR; } + PixelFormatInfo info; + getPixelFormatInfo(format, &info); + uint32_t allocFlags = MemoryDealer::PAGE_ALIGNED; const uint32_t align = 4; // must match GL_UNPACK_ALIGNMENT - const uint32_t Bpp = bytesPerPixel(format); + const uint32_t Bpp = info.bytesPerPixel; uint32_t stride = (w + (alignment-1)) & ~(alignment-1); stride = ((stride * Bpp + (align-1)) & ~(align-1)) / Bpp; - size_t size = stride * h * Bpp; - if (format == PIXEL_FORMAT_YCbCr_422_SP || - format == PIXEL_FORMAT_YCbCr_420_SP) { - // in YUV planar, bitsPerPixel is for the Y plane - size = (size * bitsPerPixel(format)) / 8; - } - + size_t size = info.getScanlineSize(stride) * h; if (allocFlags & MemoryDealer::PAGE_ALIGNED) { size_t pagesize = getpagesize(); size = (size + (pagesize-1)) & ~(pagesize-1); diff --git a/libs/surfaceflinger/LayerBitmap.h b/libs/surfaceflinger/LayerBitmap.h index 4c2eb50df5f5816fdd73a39c7eee162290d8ed29..9ad64c40becf9339a0f40f67f8b5ef32dd6b01c2 100644 --- a/libs/surfaceflinger/LayerBitmap.h +++ b/libs/surfaceflinger/LayerBitmap.h @@ -70,9 +70,6 @@ public: void getBitmapSurface(copybit_image_t* img) const; private: - LayerBitmap(const LayerBitmap& rhs); - LayerBitmap& operator = (const LayerBitmap& rhs); - sp mAllocator; sp mBitsMemory; uint32_t mAllocFlags; diff --git a/libs/surfaceflinger/LayerBlur.cpp b/libs/surfaceflinger/LayerBlur.cpp index efadbcf4c645b931539f85c35884a96f4b77e811..d3e456f1bf8f527ab93c7e5e5eed856998526836 100644 --- a/libs/surfaceflinger/LayerBlur.cpp +++ b/libs/surfaceflinger/LayerBlur.cpp @@ -23,6 +23,9 @@ #include #include +#include +#include + #include "BlurFilter.h" #include "LayerBlur.h" #include "SurfaceFlinger.h" diff --git a/libs/surfaceflinger/LayerBuffer.cpp b/libs/surfaceflinger/LayerBuffer.cpp index c9cebf4c9164ae207575315c23632273795ce1ac..00fab70d491d040ffe665604230288513959a0d2 100644 --- a/libs/surfaceflinger/LayerBuffer.cpp +++ b/libs/surfaceflinger/LayerBuffer.cpp @@ -25,6 +25,9 @@ #include #include +#include +#include + #include #include @@ -129,18 +132,24 @@ void LayerBuffer::onDraw(const Region& clip) const } } +bool LayerBuffer::transformed() const +{ + sp source(getSource()); + if (LIKELY(source != 0)) + return source->transformed(); + return false; +} + /** * This creates a "buffer" source for this surface */ -status_t LayerBuffer::registerBuffers(int w, int h, int hstride, int vstride, - PixelFormat format, const sp& memoryHeap) +status_t LayerBuffer::registerBuffers(const ISurface::BufferHeap& buffers) { Mutex::Autolock _l(mLock); if (mSource != 0) return INVALID_OPERATION; - sp source = new BufferSource(*this, w, h, - hstride, vstride, format, memoryHeap); + sp source = new BufferSource(*this, buffers); status_t result = source->getStatus(); if (result == NO_ERROR) { @@ -194,13 +203,39 @@ LayerBuffer::SurfaceBuffer::~SurfaceBuffer() mOwner = 0; } -status_t LayerBuffer::SurfaceBuffer::registerBuffers( - int w, int h, int hs, int vs, - PixelFormat format, const sp& heap) +status_t LayerBuffer::SurfaceBuffer::onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) +{ + switch (code) { + case REGISTER_BUFFERS: + case UNREGISTER_BUFFERS: + case CREATE_OVERLAY: + { + // codes that require permission check + IPCThreadState* ipc = IPCThreadState::self(); + const int pid = ipc->getCallingPid(); + const int self_pid = getpid(); + if (LIKELY(pid != self_pid)) { + // we're called from a different process, do the real check + if (!checkCallingPermission( + String16("android.permission.ACCESS_SURFACE_FLINGER"))) + { + const int uid = ipc->getCallingUid(); + LOGE("Permission Denial: " + "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); + return PERMISSION_DENIED; + } + } + } + } + return LayerBaseClient::Surface::onTransact(code, data, reply, flags); +} + +status_t LayerBuffer::SurfaceBuffer::registerBuffers(const ISurface::BufferHeap& buffers) { LayerBuffer* owner(getOwner()); if (owner) - return owner->registerBuffers(w, h, hs, vs, format, heap); + return owner->registerBuffers(buffers); return NO_INIT; } @@ -237,23 +272,20 @@ void LayerBuffer::SurfaceBuffer::disown() // LayerBuffer::Buffer // ============================================================================ -LayerBuffer::Buffer::Buffer(const sp& heap, ssize_t offset, - int w, int h, int hs, int vs, int f) -: mHeap(heap) +LayerBuffer::Buffer::Buffer(const ISurface::BufferHeap& buffers, ssize_t offset) + : mBufferHeap(buffers) { NativeBuffer& src(mNativeBuffer); src.crop.l = 0; src.crop.t = 0; - src.crop.r = w; - src.crop.b = h; - src.img.w = hs ?: w; - src.img.h = vs ?: h; - src.img.format = f; + src.crop.r = buffers.w; + src.crop.b = buffers.h; + src.img.w = buffers.hor_stride ?: buffers.w; + src.img.h = buffers.ver_stride ?: buffers.h; + src.img.format = buffers.format; src.img.offset = offset; - src.img.base = heap->base(); - src.img.fd = heap->heapID(); - // FIXME: make sure this buffer lies within the heap, in which case, set - // mHeap to null + src.img.base = buffers.heap->base(); + src.img.fd = buffers.heap->heapID(); } LayerBuffer::Buffer::~Buffer() @@ -283,41 +315,55 @@ void LayerBuffer::Source::postBuffer(ssize_t offset) { } void LayerBuffer::Source::unregisterBuffers() { } +bool LayerBuffer::Source::transformed() const { + return mLayer.mTransformed; +} // --------------------------------------------------------------------------- LayerBuffer::BufferSource::BufferSource(LayerBuffer& layer, - int w, int h, int hstride, int vstride, - PixelFormat format, const sp& memoryHeap) - : Source(layer), mStatus(NO_ERROR), mTextureName(-1U) + const ISurface::BufferHeap& buffers) + : Source(layer), mStatus(NO_ERROR), + mBufferSize(0), mTextureName(-1U) { - if (memoryHeap == NULL) { + if (buffers.heap == NULL) { // this is allowed, but in this case, it is illegal to receive // postBuffer(). The surface just erases the framebuffer with // fully transparent pixels. - mHeap.clear(); - mWidth = w; - mHeight = h; + mBufferHeap = buffers; mLayer.setNeedsBlending(false); return; } - status_t err = (memoryHeap->heapID() >= 0) ? NO_ERROR : NO_INIT; + status_t err = (buffers.heap->heapID() >= 0) ? NO_ERROR : NO_INIT; if (err != NO_ERROR) { + LOGE("LayerBuffer::BufferSource: invalid heap (%s)", strerror(err)); mStatus = err; return; } - - // TODO: validate format/parameters - mHeap = memoryHeap; - mWidth = w; - mHeight = h; - mHStride = hstride; - mVStride = vstride; - mFormat = format; + PixelFormatInfo info; - getPixelFormatInfo(format, &info); - mLayer.setNeedsBlending((info.h_alpha - info.l_alpha) > 0); + err = getPixelFormatInfo(buffers.format, &info); + if (err != NO_ERROR) { + LOGE("LayerBuffer::BufferSource: invalid format %d (%s)", + buffers.format, strerror(err)); + mStatus = err; + return; + } + + if (buffers.hor_stride<0 || buffers.ver_stride<0) { + LOGE("LayerBuffer::BufferSource: invalid parameters " + "(w=%d, h=%d, xs=%d, ys=%d)", + buffers.w, buffers.h, buffers.hor_stride, buffers.ver_stride); + mStatus = BAD_VALUE; + return; + } + + mBufferHeap = buffers; + mLayer.setNeedsBlending((info.h_alpha - info.l_alpha) > 0); + mBufferSize = info.getScanlineSize(buffers.hor_stride)*buffers.ver_stride; + mLayer.forceVisibilityTransaction(); + } LayerBuffer::BufferSource::~BufferSource() @@ -329,21 +375,24 @@ LayerBuffer::BufferSource::~BufferSource() void LayerBuffer::BufferSource::postBuffer(ssize_t offset) { - sp heap; - int w, h, hs, vs, f; + ISurface::BufferHeap buffers; { // scope for the lock Mutex::Autolock _l(mLock); - w = mWidth; - h = mHeight; - hs= mHStride; - vs= mVStride; - f = mFormat; - heap = mHeap; + buffers = mBufferHeap; + if (buffers.heap != 0) { + const size_t memorySize = buffers.heap->getSize(); + if ((size_t(offset) + mBufferSize) > memorySize) { + LOGE("LayerBuffer::BufferSource::postBuffer() " + "invalid buffer (offset=%d, size=%d, heap-size=%d", + int(offset), int(mBufferSize), int(memorySize)); + return; + } + } } sp buffer; - if (heap != 0) { - buffer = new LayerBuffer::Buffer(heap, offset, w, h, hs, vs, f); + if (buffers.heap != 0) { + buffer = new LayerBuffer::Buffer(buffers, offset); if (buffer->getStatus() != NO_ERROR) buffer.clear(); setBuffer(buffer); @@ -354,7 +403,7 @@ void LayerBuffer::BufferSource::postBuffer(ssize_t offset) void LayerBuffer::BufferSource::unregisterBuffers() { Mutex::Autolock _l(mLock); - mHeap.clear(); + mBufferHeap.heap.clear(); mBuffer.clear(); mLayer.invalidate(); } @@ -371,6 +420,11 @@ void LayerBuffer::BufferSource::setBuffer(const sp& buffer) mBuffer = buffer; } +bool LayerBuffer::BufferSource::transformed() const +{ + return mBufferHeap.transform ? true : Source::transformed(); +} + void LayerBuffer::BufferSource::onDraw(const Region& clip) const { sp buffer(getBuffer()); @@ -417,7 +471,7 @@ void LayerBuffer::BufferSource::onDraw(const Region& clip) const if (UNLIKELY(mTemporaryDealer == 0)) { // allocate a memory-dealer for this the first time mTemporaryDealer = mLayer.mFlinger->getSurfaceHeapManager() - ->createHeap(ISurfaceComposer::eHardware); + ->createHeap(ISurfaceComposer::eHardware); mTempBitmap.init(mTemporaryDealer); } @@ -447,16 +501,31 @@ void LayerBuffer::BufferSource::onDraw(const Region& clip) const copybit_image_t dst; hw.getDisplaySurface(&dst); const copybit_rect_t& drect - = reinterpret_cast(transformedBounds); + = reinterpret_cast(transformedBounds); const State& s(mLayer.drawingState()); region_iterator it(clip); - copybit->set_parameter(copybit, COPYBIT_TRANSFORM, mLayer.getOrientation()); + + // pick the right orientation for this buffer + int orientation = mLayer.getOrientation(); + if (UNLIKELY(mBufferHeap.transform)) { + Transform rot90; + GraphicPlane::orientationToTransfrom( + ISurfaceComposer::eOrientation90, 0, 0, &rot90); + const Transform& planeTransform(mLayer.graphicPlane(0).transform()); + const Layer::State& s(mLayer.drawingState()); + Transform tr(planeTransform * s.transform * rot90); + orientation = tr.getOrientation(); + } + + copybit->set_parameter(copybit, COPYBIT_TRANSFORM, orientation); copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, s.alpha); - copybit->set_parameter(copybit, COPYBIT_DITHER, - s.flags & ISurfaceComposer::eLayerDither ? - COPYBIT_ENABLE : COPYBIT_DISABLE); + copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_ENABLE); + err = copybit->stretch(copybit, &dst, &src.img, &drect, &src.crop, &it); + if (err != NO_ERROR) { + LOGE("copybit failed (%s)", strerror(err)); + } } if (!can_use_copybit || err) { @@ -475,10 +544,11 @@ void LayerBuffer::BufferSource::onDraw(const Region& clip) const t.data = (GGLubyte*)(intptr_t(src.img.base) + src.img.offset); const Region dirty(Rect(t.width, t.height)); mLayer.loadTexture(dirty, mTextureName, t, w, h); - mLayer.drawWithOpenGL(clip, mTextureName, t); + mLayer.drawWithOpenGL(clip, mTextureName, t, mBufferHeap.transform); } } + // --------------------------------------------------------------------------- LayerBuffer::OverlaySource::OverlaySource(LayerBuffer& layer, diff --git a/libs/surfaceflinger/LayerBuffer.h b/libs/surfaceflinger/LayerBuffer.h index 6e3d49f05373a63eb508e90049491675b9826a3f..2dc77f1501e9a46de3a978a0e2dfe7b25dc5448b 100644 --- a/libs/surfaceflinger/LayerBuffer.h +++ b/libs/surfaceflinger/LayerBuffer.h @@ -22,7 +22,7 @@ #include #include -#include +#include #include "LayerBase.h" #include "LayerBitmap.h" @@ -46,6 +46,7 @@ class LayerBuffer : public LayerBaseClient virtual void onVisibilityResolved(const Transform& planeTransform); virtual void postBuffer(ssize_t offset); virtual void unregisterBuffers(); + virtual bool transformed() const; protected: LayerBuffer& mLayer; }; @@ -67,9 +68,9 @@ public: virtual void onDraw(const Region& clip) const; virtual uint32_t doTransaction(uint32_t flags); virtual void unlockPageFlip(const Transform& planeTransform, Region& outDirtyRegion); + virtual bool transformed() const; - status_t registerBuffers(int w, int h, int hstride, int vstride, - PixelFormat format, const sp& heap); + status_t registerBuffers(const ISurface::BufferHeap& buffers); void postBuffer(ssize_t offset); void unregisterBuffers(); sp createOverlay(uint32_t w, uint32_t h, int32_t format); @@ -89,10 +90,9 @@ private: class Buffer : public LightRefBase { public: - Buffer(const sp& heap, ssize_t offset, - int w, int h, int hs, int vs, int f); + Buffer(const ISurface::BufferHeap& buffers, ssize_t offset); inline status_t getStatus() const { - return mHeap!=0 ? NO_ERROR : NO_INIT; + return mBufferHeap.heap!=0 ? NO_ERROR : NO_INIT; } inline const NativeBuffer& getBuffer() const { return mNativeBuffer; @@ -103,15 +103,13 @@ private: Buffer(const Buffer& rhs); ~Buffer(); private: - sp mHeap; - NativeBuffer mNativeBuffer; + ISurface::BufferHeap mBufferHeap; + NativeBuffer mNativeBuffer; }; class BufferSource : public Source { public: - BufferSource(LayerBuffer& layer, - int w, int h, int hstride, int vstride, - PixelFormat format, const sp& heap); + BufferSource(LayerBuffer& layer, const ISurface::BufferHeap& buffers); virtual ~BufferSource(); status_t getStatus() const { return mStatus; } @@ -121,16 +119,13 @@ private: virtual void onDraw(const Region& clip) const; virtual void postBuffer(ssize_t offset); virtual void unregisterBuffers(); + virtual bool transformed() const; private: mutable Mutex mLock; - sp mHeap; sp mBuffer; status_t mStatus; - int mWidth; - int mHeight; - int mHStride; - int mVStride; - int mFormat; + ISurface::BufferHeap mBufferHeap; + size_t mBufferSize; mutable sp mTemporaryDealer; mutable LayerBitmap mTempBitmap; mutable GLuint mTextureName; @@ -186,8 +181,9 @@ private: public: SurfaceBuffer(SurfaceID id, LayerBuffer* owner); virtual ~SurfaceBuffer(); - virtual status_t registerBuffers(int w, int h, int hstride, int vstride, - PixelFormat format, const sp& heap); + virtual status_t onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); + virtual status_t registerBuffers(const ISurface::BufferHeap& buffers); virtual void postBuffer(ssize_t offset); virtual void unregisterBuffers(); virtual sp createOverlay( diff --git a/libs/surfaceflinger/LayerOrientationAnim.cpp b/libs/surfaceflinger/LayerOrientationAnim.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b72d7ce948783c7b2c945e32bdf1aeb71e0c63a --- /dev/null +++ b/libs/surfaceflinger/LayerOrientationAnim.cpp @@ -0,0 +1,287 @@ +/* + * 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. + */ + +#define LOG_TAG "SurfaceFlinger" + +#include +#include +#include + +#include +#include + +#include + +#include + +#include "LayerBase.h" +#include "LayerOrientationAnim.h" +#include "SurfaceFlinger.h" +#include "DisplayHardware/DisplayHardware.h" +#include "OrientationAnimation.h" + +namespace android { +// --------------------------------------------------------------------------- + +const uint32_t LayerOrientationAnim::typeInfo = LayerBase::typeInfo | 0x80; +const char* const LayerOrientationAnim::typeID = "LayerOrientationAnim"; + +// --------------------------------------------------------------------------- + +LayerOrientationAnim::LayerOrientationAnim( + SurfaceFlinger* flinger, DisplayID display, + OrientationAnimation* anim, + const LayerBitmap& bitmap, + const LayerBitmap& bitmapIn) + : LayerBase(flinger, display), mAnim(anim), + mBitmap(bitmap), mBitmapIn(bitmapIn), + mTextureName(-1), mTextureNameIn(-1) +{ + mStartTime = systemTime(); + mFinishTime = 0; + mOrientationCompleted = false; + mFirstRedraw = false; + mLastNormalizedTime = 0; + mLastScale = 0; + mNeedsBlending = false; +} + +LayerOrientationAnim::~LayerOrientationAnim() +{ + if (mTextureName != -1U) { + LayerBase::deletedTextures.add(mTextureName); + } + if (mTextureNameIn != -1U) { + LayerBase::deletedTextures.add(mTextureNameIn); + } +} + +bool LayerOrientationAnim::needsBlending() const +{ + return mNeedsBlending; +} + +Point LayerOrientationAnim::getPhysicalSize() const +{ + const GraphicPlane& plane(graphicPlane(0)); + const DisplayHardware& hw(plane.displayHardware()); + return Point(hw.getWidth(), hw.getHeight()); +} + +void LayerOrientationAnim::validateVisibility(const Transform&) +{ + const Layer::State& s(drawingState()); + const Transform tr(s.transform); + const Point size(getPhysicalSize()); + uint32_t w = size.x; + uint32_t h = size.y; + mTransformedBounds = tr.makeBounds(w, h); + mLeft = tr.tx(); + mTop = tr.ty(); + transparentRegionScreen.clear(); + mTransformed = true; + mCanUseCopyBit = false; + copybit_device_t* copybit = mFlinger->getBlitEngine(); + if (copybit) { + mCanUseCopyBit = true; + } +} + +void LayerOrientationAnim::onOrientationCompleted() +{ + mFinishTime = systemTime(); + mOrientationCompleted = true; + mFirstRedraw = true; + mNeedsBlending = true; + mFlinger->invalidateLayerVisibility(this); +} + +void LayerOrientationAnim::onDraw(const Region& clip) const +{ + // Animation... + const float MIN_SCALE = 0.5f; + const float DURATION = ms2ns(200); + const float BOUNCES_PER_SECOND = 1.618f; + const float BOUNCES_AMPLITUDE = 1.0f/32.0f; + + const nsecs_t now = systemTime(); + float scale, alpha; + + if (mOrientationCompleted) { + if (mFirstRedraw) { + mFirstRedraw = false; + + // make a copy of what's on screen + copybit_image_t image; + mBitmapIn.getBitmapSurface(&image); + const DisplayHardware& hw(graphicPlane(0).displayHardware()); + hw.copyBackToImage(image); + + // and erase the screen for this round + glDisable(GL_BLEND); + glDisable(GL_DITHER); + glDisable(GL_SCISSOR_TEST); + glClearColor(0,0,0,0); + glClear(GL_COLOR_BUFFER_BIT); + + // FIXME: code below is gross + mNeedsBlending = false; + LayerOrientationAnim* self(const_cast(this)); + mFlinger->invalidateLayerVisibility(self); + } + + // make sure pick-up where we left off + const float duration = DURATION * mLastNormalizedTime; + const float normalizedTime = (float(now - mFinishTime) / duration); + if (normalizedTime <= 1.0f) { + const float squaredTime = normalizedTime*normalizedTime; + scale = (1.0f - mLastScale)*squaredTime + mLastScale; + alpha = (1.0f - normalizedTime); + alpha *= alpha; + alpha *= alpha; + } else { + mAnim->onAnimationFinished(); + scale = 1.0f; + alpha = 0.0f; + } + } else { + const float normalizedTime = float(now - mStartTime) / DURATION; + if (normalizedTime <= 1.0f) { + mLastNormalizedTime = normalizedTime; + const float squaredTime = normalizedTime*normalizedTime; + scale = (MIN_SCALE-1.0f)*squaredTime + 1.0f; + alpha = 1.0f; + } else { + mLastNormalizedTime = 1.0f; + const float to_seconds = DURATION / seconds(1); + const float phi = BOUNCES_PER_SECOND * + (((normalizedTime - 1.0f) * to_seconds)*M_PI*2); + scale = MIN_SCALE + BOUNCES_AMPLITUDE * (1.0f - cosf(phi)); + alpha = 1.0f; + } + mLastScale = scale; + } + drawScaled(scale, alpha); +} + +void LayerOrientationAnim::drawScaled(float f, float alpha) const +{ + copybit_image_t dst; + const GraphicPlane& plane(graphicPlane(0)); + const DisplayHardware& hw(plane.displayHardware()); + hw.getDisplaySurface(&dst); + + // clear screen + // TODO: with update on demand, we may be able + // to not erase the screen at all during the animation + if (!mOrientationCompleted) { + glDisable(GL_BLEND); + glDisable(GL_DITHER); + glDisable(GL_SCISSOR_TEST); + glClearColor(0,0,0,0); + glClear(GL_COLOR_BUFFER_BIT); + } + + const int w = dst.w*f; + const int h = dst.h*f; + const int xc = uint32_t(dst.w-w)/2; + const int yc = uint32_t(dst.h-h)/2; + const copybit_rect_t drect = { xc, yc, xc+w, yc+h }; + + copybit_image_t src; + mBitmap.getBitmapSurface(&src); + const copybit_rect_t srect = { 0, 0, src.w, src.h }; + + int err = NO_ERROR; + const int can_use_copybit = canUseCopybit(); + if (can_use_copybit) { + copybit_device_t* copybit = mFlinger->getBlitEngine(); + copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0); + copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_ENABLE); + + if (alpha < 1.0f) { + copybit_image_t srcIn; + mBitmapIn.getBitmapSurface(&srcIn); + region_iterator it(Region(Rect( drect.l, drect.t, drect.r, drect.b ))); + copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 0xFF); + err = copybit->stretch(copybit, &dst, &srcIn, &drect, &srect, &it); + } + + if (!err && alpha > 0.0f) { + region_iterator it(Region(Rect( drect.l, drect.t, drect.r, drect.b ))); + copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, int(alpha*255)); + err = copybit->stretch(copybit, &dst, &src, &drect, &srect, &it); + } + LOGE_IF(err != NO_ERROR, "copybit failed (%s)", strerror(err)); + } + if (!can_use_copybit || err) { + GGLSurface t; + t.version = sizeof(GGLSurface); + t.width = src.w; + t.height = src.h; + t.stride = src.w; + t.vstride= src.h; + t.format = src.format; + t.data = (GGLubyte*)(intptr_t(src.base) + src.offset); + + Transform tr; + tr.set(f,0,0,f); + tr.set(xc, yc); + + // FIXME: we should not access mVertices and mDrawingState like that, + // but since we control the animation, we know it's going to work okay. + // eventually we'd need a more formal way of doing things like this. + LayerOrientationAnim& self(const_cast(*this)); + tr.transform(self.mVertices[0], 0, 0); + tr.transform(self.mVertices[1], 0, src.h); + tr.transform(self.mVertices[2], src.w, src.h); + tr.transform(self.mVertices[3], src.w, 0); + if (!(mFlags & DisplayHardware::SLOW_CONFIG)) { + // Too slow to do this in software + self.mDrawingState.flags |= ISurfaceComposer::eLayerFilter; + } + + if (alpha < 1.0f) { + copybit_image_t src; + mBitmapIn.getBitmapSurface(&src); + t.data = (GGLubyte*)(intptr_t(src.base) + src.offset); + if (UNLIKELY(mTextureNameIn == -1LU)) { + mTextureNameIn = createTexture(); + GLuint w=0, h=0; + const Region dirty(Rect(t.width, t.height)); + loadTexture(dirty, mTextureNameIn, t, w, h); + } + self.mDrawingState.alpha = 255; + const Region clip(Rect( drect.l, drect.t, drect.r, drect.b )); + drawWithOpenGL(clip, mTextureName, t); + } + + t.data = (GGLubyte*)(intptr_t(src.base) + src.offset); + if (UNLIKELY(mTextureName == -1LU)) { + mTextureName = createTexture(); + GLuint w=0, h=0; + const Region dirty(Rect(t.width, t.height)); + loadTexture(dirty, mTextureName, t, w, h); + } + self.mDrawingState.alpha = int(alpha*255); + const Region clip(Rect( drect.l, drect.t, drect.r, drect.b )); + drawWithOpenGL(clip, mTextureName, t); + } +} + +// --------------------------------------------------------------------------- + +}; // namespace android diff --git a/libs/surfaceflinger/LayerScreenshot.h b/libs/surfaceflinger/LayerOrientationAnim.h similarity index 53% rename from libs/surfaceflinger/LayerScreenshot.h rename to libs/surfaceflinger/LayerOrientationAnim.h index 2d9a8ec6d7af8b89f0077c464327eb1f03e1e4e9..73676859bc035ee5d9e945113e2e5e948f979c20 100644 --- a/libs/surfaceflinger/LayerScreenshot.h +++ b/libs/surfaceflinger/LayerOrientationAnim.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef ANDROID_LAYER_SCREENSHOT_H -#define ANDROID_LAYER_SCREENSHOT_H +#ifndef ANDROID_LAYER_ORIENTATION_ANIM_H +#define ANDROID_LAYER_ORIENTATION_ANIM_H #include #include @@ -23,12 +23,14 @@ #include #include "LayerBase.h" +#include "LayerBitmap.h" namespace android { // --------------------------------------------------------------------------- +class OrientationAnimation; -class LayerScreenshot : public LayerBase +class LayerOrientationAnim : public LayerBase { public: static const uint32_t typeInfo; @@ -36,22 +38,38 @@ public: virtual char const* getTypeID() const { return typeID; } virtual uint32_t getTypeInfo() const { return typeInfo; } - LayerScreenshot(SurfaceFlinger* flinger, DisplayID display); - virtual ~LayerScreenshot(); + LayerOrientationAnim(SurfaceFlinger* flinger, DisplayID display, + OrientationAnimation* anim, + const LayerBitmap& zoomOut, + const LayerBitmap& zoomIn); + virtual ~LayerOrientationAnim(); + + void onOrientationCompleted(); virtual void onDraw(const Region& clip) const; - virtual bool needsBlending() const { return true; } + virtual Point getPhysicalSize() const; + virtual void validateVisibility(const Transform& globalTransform); + virtual bool needsBlending() const; virtual bool isSecure() const { return false; } - - void takeScreenshot(Mutex& lock, Parcel* reply); - private: - mutable Condition mCV; - Parcel* mReply; + void drawScaled(float scale, float alpha) const; + + OrientationAnimation* mAnim; + LayerBitmap mBitmap; + LayerBitmap mBitmapIn; + nsecs_t mStartTime; + nsecs_t mFinishTime; + bool mOrientationCompleted; + mutable bool mFirstRedraw; + mutable float mLastNormalizedTime; + mutable float mLastScale; + mutable GLuint mTextureName; + mutable GLuint mTextureNameIn; + mutable bool mNeedsBlending; }; // --------------------------------------------------------------------------- }; // namespace android -#endif // ANDROID_LAYER_SCREENSHOT_H +#endif // ANDROID_LAYER_ORIENTATION_ANIM_H diff --git a/libs/surfaceflinger/OrientationAnimation.cpp b/libs/surfaceflinger/OrientationAnimation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6f1326b1003b07ce59514de08ddfd02f10586ba --- /dev/null +++ b/libs/surfaceflinger/OrientationAnimation.cpp @@ -0,0 +1,155 @@ +/* + * 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. + */ + +#define LOG_TAG "SurfaceFlinger" + +#include +#include +#include + +#include "LayerOrientationAnim.h" +#include "OrientationAnimation.h" +#include "SurfaceFlinger.h" +#include "VRamHeap.h" + +#include "DisplayHardware/DisplayHardware.h" + +namespace android { + +// --------------------------------------------------------------------------- + +OrientationAnimation::OrientationAnimation(const sp& flinger) + : mFlinger(flinger), mLayerOrientationAnim(NULL), mState(DONE) +{ + // allocate a memory-dealer for this the first time + mTemporaryDealer = mFlinger->getSurfaceHeapManager()->createHeap( + ISurfaceComposer::eHardware); +} + +OrientationAnimation::~OrientationAnimation() +{ +} + +void OrientationAnimation::onOrientationChanged() +{ + if (mState == DONE) + mState = PREPARE; +} + +void OrientationAnimation::onAnimationFinished() +{ + if (mState != DONE) + mState = FINISH; +} + +bool OrientationAnimation::run_impl() +{ + bool skip_frame; + switch (mState) { + default: + case DONE: + skip_frame = done(); + break; + case PREPARE: + skip_frame = prepare(); + break; + case PHASE1: + skip_frame = phase1(); + break; + case PHASE2: + skip_frame = phase2(); + break; + case FINISH: + skip_frame = finished(); + break; + } + return skip_frame; +} + +bool OrientationAnimation::done() +{ + if (mFlinger->isFrozen()) { + // we are not allowed to draw, but pause a bit to make sure + // apps don't end up using the whole CPU, if they depend on + // surfaceflinger for synchronization. + usleep(8333); // 8.3ms ~ 120fps + return true; + } + return false; +} + +bool OrientationAnimation::prepare() +{ + mState = PHASE1; + + const GraphicPlane& plane(mFlinger->graphicPlane(0)); + const DisplayHardware& hw(plane.displayHardware()); + const uint32_t w = hw.getWidth(); + const uint32_t h = hw.getHeight(); + + LayerBitmap bitmap; + bitmap.init(mTemporaryDealer); + bitmap.setBits(w, h, 1, hw.getFormat()); + + LayerBitmap bitmapIn; + bitmapIn.init(mTemporaryDealer); + bitmapIn.setBits(w, h, 1, hw.getFormat()); + + copybit_image_t front; + bitmap.getBitmapSurface(&front); + hw.copyFrontToImage(front); + + LayerOrientationAnim* l = new LayerOrientationAnim( + mFlinger.get(), 0, this, bitmap, bitmapIn); + l->initStates(w, h, 0); + l->setLayer(INT_MAX-1); + mFlinger->addLayer(l); + mLayerOrientationAnim = l; + return true; +} + +bool OrientationAnimation::phase1() +{ + if (mFlinger->isFrozen() == false) { + // start phase 2 + mState = PHASE2; + mLayerOrientationAnim->onOrientationCompleted(); + mLayerOrientationAnim->invalidate(); + return true; + + } + mLayerOrientationAnim->invalidate(); + return false; +} + +bool OrientationAnimation::phase2() +{ + // do the 2nd phase of the animation + mLayerOrientationAnim->invalidate(); + return false; +} + +bool OrientationAnimation::finished() +{ + mState = DONE; + mFlinger->removeLayer(mLayerOrientationAnim); + mLayerOrientationAnim = NULL; + return true; +} + +// --------------------------------------------------------------------------- + +}; // namespace android diff --git a/libs/surfaceflinger/OrientationAnimation.h b/libs/surfaceflinger/OrientationAnimation.h new file mode 100644 index 0000000000000000000000000000000000000000..ba33fcedd405549d11705745c444fd4adc60c99c --- /dev/null +++ b/libs/surfaceflinger/OrientationAnimation.h @@ -0,0 +1,73 @@ +/* + * 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. + */ + +#ifndef ANDROID_ORIENTATION_ANIMATION_H +#define ANDROID_ORIENTATION_ANIMATION_H + +#include +#include + +#include "SurfaceFlinger.h" + +namespace android { + +// --------------------------------------------------------------------------- + +class SurfaceFlinger; +class MemoryDealer; +class LayerOrientationAnim; + +class OrientationAnimation +{ +public: + OrientationAnimation(const sp& flinger); + virtual ~OrientationAnimation(); + + void onOrientationChanged(); + void onAnimationFinished(); + inline bool run() { + if (LIKELY(mState == DONE)) + return false; + return run_impl(); + } + +private: + enum { + DONE = 0, + PREPARE, + PHASE1, + PHASE2, + FINISH + }; + + bool run_impl(); + bool done(); + bool prepare(); + bool phase1(); + bool phase2(); + bool finished(); + + sp mFlinger; + sp mTemporaryDealer; + LayerOrientationAnim* mLayerOrientationAnim; + int mState; +}; + +// --------------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_ORIENTATION_ANIMATION_H diff --git a/libs/surfaceflinger/RFBServer.cpp b/libs/surfaceflinger/RFBServer.cpp deleted file mode 100644 index c2c1989413884d486e440a5176ce309d1d8d1d24..0000000000000000000000000000000000000000 --- a/libs/surfaceflinger/RFBServer.cpp +++ /dev/null @@ -1,722 +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. - */ - -#define LOG_TAG "RFBServer" - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include - -#include - -#include -#include - -#ifdef HAVE_ANDROID_OS -#include -#endif - -#include "RFBServer.h" -#include "SurfaceFlinger.h" - -/* BUG=773511: this is a temporary hack required while developing the new - set of "clean kernel headers" for the Bionic C library. */ -#ifndef KEY_STAR -#define KEY_STAR 227 -#endif -#ifndef KEY_SHARP -#define KEY_SHARP 228 -#endif -#ifndef KEY_SOFT1 -#define KEY_SOFT1 229 -#endif -#ifndef KEY_SOFT2 -#define KEY_SOFT2 230 -#endif -#ifndef KEY_CENTER -#define KEY_CENTER 232 -#endif - -// ---------------------------------------------------------------------------- - -#define DEBUG_MSG 0 - -// ---------------------------------------------------------------------------- - -namespace android { - -const int VNC_PORT = 5900; - -RFBServer::RFBServer(uint32_t w, uint32_t h, android::PixelFormat format) - : Thread(false), mFD(-1), mStatus(NO_INIT), mIoVec(0) -{ - mFrameBuffer.version = sizeof(mFrameBuffer); - mFrameBuffer.width = w; - mFrameBuffer.height = h; - mFrameBuffer.stride = w; - mFrameBuffer.format = format; - mFrameBuffer.data = 0; -} - -RFBServer::~RFBServer() -{ - if (mRobinThread != 0) { - // ask the thread to exit first - mRobinThread->exitAndWait(); - } - - free(mFrameBuffer.data); - - delete [] mIoVec; -} - -void RFBServer::onFirstRef() -{ - run("Batman"); -} - -status_t RFBServer::readyToRun() -{ - LOGI("RFB server ready to run"); - return NO_ERROR; -} - -bool RFBServer::threadLoop() -{ - struct sockaddr addr; - socklen_t alen; - int serverfd = -1; - int port = VNC_PORT; - - do { - retry: - if (serverfd < 0) { - serverfd = socket_loopback_server(port, SOCK_STREAM); - if (serverfd < 0) { - if ((errno == EADDRINUSE) && (port < (VNC_PORT+10))) { - LOGW("port %d already in use, trying %d", port, port+1); - port++; - goto retry; - } - LOGE("couldn't create socket, port=%d, error %d (%s)", - port, errno, strerror(errno)); - sleep(1); - break; - } - fcntl(serverfd, F_SETFD, FD_CLOEXEC); - } - - alen = sizeof(addr); - mFD = accept(serverfd, &addr, &alen); - - if (mFD < 0) { - LOGE("couldn't accept(), error %d (%s)", errno, strerror(errno)); - // we could have run out of file descriptors, wait a bit and - // try again. - sleep(1); - goto retry; - } - fcntl(mFD, F_SETFD, FD_CLOEXEC); - - // send protocol version and Authentication method - mStatus = NO_ERROR; - handshake(3, 3, Authentication::None); - - if (alive()) { - // create the thread we use to send data to the client - mRobinThread = new ServerThread(this); - } - - while( alive() ) { - // client message must be destroyed at each iteration - // (most of the time this is a no-op) - ClientMessage msg; - waitForClientMessage(msg); - if (alive()) { - handleClientMessage(msg); - } - } - - } while( alive() ); - - // free-up some resources - if (mRobinThread != 0) { - mRobinThread->exitAndWait(); - mRobinThread.clear(); - } - - free(mFrameBuffer.data); - mFrameBuffer.data = 0; - - close(mFD); - close(serverfd); - mFD = -1; - - // we'll try again - return true; -} - -// ---------------------------------------------------------------------------- - -RFBServer::ServerThread::ServerThread(const sp& receiver) - : Thread(false), mReceiver(receiver) -{ - LOGD("RFB Server Thread created"); -} - -RFBServer::ServerThread::~ServerThread() -{ - LOGD("RFB Server Thread destroyed"); -} - -void RFBServer::ServerThread::onFirstRef() -{ - mUpdateBarrier.close(); - run("Robin"); -} - -status_t RFBServer::ServerThread::readyToRun() -{ - return NO_ERROR; -} - -void RFBServer::ServerThread::wake() -{ - mUpdateBarrier.open(); -} - -void RFBServer::ServerThread::exitAndWait() -{ - requestExit(); - mUpdateBarrier.open(); - requestExitAndWait(); -} - -bool RFBServer::ServerThread::threadLoop() -{ - sp receiver(mReceiver.promote()); - if (receiver == 0) - return false; - - // wait for something to do - mUpdateBarrier.wait(); - - // we're asked to quit, abort everything - if (exitPending()) - return false; - - mUpdateBarrier.close(); - - // process updates - receiver->sendFrameBufferUpdates(); - return !exitPending(); -} - -// ---------------------------------------------------------------------------- - -void RFBServer::handshake(uint8_t major, uint8_t minor, uint32_t auth) -{ - ProtocolVersion protocolVersion(major, minor); - if( !write(protocolVersion) ) - return; - - if ( !read(protocolVersion) ) - return; - - int maj, min; - if ( protocolVersion.decode(maj, min) != NO_ERROR ) { - mStatus = -1; - return; - } - -#if DEBUG_MSG - LOGD("client protocol string: <%s>", (char*)protocolVersion.payload()); - LOGD("client wants protocol version %d.%d\n", maj, min); -#endif - - Authentication authentication(auth); - if( !write(authentication) ) - return; - - ClientInitialization clientInit; - if ( !read(clientInit) ) - return; - -#if DEBUG_MSG - LOGD("client initialization: sharedFlags = %d\n", clientInit.sharedFlags()); -#endif - - ServerInitialization serverInit("Android RFB"); - ServerInitialization::Payload& message(serverInit.message()); - message.framebufferWidth = htons(mFrameBuffer.width); - message.framebufferHeight = htons(mFrameBuffer.height); - message.serverPixelFormat.bitsPerPixel = 16; - message.serverPixelFormat.depth = 16; - message.serverPixelFormat.bigEndianFlag = 0; - message.serverPixelFormat.trueColorFlag = 1; - message.serverPixelFormat.redMax = htons((1<<5)-1); - message.serverPixelFormat.greenMax = htons((1<<6)-1); - message.serverPixelFormat.blueMax = htons((1<<5)-1); - message.serverPixelFormat.redShift = 11; - message.serverPixelFormat.greenShift = 5; - message.serverPixelFormat.blueShift = 0; - - mIoVec = new iovec[mFrameBuffer.height]; - - write(serverInit); -} - -void RFBServer::handleClientMessage(const ClientMessage& msg) -{ - switch(msg.type()) { - case SET_PIXEL_FORMAT: - handleSetPixelFormat(msg.messages().setPixelFormat); - break; - case SET_ENCODINGS: - handleSetEncodings(msg.messages().setEncodings); - break; - case FRAME_BUFFER_UPDATE_REQ: - handleFrameBufferUpdateReq(msg.messages().frameBufferUpdateRequest); - break; - case KEY_EVENT: - handleKeyEvent(msg.messages().keyEvent); - break; - } -} - -void RFBServer::handleSetPixelFormat(const SetPixelFormat& msg) -{ - if (!validatePixelFormat(msg.pixelFormat)) { - LOGE("The builtin VNC server only supports the RGB 565 pixel format"); - LOGD("requested pixel format:"); - LOGD("bitsPerPixel: %d", msg.pixelFormat.bitsPerPixel); - LOGD("depth: %d", msg.pixelFormat.depth); - LOGD("bigEndianFlag: %d", msg.pixelFormat.bigEndianFlag); - LOGD("trueColorFlag: %d", msg.pixelFormat.trueColorFlag); - LOGD("redmax: %d", ntohs(msg.pixelFormat.redMax)); - LOGD("bluemax: %d", ntohs(msg.pixelFormat.greenMax)); - LOGD("greenmax: %d", ntohs(msg.pixelFormat.blueMax)); - LOGD("redshift: %d", msg.pixelFormat.redShift); - LOGD("greenshift: %d", msg.pixelFormat.greenShift); - LOGD("blueshift: %d", msg.pixelFormat.blueShift); - mStatus = -1; - } -} - -bool RFBServer::validatePixelFormat(const PixelFormat& pf) -{ - if ((pf.bitsPerPixel != 16) || (pf.depth != 16)) - return false; - - if (pf.bigEndianFlag || !pf.trueColorFlag) - return false; - - if (ntohs(pf.redMax)!=0x1F || - ntohs(pf.greenMax)!=0x3F || - ntohs(pf.blueMax)!=0x1F) { - return false; - } - - if (pf.redShift!=11 || pf.greenShift!=5 || pf.blueShift!=0) - return false; - - return true; -} - -void RFBServer::handleSetEncodings(const SetEncodings& msg) -{ - /* From the RFB specification: - Sets the encoding types in which pixel data can be sent by the server. - The order of the encoding types given in this message is a hint by the - client as to its preference (the first encoding specified being most - preferred). The server may or may not choose to make use of this hint. - Pixel data may always be sent in raw encoding even if not specified - explicitly here. - */ - - LOGW("SetEncodings received. Only RAW is supported."); -} - -void RFBServer::handleFrameBufferUpdateReq(const FrameBufferUpdateRequest& msg) -{ -#if DEBUG_MSG - LOGD("handle FrameBufferUpdateRequest"); -#endif - - Rect r; - r.left = ntohs(msg.x); - r.top = ntohs(msg.y); - r.right = r.left + ntohs(msg.width); - r.bottom = r.top + ntohs(msg.height); - - Mutex::Autolock _l(mRegionLock); - mClientRegionRequest.set(r); - if (!msg.incremental) - mDirtyRegion.orSelf(r); - - mRobinThread->wake(); -} - -void RFBServer::handleKeyEvent(const KeyEvent& msg) -{ -#ifdef HAVE_ANDROID_OS - - int scancode = 0; - int code = ntohl(msg.key); - - if (code>='0' && code<='9') { - scancode = (code & 0xF) - 1; - if (scancode<0) scancode += 10; - scancode += KEY_1; - } else if (code>=0xFF50 && code<=0xFF58) { - static const uint16_t map[] = - { KEY_HOME, KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN, - KEY_SOFT1, KEY_SOFT2, KEY_END, 0 }; - scancode = map[code & 0xF]; - } else if (code>=0xFFE1 && code<=0xFFEE) { - static const uint16_t map[] = - { KEY_LEFTSHIFT, KEY_LEFTSHIFT, - KEY_COMPOSE, KEY_COMPOSE, - KEY_LEFTSHIFT, KEY_LEFTSHIFT, - 0,0, - KEY_LEFTALT, KEY_RIGHTALT, - 0, 0, 0, 0 }; - scancode = map[code & 0xF]; - } else if ((code>='A' && code<='Z') || (code>='a' && code<='z')) { - static const uint16_t map[] = { - KEY_A, KEY_B, KEY_C, KEY_D, KEY_E, - KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, - KEY_K, KEY_L, KEY_M, KEY_N, KEY_O, - KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T, - KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z }; - scancode = map[(code & 0x5F) - 'A']; - } else { - switch (code) { - case 0x0003: scancode = KEY_CENTER; break; - case 0x0020: scancode = KEY_SPACE; break; - case 0x0023: scancode = KEY_SHARP; break; - case 0x0033: scancode = KEY_SHARP; break; - case 0x002C: scancode = KEY_COMMA; break; - case 0x003C: scancode = KEY_COMMA; break; - case 0x002E: scancode = KEY_DOT; break; - case 0x003E: scancode = KEY_DOT; break; - case 0x002F: scancode = KEY_SLASH; break; - case 0x003F: scancode = KEY_SLASH; break; - case 0x0032: scancode = KEY_EMAIL; break; - case 0x0040: scancode = KEY_EMAIL; break; - case 0xFF08: scancode = KEY_BACKSPACE; break; - case 0xFF1B: scancode = KEY_BACK; break; - case 0xFF09: scancode = KEY_TAB; break; - case 0xFF0D: scancode = KEY_ENTER; break; - case 0x002A: scancode = KEY_STAR; break; - case 0xFFBE: scancode = KEY_SEND; break; // F1 - case 0xFFBF: scancode = KEY_END; break; // F2 - case 0xFFC0: scancode = KEY_HOME; break; // F3 - case 0xFFC5: scancode = KEY_POWER; break; // F8 - } - } - -#if DEBUG_MSG - LOGD("handle KeyEvent 0x%08x, %d, scancode=%d\n", code, msg.downFlag, scancode); -#endif - - if (scancode) { - mEventInjector.injectKey(uint16_t(scancode), - msg.downFlag ? EventInjector::DOWN : EventInjector::UP); - } -#endif -} - -void RFBServer::waitForClientMessage(ClientMessage& msg) -{ - if ( !read(msg.payload(), 1) ) - return; - - switch(msg.type()) { - - case SET_PIXEL_FORMAT: - read(msg.payload(1), sizeof(SetPixelFormat)-1); - break; - - case FIX_COLOUR_MAP_ENTRIES: - mStatus = UNKNOWN_ERROR; - return; - - case SET_ENCODINGS: - { - if ( !read(msg.payload(1), sizeof(SetEncodings)-1) ) - return; - - size_t size = ntohs( msg.messages().setEncodings.numberOfEncodings ) * 4; - if (msg.resize(sizeof(SetEncodings) + size) != NO_ERROR) { - mStatus = NO_MEMORY; - return; - } - - if ( !read(msg.payload(sizeof(SetEncodings)), size) ) - return; - - break; - } - - case FRAME_BUFFER_UPDATE_REQ: - read(msg.payload(1), sizeof(FrameBufferUpdateRequest)-1); - break; - - case KEY_EVENT: - read(msg.payload(1), sizeof(KeyEvent)-1); - break; - - case POINTER_EVENT: - read(msg.payload(1), sizeof(PointerEvent)-1); - break; - - case CLIENT_CUT_TEXT: - { - if ( !read(msg.payload(1), sizeof(ClientCutText)-1) ) - return; - - size_t size = ntohl( msg.messages().clientCutText.length ); - if (msg.resize(sizeof(ClientCutText) + size) != NO_ERROR) { - mStatus = NO_MEMORY; - return; - } - - if ( !read(msg.payload(sizeof(SetEncodings)), size) ) - return; - - break; - } - - default: - LOGE("Unknown Message %d", msg.type()); - mStatus = UNKNOWN_ERROR; - return; - } -} - -// ---------------------------------------------------------------------------- - -bool RFBServer::write(const Message& msg) -{ - write(msg.payload(), msg.size()); - return alive(); -} - -bool RFBServer::read(Message& msg) -{ - read(msg.payload(), msg.size()); - return alive(); -} - -bool RFBServer::write(const void* buffer, int size) -{ - int wr = ::write(mFD, buffer, size); - if (wr != size) { - //LOGE("write(%d) error %d (%s)", size, wr, strerror(errno)); - mStatus = (wr == -1) ? errno : -1; - } - return alive(); -} - -bool RFBServer::read(void* buffer, int size) -{ - int rd = ::read(mFD, buffer, size); - if (rd != size) { - //LOGE("read(%d) error %d (%s)", size, rd, strerror(errno)); - mStatus = (rd == -1) ? errno : -1; - } - return alive(); -} - -bool RFBServer::alive() const -{ - return mStatus == 0; -} - -bool RFBServer::isConnected() const -{ - return alive(); -} - -// ---------------------------------------------------------------------------- - -void RFBServer::frameBufferUpdated(const GGLSurface& front, const Region& reg) -{ - Mutex::Autolock _l(mRegionLock); - - // update dirty region - mDirtyRegion.orSelf(reg); - - // remember the front-buffer - mFrontBuffer = front; - - // The client has not requested anything, don't do anything more - if (mClientRegionRequest.isEmpty()) - return; - - // wake the sending thread up - mRobinThread->wake(); -} - -void RFBServer::sendFrameBufferUpdates() -{ - Vector rects; - size_t countRects; - GGLSurface fb; - - { // Scope for the lock - Mutex::Autolock _l(mRegionLock); - if (mFrontBuffer.data == 0) - return; - - const Region reg( mDirtyRegion.intersect(mClientRegionRequest) ); - if (reg.isEmpty()) - return; - - mDirtyRegion.subtractSelf(reg); - countRects = reg.rects(rects); - - // copy the frame-buffer so we can stay responsive - size_t bytesPerPix = bytesPerPixel(mFrameBuffer.format); - size_t bpr = mFrameBuffer.stride * bytesPerPix; - if (mFrameBuffer.data == 0) { - mFrameBuffer.data = (GGLubyte*)malloc(bpr * mFrameBuffer.height); - if (mFrameBuffer.data == 0) - return; - } - - memcpy(mFrameBuffer.data, mFrontBuffer.data, bpr*mFrameBuffer.height); - fb = mFrameBuffer; - } - - FrameBufferUpdate msgHeader; - msgHeader.type = 0; - msgHeader.numberOfRectangles = htons(countRects); - write(&msgHeader, sizeof(msgHeader)); - - Rectangle rectangle; - for (size_t i=0 ; i(fb.data) + offset; - iovec* iov = mIoVec; - while (h--) { - iov->iov_base = src; - iov->iov_len = bytes; - src += bpr; - iov++; - } - size_t iovcnt = iov - mIoVec; - int wr = ::writev(mFD, mIoVec, iovcnt); - if (wr < 0) { - //LOGE("write(%d) error %d (%s)", size, wr, strerror(errno)); - mStatus = errno; - } - } -} - -// ---------------------------------------------------------------------------- - -RFBServer::Message::Message(size_t size) - : mSize(size), mAllocatedSize(size) -{ - mPayload = malloc(size); -} - -RFBServer::Message::Message(void* payload, size_t size) - : mPayload(payload), mSize(size), mAllocatedSize(0) -{ -} - -RFBServer::Message::~Message() -{ - if (mAllocatedSize) - free(mPayload); -} - -status_t RFBServer::Message::resize(size_t size) -{ - if (size > mAllocatedSize) { - void* newp; - if (mAllocatedSize) { - newp = realloc(mPayload, size); - if (!newp) return NO_MEMORY; - } else { - newp = malloc(size); - if (!newp) return NO_MEMORY; - memcpy(newp, mPayload, mSize); - mAllocatedSize = size; - } - mPayload = newp; - } - mSize = size; - return NO_ERROR; -} - -// ---------------------------------------------------------------------------- - -RFBServer::EventInjector::EventInjector() - : mFD(-1) -{ -} - -RFBServer::EventInjector::~EventInjector() -{ -} - -void RFBServer::EventInjector::injectKey(uint16_t code, uint16_t value) -{ -#ifdef HAVE_ANDROID_OS - // XXX: we need to open the right event device - int version; - mFD = open("/dev/input/event0", O_RDWR); - ioctl(mFD, EVIOCGVERSION, &version); - - input_event ev; - memset(&ev, 0, sizeof(ev)); - ev.type = EV_KEY; - ev.code = code; - ev.value = value; - ::write(mFD, &ev, sizeof(ev)); - - close(mFD); - mFD = -1; -#endif -} - - -}; // namespace android - diff --git a/libs/surfaceflinger/RFBServer.h b/libs/surfaceflinger/RFBServer.h deleted file mode 100644 index 420912ed724da32afbac83be183c72108485e3fa..0000000000000000000000000000000000000000 --- a/libs/surfaceflinger/RFBServer.h +++ /dev/null @@ -1,316 +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. - */ - -#ifndef ANDROID_RFB_SERVER_H -#define ANDROID_RFB_SERVER_H - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -#include "Barrier.h" - -namespace android { - -class SurfaceFlinger; - -class RFBServer : public Thread -{ -public: - RFBServer(uint32_t w, uint32_t h, android::PixelFormat format); - virtual ~RFBServer(); - - void frameBufferUpdated(const GGLSurface& front, const Region& reg); - bool isConnected() const; - -private: - typedef uint8_t card8; - typedef uint16_t card16; - typedef uint32_t card32; - - struct Message { - Message(size_t size); - virtual ~Message(); - void* payload(int offset=0) { - return static_cast(mPayload)+offset; - } - void const * payload(int offset=0) const { - return static_cast(mPayload)+offset; - } - size_t size() const { return mSize; } - protected: - Message(void* payload, size_t size); - status_t resize(size_t size); - private: - void* mPayload; - size_t mSize; - size_t mAllocatedSize; - }; - - struct ProtocolVersion : public Message { - ProtocolVersion(uint8_t major, uint8_t minor) - : Message(&messageData, 12) { - char* p = static_cast(payload()); - snprintf(p, 13, "RFB %03u.%03u%c", major, minor, 0xA); - } - status_t decode(int& maj, int& min) { - char* p = static_cast(payload()); - int n = sscanf(p, "RFB %03u.%03u", &maj, &min); - return (n == 2) ? NO_ERROR : NOT_ENOUGH_DATA; - } - private: - char messageData[12+1]; - }; - - struct Authentication : public Message { - enum { Failed=0, None=1, Vnc=2 }; - Authentication(int auth) : Message(&messageData, 4) { - *static_cast(payload()) = htonl(auth); - } - private: - card32 messageData; - }; - - struct ClientInitialization : public Message { - ClientInitialization() : Message(&messageData, 1) { } - int sharedFlags() { - return messageData; - } - private: - card8 messageData; - }; - - struct PixelFormat { - card8 bitsPerPixel; - card8 depth; - card8 bigEndianFlag; - card8 trueColorFlag; - card16 redMax; - card16 greenMax; - card16 blueMax; - card8 redShift; - card8 greenShift; - card8 blueShift; - uint8_t padding[3]; - } __attribute__((packed)); - - struct ServerInitialization : public Message { - ServerInitialization(char const * name) - : Message(sizeof(Payload) + strlen(name)) - { - const size_t nameLength = size() - sizeof(Payload); - message().nameLength = htonl(nameLength); - memcpy((char*)message().nameString, name,nameLength); - } - struct Payload { - card16 framebufferWidth; - card16 framebufferHeight; - PixelFormat serverPixelFormat; - card32 nameLength; - card8 nameString[0]; - } __attribute__((packed)); - Payload& message() { - return *static_cast(payload()); - } - }; - - // client messages... - - struct SetPixelFormat { - card8 type; - uint8_t padding[3]; - PixelFormat pixelFormat; - } __attribute__((packed)); - - struct SetEncodings { - enum { Raw=0, CoR=1, RRE=2, CoRRE=4, Hextile=5 }; - card8 type; - uint8_t padding; - card16 numberOfEncodings; - card32 encodings[0]; - } __attribute__((packed)); - - struct FrameBufferUpdateRequest { - card8 type; - card8 incremental; - card16 x; - card16 y; - card16 width; - card16 height; - } __attribute__((packed)); - - struct KeyEvent { - card8 type; - card8 downFlag; - uint8_t padding[2]; - card32 key; - } __attribute__((packed)); - - struct PointerEvent { - card8 type; - card8 buttonMask; - card16 x; - card16 y; - } __attribute__((packed)); - - struct ClientCutText { - card8 type; - uint8_t padding[3]; - card32 length; - card8 text[0]; - } __attribute__((packed)); - - union ClientMessages { - card8 type; - SetPixelFormat setPixelFormat; - SetEncodings setEncodings; - FrameBufferUpdateRequest frameBufferUpdateRequest; - KeyEvent keyEvent; - PointerEvent pointerEvent; - ClientCutText clientCutText; - }; - - struct Rectangle { - card16 x; - card16 y; - card16 w; - card16 h; - card32 encoding; - } __attribute__((packed)); - - struct FrameBufferUpdate { - card8 type; - uint8_t padding; - card16 numberOfRectangles; - Rectangle rectangles[0]; - } __attribute__((packed)); - - enum { - SET_PIXEL_FORMAT = 0, - FIX_COLOUR_MAP_ENTRIES = 1, - SET_ENCODINGS = 2, - FRAME_BUFFER_UPDATE_REQ = 3, - KEY_EVENT = 4, - POINTER_EVENT = 5, - CLIENT_CUT_TEXT = 6, - }; - - struct ClientMessage : public Message { - ClientMessage() - : Message(&messageData, sizeof(messageData)) { - } - const ClientMessages& messages() const { - return *static_cast(payload()); - } - const int type() const { - return messages().type; - } - status_t resize(size_t size) { - return Message::resize(size); - } - - ClientMessages messageData; - }; - - - class ServerThread : public Thread - { - friend class RFBServer; - public: - ServerThread(const sp& receiver); - virtual ~ServerThread(); - void wake(); - void exitAndWait(); - private: - virtual bool threadLoop(); - virtual status_t readyToRun(); - virtual void onFirstRef(); - wp mReceiver; - bool (RFBServer::*mAction)(); - Barrier mUpdateBarrier; - }; - - class EventInjector { - public: - enum { UP=0, DOWN=1 }; - EventInjector(); - ~EventInjector(); - void injectKey(uint16_t code, uint16_t value); - private: - struct input_event { - struct timeval time; - uint16_t type; - uint16_t code; - uint32_t value; - }; - int mFD; - }; - - void handshake(uint8_t major, uint8_t minor, uint32_t auth); - void waitForClientMessage(ClientMessage& msg); - void handleClientMessage(const ClientMessage& msg); - void handleSetPixelFormat(const SetPixelFormat& msg); - void handleSetEncodings(const SetEncodings& msg); - void handleFrameBufferUpdateReq(const FrameBufferUpdateRequest& msg); - void handleKeyEvent(const KeyEvent& msg); - void sendFrameBufferUpdates(); - - bool validatePixelFormat(const PixelFormat& pf); - bool alive() const; - bool write(const Message& msg); - bool read(Message& msg); - - bool write(const void* buffer, int size); - bool read(void* buffer, int size); - - virtual bool threadLoop(); - virtual status_t readyToRun(); - virtual void onFirstRef(); - - sp mRobinThread; - - int mFD; - int mStatus; - iovec* mIoVec; - - EventInjector mEventInjector; - - Mutex mRegionLock; - // This is the region requested by the client since the last - // time we updated it - Region mClientRegionRequest; - // This is the region of the screen that needs to be sent to the - // client since the last time we updated it. - // Typically this is the dirty region, but not necessarily, for - // instance if the client asked for a non incremental update. - Region mDirtyRegion; - - GGLSurface mFrameBuffer; - GGLSurface mFrontBuffer; -}; - -}; // namespace android - -#endif // ANDROID_RFB_SERVER_H diff --git a/libs/surfaceflinger/SurfaceFlinger.cpp b/libs/surfaceflinger/SurfaceFlinger.cpp index 554e8e79b4aeb1f0f77f1bd22f61b9da1216bd21..242d0268822f4f9d0401b18a1462aaa303ba4608 100644 --- a/libs/surfaceflinger/SurfaceFlinger.cpp +++ b/libs/surfaceflinger/SurfaceFlinger.cpp @@ -53,20 +53,15 @@ #include "LayerBuffer.h" #include "LayerDim.h" #include "LayerBitmap.h" -#include "LayerScreenshot.h" +#include "LayerOrientationAnim.h" +#include "OrientationAnimation.h" #include "SurfaceFlinger.h" -#include "RFBServer.h" #include "VRamHeap.h" #include "DisplayHardware/DisplayHardware.h" #include "GPUHardware/GPUHardware.h" -// the VNC server even on local ports presents a significant -// thread as it can allow an application to control and "see" other -// applications, de-facto bypassing security permissions. -#define ENABLE_VNC_SERVER 0 - #define DISPLAY_COUNT 1 namespace android { @@ -185,6 +180,7 @@ SurfaceFlinger::SurfaceFlinger() mDeferReleaseConsole(false), mFreezeDisplay(false), mFreezeCount(0), + mFreezeDisplayTime(0), mDebugRegion(0), mDebugCpu(0), mDebugFps(0), @@ -225,6 +221,7 @@ void SurfaceFlinger::init() SurfaceFlinger::~SurfaceFlinger() { glDeleteTextures(1, &mWormholeTexName); + delete mOrientationAnimation; } copybit_device_t* SurfaceFlinger::getBlitEngine() const @@ -448,6 +445,8 @@ status_t SurfaceFlinger::readyToRun() * We're now ready to accept clients... */ + mOrientationAnimation = new OrientationAnimation(this); + // start CPU gauge display if (mDebugCpu) mCpuGauge = new CPUGauge(this, ms2ns(500)); @@ -456,9 +455,6 @@ status_t SurfaceFlinger::readyToRun() if (mDebugNoBootAnimation == false) mBootAnimation = new BootAnimation(this); - if (ENABLE_VNC_SERVER) - mRFBServer = new RFBServer(w, h, f); - return NO_ERROR; } @@ -472,17 +468,25 @@ void SurfaceFlinger::waitForEvent() { // wait for something to do if (UNLIKELY(isFrozen())) { - // wait 2 seconds - int err = mSyncObject.wait(ms2ns(3000)); + // wait 5 seconds + const nsecs_t freezeDisplayTimeout = ms2ns(5000); + const nsecs_t now = systemTime(); + if (mFreezeDisplayTime == 0) { + mFreezeDisplayTime = now; + } + nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime); + int err = (waitTime > 0) ? mSyncObject.wait(waitTime) : TIMED_OUT; if (err != NO_ERROR) { if (isFrozen()) { // we timed out and are still frozen LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d", mFreezeDisplay, mFreezeCount); mFreezeCount = 0; + mFreezeDisplay = false; } } } else { + mFreezeDisplayTime = 0; mSyncObject.wait(); } } @@ -556,11 +560,8 @@ bool SurfaceFlinger::threadLoop() void SurfaceFlinger::postFramebuffer() { - if (UNLIKELY(isFrozen())) { - // we are not allowed to draw, but pause a bit to make sure - // apps don't end up using the whole CPU, if they depend on - // surfaceflinger for synchronization. - usleep(8333); // 8.3ms ~ 120fps + const bool skip = mOrientationAnimation->run(); + if (UNLIKELY(skip)) { return; } @@ -571,18 +572,6 @@ void SurfaceFlinger::postFramebuffer() debugShowFPS(); } - if (UNLIKELY(ENABLE_VNC_SERVER && - mRFBServer!=0 && mRFBServer->isConnected())) { - if (!mSecureFrameBuffer) { - GGLSurface fb; - // backbufer, is going to become the front buffer really soon - hw.getDisplaySurface(&fb); - if (LIKELY(fb.data != 0)) { - mRFBServer->frameBufferUpdated(fb, mInvalidRegion); - } - } - } - hw.flip(mInvalidRegion); mInvalidRegion.clear(); @@ -685,18 +674,13 @@ void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) mVisibleRegionsDirty = true; mDirtyRegion.set(hw.bounds()); + + mOrientationAnimation->onOrientationChanged(); } if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) { // freezing or unfreezing the display -> trigger animation if needed mFreezeDisplay = mCurrentState.freezeDisplay; - const nsecs_t now = systemTime(); - if (mFreezeDisplay) { - mFreezeDisplayTime = now; - } else { - //LOGD("Screen was frozen for %llu us", - // ns2us(now-mFreezeDisplayTime)); - } } // some layers might have been removed, so @@ -875,19 +859,9 @@ void SurfaceFlinger::handleRepaint() uint32_t flags = hw.getFlags(); if (flags & DisplayHardware::BUFFER_PRESERVED) { - if (flags & DisplayHardware::COPY_BACK_EXTENSION) { - // yay. nothing to do here. - } else { - if (flags & DisplayHardware::UPDATE_ON_DEMAND) { - // we need to fully redraw the part that will be updated - mDirtyRegion.set(mInvalidRegion.bounds()); - } else { - // TODO: we only need te redraw the part that had been drawn - // the round before and is not drawn now - } - } + // here we assume DisplayHardware::flip()'s implementation + // performs the copy-back optimization. } else { - // COPY_BACK_EXTENSION makes no sense here if (flags & DisplayHardware::UPDATE_ON_DEMAND) { // we need to fully redraw the part that will be updated mDirtyRegion.set(mInvalidRegion.bounds()); @@ -1077,6 +1051,29 @@ void SurfaceFlinger::debugShowFPS() const // XXX: mFPS has the value we want } +status_t SurfaceFlinger::addLayer(LayerBase* layer) +{ + Mutex::Autolock _l(mStateLock); + addLayer_l(layer); + setTransactionFlags(eTransactionNeeded|eTraversalNeeded); + return NO_ERROR; +} + +status_t SurfaceFlinger::removeLayer(LayerBase* layer) +{ + Mutex::Autolock _l(mStateLock); + removeLayer_l(layer); + setTransactionFlags(eTransactionNeeded); + return NO_ERROR; +} + +status_t SurfaceFlinger::invalidateLayerVisibility(LayerBase* layer) +{ + layer->forceVisibilityTransaction(); + setTransactionFlags(eTraversalNeeded); + return NO_ERROR; +} + status_t SurfaceFlinger::addLayer_l(LayerBase* layer) { ssize_t i = mCurrentState.layersSortedByZ.add( @@ -1555,55 +1552,17 @@ status_t SurfaceFlinger::onTransact( status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { - if (code == 1012) { - // take screen-shot of the front buffer - if (UNLIKELY(checkCallingPermission( - String16("android.permission.READ_FRAME_BUFFER")) == false)) - { // not allowed - LOGE("Permission Denial: " - "can't take screenshots from pid=%d, uid=%d\n", - IPCThreadState::self()->getCallingPid(), - IPCThreadState::self()->getCallingUid()); - return PERMISSION_DENIED; - } - - if (UNLIKELY(mSecureFrameBuffer)) { - LOGE("A secure window is on screen: " - "can't take screenshots from pid=%d, uid=%d\n", - IPCThreadState::self()->getCallingPid(), - IPCThreadState::self()->getCallingUid()); - return PERMISSION_DENIED; - } - - LOGI("Taking a screenshot..."); - - LayerScreenshot* l = new LayerScreenshot(this, 0); - - Mutex::Autolock _l(mStateLock); - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - l->initStates(hw.getWidth(), hw.getHeight(), 0); - l->setLayer(INT_MAX); - - addLayer_l(l); - setTransactionFlags(eTransactionNeeded|eTraversalNeeded); - - l->takeScreenshot(mStateLock, reply); - - removeLayer_l(l); - setTransactionFlags(eTransactionNeeded); - return NO_ERROR; - } else { - // HARDWARE_TEST stuff... - if (UNLIKELY(checkCallingPermission( - String16("android.permission.HARDWARE_TEST")) == false)) - { // not allowed - LOGE("Permission Denial: pid=%d, uid=%d\n", - IPCThreadState::self()->getCallingPid(), - IPCThreadState::self()->getCallingUid()); - return PERMISSION_DENIED; - } - int n; - switch (code) { + // HARDWARE_TEST stuff... + if (UNLIKELY(checkCallingPermission( + String16("android.permission.HARDWARE_TEST")) == false)) + { // not allowed + LOGE("Permission Denial: pid=%d, uid=%d\n", + IPCThreadState::self()->getCallingPid(), + IPCThreadState::self()->getCallingUid()); + return PERMISSION_DENIED; + } + int n; + switch (code) { case 1000: // SHOW_CPU n = data.readInt32(); mDebugCpu = n ? 1 : 0; @@ -1636,8 +1595,8 @@ status_t SurfaceFlinger::onTransact( const DisplayHardware& hw(graphicPlane(0).displayHardware()); mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe signalEvent(); - } - return NO_ERROR; + } + return NO_ERROR; case 1005: // ask GPU revoke mGPU->friendlyRevoke(); return NO_ERROR; @@ -1653,13 +1612,12 @@ status_t SurfaceFlinger::onTransact( reply->writeInt32(mDebugRegion); reply->writeInt32(mDebugBackground); return NO_ERROR; - case 1013: { // screenshot + case 1013: { Mutex::Autolock _l(mStateLock); const DisplayHardware& hw(graphicPlane(0).displayHardware()); reply->writeInt32(hw.getPageFlipCount()); } return NO_ERROR; - } } } return err; @@ -1813,10 +1771,33 @@ void GraphicPlane::setTransform(const Transform& tr) { mGlobalTransform = mOrientationTransform * mTransform; } -status_t GraphicPlane::setOrientation(int orientation) -{ +status_t GraphicPlane::orientationToTransfrom( + int orientation, int w, int h, Transform* tr) +{ float a, b, c, d, x, y; + switch (orientation) { + case ISurfaceComposer::eOrientationDefault: + a=1; b=0; c=0; d=1; x=0; y=0; + break; + case ISurfaceComposer::eOrientation90: + a=0; b=-1; c=1; d=0; x=w; y=0; + break; + case ISurfaceComposer::eOrientation180: + a=-1; b=0; c=0; d=-1; x=w; y=h; + break; + case ISurfaceComposer::eOrientation270: + a=0; b=1; c=-1; d=0; x=0; y=h; + break; + default: + return BAD_VALUE; + } + tr->set(a, b, c, d); + tr->set(x, y); + return NO_ERROR; +} +status_t GraphicPlane::setOrientation(int orientation) +{ const DisplayHardware& hw(displayHardware()); const float w = hw.getWidth(); const float h = hw.getHeight(); @@ -1830,30 +1811,21 @@ status_t GraphicPlane::setOrientation(int orientation) // If the rotation can be handled in hardware, this is where // the magic should happen. - - switch (orientation) { - case ISurfaceComposer::eOrientation90: - a=0; b=-1; c=1; d=0; x=w; y=0; - break; - case ISurfaceComposer::eOrientation180: - a=-1; b=0; c=0; d=-1; x=w; y=h; - break; - case ISurfaceComposer::eOrientation270: - a=0; b=1; c=-1; d=0; x=0; y=h; - break; - case 42: { + if (UNLIKELY(orientation == 42)) { + float a, b, c, d, x, y; const float r = (3.14159265f / 180.0f) * 42.0f; const float si = sinf(r); const float co = cosf(r); a=co; b=-si; c=si; d=co; x = si*(h*0.5f) + (1-co)*(w*0.5f); y =-si*(w*0.5f) + (1-co)*(h*0.5f); - } break; - default: - return BAD_VALUE; + mOrientationTransform.set(a, b, c, d); + mOrientationTransform.set(x, y); + } else { + GraphicPlane::orientationToTransfrom(orientation, w, h, + &mOrientationTransform); } - mOrientationTransform.set(a, b, c, d); - mOrientationTransform.set(x, y); + mGlobalTransform = mOrientationTransform * mTransform; return NO_ERROR; } diff --git a/libs/surfaceflinger/SurfaceFlinger.h b/libs/surfaceflinger/SurfaceFlinger.h index a242f1aa01862198409585156b4bb223fdf1067b..f7d77640ae3c1ddab044234803449202c2a3287d 100644 --- a/libs/surfaceflinger/SurfaceFlinger.h +++ b/libs/surfaceflinger/SurfaceFlinger.h @@ -35,11 +35,11 @@ #include #include +#include "Barrier.h" +#include "BootAnimation.h" +#include "CPUGauge.h" #include "Layer.h" #include "Tokenizer.h" -#include "CPUGauge.h" -#include "BootAnimation.h" -#include "Barrier.h" struct copybit_device_t; struct overlay_device_t; @@ -48,16 +48,17 @@ namespace android { // --------------------------------------------------------------------------- -class BClient; class Client; +class BClient; class DisplayHardware; +class FreezeLock; class GPUHardwareInterface; class IGPUCallback; class Layer; class LayerBuffer; -class RFBServer; +class LayerOrientationAnim; +class OrientationAnimation; class SurfaceHeapManager; -class FreezeLock; typedef int32_t ClientID; @@ -110,6 +111,8 @@ private: class GraphicPlane { public: + static status_t orientationToTransfrom(int orientation, int w, int h, + Transform* tr); GraphicPlane(); ~GraphicPlane(); @@ -181,7 +184,12 @@ public: copybit_device_t* getBlitEngine() const; overlay_control_device_t* getOverlayEngine() const; + + status_t removeLayer(LayerBase* layer); + status_t addLayer(LayerBase* layer); + status_t invalidateLayerVisibility(LayerBase* layer); + private: friend class BClient; friend class LayerBase; @@ -337,7 +345,6 @@ private: sp mGPU; GLuint mWormholeTexName; sp mBootAnimation; - sp mRFBServer; nsecs_t mBootTime; // Can only accessed from the main thread, these members @@ -352,6 +359,8 @@ private: bool mFreezeDisplay; int32_t mFreezeCount; nsecs_t mFreezeDisplayTime; + friend class OrientationAnimation; + OrientationAnimation* mOrientationAnimation; // access protected by mDebugLock mutable Mutex mDebugLock; diff --git a/libs/surfaceflinger/VRamHeap.cpp b/libs/surfaceflinger/VRamHeap.cpp index 77bc5766be0a342b5ffb8202a860878b7ce48e53..0ccd71f0b8446c7407c6c58c28317fbebd448346 100644 --- a/libs/surfaceflinger/VRamHeap.cpp +++ b/libs/surfaceflinger/VRamHeap.cpp @@ -35,8 +35,6 @@ #include #include -#include - #include "GPUHardware/GPUHardware.h" #include "SurfaceFlinger.h" #include "VRamHeap.h" diff --git a/libs/ui/Camera.cpp b/libs/ui/Camera.cpp index 50c60084adf7f595fbc5bcc348297e6c4d0f65a4..b3cbda14fb06fa11043f39b90f6c8d24df3cebb6 100644 --- a/libs/ui/Camera.cpp +++ b/libs/ui/Camera.cpp @@ -84,8 +84,10 @@ void Camera::init() mRawCallbackCookie = 0; mJpegCallback = 0; mJpegCallbackCookie = 0; - mFrameCallback = 0; - mFrameCallbackCookie = 0; + mPreviewCallback = 0; + mPreviewCallbackCookie = 0; + mRecordingCallback = 0; + mRecordingCallbackCookie = 0; mErrorCallback = 0; mErrorCallbackCookie = 0; mAutoFocusCallback = 0; @@ -108,6 +110,8 @@ sp Camera::connect() if (c->mCamera != 0) { c->mCamera->asBinder()->linkToDeath(c); c->mStatus = NO_ERROR; + } else { + c.clear(); } return c; } @@ -184,6 +188,15 @@ status_t Camera::startPreview() return c->startPreview(); } +// start recording mode, must call setPreviewDisplay first +status_t Camera::startRecording() +{ + LOGV("startRecording"); + sp c = mCamera; + if (c == 0) return NO_INIT; + return c->startRecording(); +} + // stop preview mode void Camera::stopPreview() { @@ -193,6 +206,24 @@ void Camera::stopPreview() c->stopPreview(); } +// stop recording mode +void Camera::stopRecording() +{ + LOGV("stopRecording"); + sp c = mCamera; + if (c == 0) return; + c->stopRecording(); +} + +// release a recording frame +void Camera::releaseRecordingFrame(const sp& mem) +{ + LOGV("releaseRecordingFrame"); + sp c = mCamera; + if (c == 0) return; + c->releaseRecordingFrame(mem); +} + // get preview state bool Camera::previewEnabled() { @@ -202,6 +233,15 @@ bool Camera::previewEnabled() return c->previewEnabled(); } +// get recording state +bool Camera::recordingEnabled() +{ + LOGV("recordingEnabled"); + sp c = mCamera; + if (c == 0) return false; + return c->recordingEnabled(); +} + status_t Camera::autoFocus() { LOGV("autoFocus"); @@ -266,14 +306,21 @@ void Camera::setJpegCallback(frame_callback cb, void *cookie) mJpegCallbackCookie = cookie; } -void Camera::setFrameCallback(frame_callback cb, void *cookie, int frame_callback_flag) +void Camera::setPreviewCallback(frame_callback cb, void *cookie, int flag) { - LOGV("setFrameCallback"); - mFrameCallback = cb; - mFrameCallbackCookie = cookie; + LOGV("setPreviewCallback"); + mPreviewCallback = cb; + mPreviewCallbackCookie = cookie; sp c = mCamera; if (c == 0) return; - mCamera->setFrameCallbackFlag(frame_callback_flag); + mCamera->setPreviewCallbackFlag(flag); +} + +void Camera::setRecordingCallback(frame_callback cb, void *cookie) +{ + LOGV("setRecordingCallback"); + mRecordingCallback = cb; + mRecordingCallbackCookie = cookie; } void Camera::setErrorCallback(error_callback cb, void *cookie) @@ -316,12 +363,21 @@ void Camera::jpegCallback(const sp& picture) } } -// callback from camera service when video frame is ready -void Camera::frameCallback(const sp& frame) +// callback from camera service when preview frame is ready +void Camera::previewCallback(const sp& frame) { LOGV("frameCallback"); - if (mFrameCallback) { - mFrameCallback(frame, mFrameCallbackCookie); + if (mPreviewCallback) { + mPreviewCallback(frame, mPreviewCallbackCookie); + } +} + +// callback from camera service when a recording frame is ready +void Camera::recordingCallback(const sp& frame) +{ + LOGV("recordingCallback"); + if (mRecordingCallback) { + mRecordingCallback(frame, mRecordingCallbackCookie); } } diff --git a/libs/ui/CameraParameters.cpp b/libs/ui/CameraParameters.cpp index 7ca77bbc536b0724b03565ac54afde824d487f5d..6c258366fdd4273914efd9b788eecbe44cd1d667 100644 --- a/libs/ui/CameraParameters.cpp +++ b/libs/ui/CameraParameters.cpp @@ -24,6 +24,9 @@ namespace android { +static const char* portrait = "portrait"; +static const char* landscape = "landscape"; + CameraParameters::CameraParameters() : mMap() { @@ -182,6 +185,23 @@ void CameraParameters::setPreviewFormat(const char *format) set("preview-format", format); } +int CameraParameters::getOrientation() const +{ + const char* orientation = get("orientation"); + if (orientation && !strcmp(orientation, portrait)) + return CAMERA_ORIENTATION_PORTRAIT; + return CAMERA_ORIENTATION_LANDSCAPE; +} + +void CameraParameters::setOrientation(int orientation) +{ + if (orientation == CAMERA_ORIENTATION_PORTRAIT) { + set("preview-format", portrait); + } else { + set("preview-format", landscape); + } +} + const char *CameraParameters::getPreviewFormat() const { return get("preview-format"); diff --git a/libs/ui/EGLDisplaySurface.cpp b/libs/ui/EGLDisplaySurface.cpp index 44258a8d2c72e17a3cf8b619e6cb57c35b11a71d..d06c98b9bb4db53c8419f040c55ec136a477414e 100644 --- a/libs/ui/EGLDisplaySurface.cpp +++ b/libs/ui/EGLDisplaySurface.cpp @@ -42,7 +42,7 @@ #include #endif -#include +#include #include @@ -71,8 +71,6 @@ EGLDisplaySurface::EGLDisplaySurface() egl_native_window_t::incRef = &EGLDisplaySurface::hook_incRef; egl_native_window_t::decRef = &EGLDisplaySurface::hook_decRef; egl_native_window_t::swapBuffers = &EGLDisplaySurface::hook_swapBuffers; - egl_native_window_t::setSwapRectangle = &EGLDisplaySurface::hook_setSwapRectangle; - egl_native_window_t::nextBuffer = &EGLDisplaySurface::hook_nextBuffer; egl_native_window_t::connect = 0; egl_native_window_t::disconnect = 0; @@ -136,15 +134,6 @@ uint32_t EGLDisplaySurface::hook_swapBuffers(NativeWindowType window) { EGLDisplaySurface* that = static_cast(window); return that->swapBuffers(); } -uint32_t EGLDisplaySurface::hook_nextBuffer(NativeWindowType window) { - EGLDisplaySurface* that = static_cast(window); - return that->nextBuffer(); -} -void EGLDisplaySurface::hook_setSwapRectangle(NativeWindowType window, - int l, int t, int w, int h) { - EGLDisplaySurface* that = static_cast(window); - that->setSwapRectangle(l, t, w, h); -} void EGLDisplaySurface::setSwapRectangle(int l, int t, int w, int h) { @@ -249,15 +238,6 @@ int32_t EGLDisplaySurface::getPageFlipCount() const return mPageFlipCount; } -uint32_t EGLDisplaySurface::nextBuffer() -{ - // update the address of the buffer to draw to next - const GGLSurface& buffer = mFb[mIndex]; - egl_native_window_t::offset = - intptr_t(buffer.data) - egl_native_window_t::base; - return 0; -} - void EGLDisplaySurface::copyFrontToBack(const Region& copyback) { #if HAVE_ANDROID_OS @@ -318,6 +298,59 @@ void EGLDisplaySurface::copyFrontToBack(const Region& copyback) } } +void EGLDisplaySurface::copyFrontToImage(const copybit_image_t& dst) +{ +#if HAVE_ANDROID_OS + if (mBlitEngine) { + copybit_image_t src = { + w: egl_native_window_t::stride, + h: egl_native_window_t::height, + format: egl_native_window_t::format, + offset: mFb[mIndex].data - mFb[0].data, + base: (void*)egl_native_window_t::base, + fd: egl_native_window_t::fd + }; + region_iterator it(Region(Rect( + egl_native_window_t::width, egl_native_window_t::height))); + mBlitEngine->blit(mBlitEngine, &dst, &src, &it); + } else +#endif + { + uint8_t* const screen_src = mFb[ mIndex].data; + const size_t bpp = bytesPerPixel(egl_native_window_t::format); + const size_t bpr = egl_native_window_t::stride * bpp; + memcpy((char*)dst.base + dst.offset, screen_src, + bpr*egl_native_window_t::height); + } +} + +void EGLDisplaySurface::copyBackToImage(const copybit_image_t& dst) +{ +#if HAVE_ANDROID_OS + if (mBlitEngine) { + copybit_image_t src = { + w: egl_native_window_t::stride, + h: egl_native_window_t::height, + format: egl_native_window_t::format, + offset: mFb[1-mIndex].data - mFb[0].data, + base: (void*)egl_native_window_t::base, + fd: egl_native_window_t::fd + }; + region_iterator it(Region(Rect( + egl_native_window_t::width, egl_native_window_t::height))); + mBlitEngine->blit(mBlitEngine, &dst, &src, &it); + } else +#endif + { + uint8_t* const screen_src = mFb[1-mIndex].data; + const size_t bpp = bytesPerPixel(egl_native_window_t::format); + const size_t bpr = egl_native_window_t::stride * bpp; + memcpy((char*)dst.base + dst.offset, screen_src, + bpr*egl_native_window_t::height); + } +} + + status_t EGLDisplaySurface::mapFrameBuffer() { char const * const device_template[] = { diff --git a/libs/ui/EGLNativeWindowSurface.cpp b/libs/ui/EGLNativeWindowSurface.cpp index d55fb7090ff618521e0e2a84096cc8eb49b10160..f1071cf9097b41e5d076e644da2d4e04c42e6888 100644 --- a/libs/ui/EGLNativeWindowSurface.cpp +++ b/libs/ui/EGLNativeWindowSurface.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include @@ -48,8 +48,6 @@ EGLNativeWindowSurface::EGLNativeWindowSurface(const sp& surface) egl_native_window_t::incRef = &EGLNativeWindowSurface::hook_incRef; egl_native_window_t::decRef = &EGLNativeWindowSurface::hook_decRef; egl_native_window_t::swapBuffers = &EGLNativeWindowSurface::hook_swapBuffers; - egl_native_window_t::nextBuffer = &EGLNativeWindowSurface::hook_nextBuffer; - egl_native_window_t::setSwapRectangle = &EGLNativeWindowSurface::hook_setSwapRectangle; egl_native_window_t::connect = &EGLNativeWindowSurface::hook_connect; egl_native_window_t::disconnect = &EGLNativeWindowSurface::hook_disconnect; @@ -98,18 +96,6 @@ uint32_t EGLNativeWindowSurface::hook_swapBuffers(NativeWindowType window) return that->swapBuffers(); } -uint32_t EGLNativeWindowSurface::hook_nextBuffer(NativeWindowType window) -{ - EGLNativeWindowSurface* that = static_cast(window); - return that->nextBuffer(); -} - -void EGLNativeWindowSurface::hook_setSwapRectangle(NativeWindowType window, int l, int t, int w, int h) -{ - EGLNativeWindowSurface* that = static_cast(window); - that->setSwapRectangle(l, t, w, h); -} - void EGLNativeWindowSurface::setSwapRectangle(int l, int t, int w, int h) { mSurface->setSwapRectangle(Rect(l, t, l+w, t+h)); @@ -138,17 +124,6 @@ uint32_t EGLNativeWindowSurface::swapBuffers() return 0; } -uint32_t EGLNativeWindowSurface::nextBuffer() -{ - const sp& surface(mSurface); - Surface::SurfaceInfo info; - surface->nextBuffer(&info); - // update the address of the buffer to draw to next - egl_native_window_t::base = intptr_t(info.base); - egl_native_window_t::offset = intptr_t(info.bits) - intptr_t(info.base); - return 0; -} - void EGLNativeWindowSurface::connect() { if (!mConnected) { diff --git a/libs/ui/EventHub.cpp b/libs/ui/EventHub.cpp index 700aa3a8ad75568d8c298b59b199279f409e43c8..3b29b094db66f4512e47f9e1fe2bff6b93e04ca5 100644 --- a/libs/ui/EventHub.cpp +++ b/libs/ui/EventHub.cpp @@ -71,10 +71,11 @@ static inline int max(int v1, int v2) EventHub::device_t::device_t(int32_t _id, const char* _path) : id(_id), path(_path), classes(0) - , layoutMap(new KeyLayoutMap()), next(NULL) { + , keyBitmask(NULL), layoutMap(new KeyLayoutMap()), next(NULL) { } EventHub::device_t::~device_t() { + delete [] keyBitmask; delete layoutMap; } @@ -403,6 +404,36 @@ bool EventHub::openPlatformInput(void) return true; } +/* + * Inspect the known devices to determine whether physical keys exist for the given + * framework-domain key codes. + */ +bool EventHub::hasKeys(size_t numCodes, int32_t* keyCodes, uint8_t* outFlags) { + for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) { + outFlags[codeIndex] = 0; + + // check each available hardware device for support for this keycode + Vector scanCodes; + for (int n = 0; (n < mFDCount) && (outFlags[codeIndex] == 0); n++) { + if (mDevices[n]) { + status_t err = mDevices[n]->layoutMap->findScancodes(keyCodes[codeIndex], &scanCodes); + if (!err) { + // check the possible scan codes identified by the layout map against the + // map of codes actually emitted by the driver + for (size_t sc = 0; sc < scanCodes.size(); sc++) { + if (test_bit(scanCodes[sc], mDevices[n]->keyBitmask)) { + outFlags[codeIndex] = 1; + break; + } + } + } + } + } + } + + return true; +} + // ---------------------------------------------------------------------------- int EventHub::open_device(const char *deviceName) @@ -527,6 +558,16 @@ int EventHub::open_device(const char *deviceName) break; } } + if ((device->classes & CLASS_KEYBOARD) != 0) { + device->keyBitmask = new uint8_t[(KEY_MAX+1)/8]; + if (device->keyBitmask != NULL) { + memcpy(device->keyBitmask, key_bitmask, sizeof(key_bitmask)); + } else { + delete device; + LOGE("out of memory allocating key bitmask"); + return -1; + } + } } if (test_bit(BTN_MOUSE, key_bitmask)) { uint8_t rel_bitmask[(REL_MAX+1)/8]; diff --git a/libs/ui/ICamera.cpp b/libs/ui/ICamera.cpp index 7b0922ec72754ecf66e94e3b7e2fc2fdfa7b71a3..ab0fef1489d64a4fa63ec2aa249183ee53044871 100644 --- a/libs/ui/ICamera.cpp +++ b/libs/ui/ICamera.cpp @@ -28,7 +28,7 @@ namespace android { enum { DISCONNECT = IBinder::FIRST_CALL_TRANSACTION, SET_PREVIEW_DISPLAY, - SET_FRAME_CALLBACK_FLAG, + SET_PREVIEW_CALLBACK_FLAG, START_PREVIEW, STOP_PREVIEW, AUTO_FOCUS, @@ -38,7 +38,11 @@ enum { CONNECT, LOCK, UNLOCK, - PREVIEW_ENABLED + PREVIEW_ENABLED, + START_RECORDING, + STOP_RECORDING, + RECORDING_ENABLED, + RELEASE_RECORDING_FRAME, }; class BpCamera: public BpInterface @@ -69,15 +73,15 @@ public: return reply.readInt32(); } - // set the frame callback flag to affect how the received frames from - // preview are handled. - void setFrameCallbackFlag(int frame_callback_flag) + // set the preview callback flag to affect how the received frames from + // preview are handled. See Camera.h for details. + void setPreviewCallbackFlag(int flag) { - LOGV("setFrameCallbackFlag(%d)", frame_callback_flag); + LOGV("setPreviewCallbackFlag(%d)", flag); Parcel data, reply; data.writeInterfaceToken(ICamera::getInterfaceDescriptor()); - data.writeInt32(frame_callback_flag); - remote()->transact(SET_FRAME_CALLBACK_FLAG, data, &reply); + data.writeInt32(flag); + remote()->transact(SET_PREVIEW_CALLBACK_FLAG, data, &reply); } // start preview mode, must call setPreviewDisplay first @@ -90,6 +94,16 @@ public: return reply.readInt32(); } + // start recording mode, must call setPreviewDisplay first + status_t startRecording() + { + LOGV("startRecording"); + Parcel data, reply; + data.writeInterfaceToken(ICamera::getInterfaceDescriptor()); + remote()->transact(START_RECORDING, data, &reply); + return reply.readInt32(); + } + // stop preview mode void stopPreview() { @@ -99,6 +113,24 @@ public: remote()->transact(STOP_PREVIEW, data, &reply); } + // stop recording mode + void stopRecording() + { + LOGV("stopRecording"); + Parcel data, reply; + data.writeInterfaceToken(ICamera::getInterfaceDescriptor()); + remote()->transact(STOP_RECORDING, data, &reply); + } + + void releaseRecordingFrame(const sp& mem) + { + LOGV("releaseRecordingFrame"); + Parcel data, reply; + data.writeInterfaceToken(ICamera::getInterfaceDescriptor()); + data.writeStrongBinder(mem->asBinder()); + remote()->transact(RELEASE_RECORDING_FRAME, data, &reply); + } + // check preview state bool previewEnabled() { @@ -109,6 +141,16 @@ public: return reply.readInt32(); } + // check recording state + bool recordingEnabled() + { + LOGV("recordingEnabled"); + Parcel data, reply; + data.writeInterfaceToken(ICamera::getInterfaceDescriptor()); + remote()->transact(RECORDING_ENABLED, data, &reply); + return reply.readInt32(); + } + // auto focus status_t autoFocus() { @@ -202,11 +244,11 @@ status_t BnCamera::onTransact( reply->writeInt32(setPreviewDisplay(surface)); return NO_ERROR; } break; - case SET_FRAME_CALLBACK_FLAG: { - LOGV("SET_FRAME_CALLBACK_TYPE"); + case SET_PREVIEW_CALLBACK_FLAG: { + LOGV("SET_PREVIEW_CALLBACK_TYPE"); CHECK_INTERFACE(ICamera, data, reply); - int frame_callback_flag = data.readInt32(); - setFrameCallbackFlag(frame_callback_flag); + int callback_flag = data.readInt32(); + setPreviewCallbackFlag(callback_flag); return NO_ERROR; } break; case START_PREVIEW: { @@ -215,18 +257,43 @@ status_t BnCamera::onTransact( reply->writeInt32(startPreview()); return NO_ERROR; } break; + case START_RECORDING: { + LOGV("START_RECORDING"); + CHECK_INTERFACE(ICamera, data, reply); + reply->writeInt32(startRecording()); + return NO_ERROR; + } break; case STOP_PREVIEW: { LOGV("STOP_PREVIEW"); CHECK_INTERFACE(ICamera, data, reply); stopPreview(); return NO_ERROR; } break; + case STOP_RECORDING: { + LOGV("STOP_RECORDING"); + CHECK_INTERFACE(ICamera, data, reply); + stopRecording(); + return NO_ERROR; + } break; + case RELEASE_RECORDING_FRAME: { + LOGV("RELEASE_RECORDING_FRAME"); + CHECK_INTERFACE(ICamera, data, reply); + sp mem = interface_cast(data.readStrongBinder()); + releaseRecordingFrame(mem); + return NO_ERROR; + } break; case PREVIEW_ENABLED: { LOGV("PREVIEW_ENABLED"); CHECK_INTERFACE(ICamera, data, reply); reply->writeInt32(previewEnabled()); return NO_ERROR; } break; + case RECORDING_ENABLED: { + LOGV("RECORDING_ENABLED"); + CHECK_INTERFACE(ICamera, data, reply); + reply->writeInt32(recordingEnabled()); + return NO_ERROR; + } break; case AUTO_FOCUS: { LOGV("AUTO_FOCUS"); CHECK_INTERFACE(ICamera, data, reply); diff --git a/libs/ui/ICameraClient.cpp b/libs/ui/ICameraClient.cpp index c5d6d52f4df9a79dd25048467b64e7829340f48d..4bec9d2ae6c3c84f713e10fef05d6dbe9ab36bb6 100644 --- a/libs/ui/ICameraClient.cpp +++ b/libs/ui/ICameraClient.cpp @@ -28,9 +28,10 @@ enum { SHUTTER_CALLBACK = IBinder::FIRST_CALL_TRANSACTION, RAW_CALLBACK, JPEG_CALLBACK, - FRAME_CALLBACK, + PREVIEW_CALLBACK, ERROR_CALLBACK, - AUTOFOCUS_CALLBACK + AUTOFOCUS_CALLBACK, + RECORDING_CALLBACK, }; class BpCameraClient: public BpInterface @@ -70,14 +71,24 @@ public: remote()->transact(JPEG_CALLBACK, data, &reply, IBinder::FLAG_ONEWAY); } - // callback from camera service to app with video frame data - void frameCallback(const sp& frame) + // callback from camera service to app with preview frame data + void previewCallback(const sp& frame) { - LOGV("frameCallback"); + LOGV("previewCallback"); Parcel data, reply; data.writeInterfaceToken(ICameraClient::getInterfaceDescriptor()); data.writeStrongBinder(frame->asBinder()); - remote()->transact(FRAME_CALLBACK, data, &reply, IBinder::FLAG_ONEWAY); + remote()->transact(PREVIEW_CALLBACK, data, &reply, IBinder::FLAG_ONEWAY); + } + + // callback from camera service to app with recording frame data + void recordingCallback(const sp& frame) + { + LOGV("recordingCallback"); + Parcel data, reply; + data.writeInterfaceToken(ICameraClient::getInterfaceDescriptor()); + data.writeStrongBinder(frame->asBinder()); + remote()->transact(RECORDING_CALLBACK, data, &reply, IBinder::FLAG_ONEWAY); } // callback from camera service to app to report error @@ -135,11 +146,18 @@ status_t BnCameraClient::onTransact( jpegCallback(picture); return NO_ERROR; } break; - case FRAME_CALLBACK: { - LOGV("FRAME_CALLBACK"); + case PREVIEW_CALLBACK: { + LOGV("PREVIEW_CALLBACK"); + CHECK_INTERFACE(ICameraClient, data, reply); + sp frame = interface_cast(data.readStrongBinder()); + previewCallback(frame); + return NO_ERROR; + } break; + case RECORDING_CALLBACK: { + LOGV("RECORDING_CALLBACK"); CHECK_INTERFACE(ICameraClient, data, reply); sp frame = interface_cast(data.readStrongBinder()); - frameCallback(frame); + recordingCallback(frame); return NO_ERROR; } break; case ERROR_CALLBACK: { diff --git a/libs/ui/ISurface.cpp b/libs/ui/ISurface.cpp index 6f3cd4776b92f36861f559b3a02ad664fc508046..d5e9f812a40b195e6b1d8601ed14ecea1e98a9df 100644 --- a/libs/ui/ISurface.cpp +++ b/libs/ui/ISurface.cpp @@ -27,12 +27,33 @@ namespace android { -enum { - REGISTER_BUFFERS = IBinder::FIRST_CALL_TRANSACTION, - UNREGISTER_BUFFERS, - POST_BUFFER, // one-way transaction - CREATE_OVERLAY, -}; +ISurface::BufferHeap::BufferHeap() + : w(0), h(0), hor_stride(0), ver_stride(0), format(0), + transform(0), flags(0) +{ +} + +ISurface::BufferHeap::BufferHeap(uint32_t w, uint32_t h, + int32_t hor_stride, int32_t ver_stride, + PixelFormat format, const sp& heap) + : w(w), h(h), hor_stride(hor_stride), ver_stride(ver_stride), + format(format), transform(0), flags(0), heap(heap) +{ +} + +ISurface::BufferHeap::BufferHeap(uint32_t w, uint32_t h, + int32_t hor_stride, int32_t ver_stride, + PixelFormat format, uint32_t transform, uint32_t flags, + const sp& heap) + : w(w), h(h), hor_stride(hor_stride), ver_stride(ver_stride), + format(format), transform(transform), flags(flags), heap(heap) +{ +} + + +ISurface::BufferHeap::~BufferHeap() +{ +} class BpSurface : public BpInterface { @@ -42,17 +63,18 @@ public: { } - virtual status_t registerBuffers(int w, int h, int hstride, int vstride, - PixelFormat format, const sp& heap) + virtual status_t registerBuffers(const BufferHeap& buffers) { Parcel data, reply; data.writeInterfaceToken(ISurface::getInterfaceDescriptor()); - data.writeInt32(w); - data.writeInt32(h); - data.writeInt32(hstride); - data.writeInt32(vstride); - data.writeInt32(format); - data.writeStrongBinder(heap->asBinder()); + data.writeInt32(buffers.w); + data.writeInt32(buffers.h); + data.writeInt32(buffers.hor_stride); + data.writeInt32(buffers.ver_stride); + data.writeInt32(buffers.format); + data.writeInt32(buffers.transform); + data.writeInt32(buffers.flags); + data.writeStrongBinder(buffers.heap->asBinder()); remote()->transact(REGISTER_BUFFERS, data, &reply); status_t result = reply.readInt32(); return result; @@ -102,13 +124,16 @@ status_t BnSurface::onTransact( switch(code) { case REGISTER_BUFFERS: { CHECK_INTERFACE(ISurface, data, reply); - int w = data.readInt32(); - int h = data.readInt32(); - int hs= data.readInt32(); - int vs= data.readInt32(); - PixelFormat f = data.readInt32(); - sp heap(interface_cast(data.readStrongBinder())); - status_t err = registerBuffers(w,h,hs,vs,f,heap); + BufferHeap buffer; + buffer.w = data.readInt32(); + buffer.h = data.readInt32(); + buffer.hor_stride = data.readInt32(); + buffer.ver_stride= data.readInt32(); + buffer.format = data.readInt32(); + buffer.transform = data.readInt32(); + buffer.flags = data.readInt32(); + buffer.heap = interface_cast(data.readStrongBinder()); + status_t err = registerBuffers(buffer); reply->writeInt32(err); return NO_ERROR; } break; diff --git a/libs/ui/PixelFormat.cpp b/libs/ui/PixelFormat.cpp index 605c8aef931f9139985fab47f81af66197e14f1e..b65ed9736ba945bdba5198eee2502722bde3cde5 100644 --- a/libs/ui/PixelFormat.cpp +++ b/libs/ui/PixelFormat.cpp @@ -19,6 +19,18 @@ namespace android { +size_t PixelFormatInfo::getScanlineSize(unsigned int width) const +{ + size_t size; + if ((components >= 6) && (components <= 8)) { + // YCbCr formats are differents. + size = (width * bitsPerPixel)>>3; + } else { + size = width * bytesPerPixel; + } + return size; +} + ssize_t bytesPerPixel(PixelFormat format) { PixelFormatInfo info; @@ -47,7 +59,25 @@ status_t getPixelFormatInfo(PixelFormat format, PixelFormatInfo* info) if (!valid) { return BAD_INDEX; } - + + #define COMPONENT(name) \ + case GGL_##name: info->components = PixelFormatInfo::name; break; + + switch (i->components) { + COMPONENT(ALPHA) + COMPONENT(RGB) + COMPONENT(RGBA) + COMPONENT(LUMINANCE) + COMPONENT(LUMINANCE_ALPHA) + COMPONENT(Y_CB_CR_SP) + COMPONENT(Y_CB_CR_P) + COMPONENT(Y_CB_CR_I) + default: + return BAD_INDEX; + } + + #undef COMPONENT + info->format = format; info->bytesPerPixel = i->size; info->bitsPerPixel = i->bitsPerPixel; @@ -59,6 +89,7 @@ status_t getPixelFormatInfo(PixelFormat format, PixelFormatInfo* info) info->l_green = i->gl; info->h_blue = i->bh; info->l_blue = i->bl; + return NO_ERROR; } diff --git a/libs/utils/CallStack.cpp b/libs/utils/CallStack.cpp index 26fb22abc01dc2843eb942466c8533a246806ca5..2fdaa71186b3869a6c71f7ae216ca68a51091873 100644 --- a/libs/utils/CallStack.cpp +++ b/libs/utils/CallStack.cpp @@ -120,13 +120,18 @@ class MapInfo { char name[]; }; - const char *map_to_name(uint64_t pc, const char* def) { + const char *map_to_name(uint64_t pc, const char* def, uint64_t* start) { mapinfo* mi = getMapInfoList(); while(mi) { - if ((pc >= mi->start) && (pc < mi->end)) + if ((pc >= mi->start) && (pc < mi->end)) { + if (start) + *start = mi->start; return mi->name; + } mi = mi->next; } + if (start) + *start = 0; return def; } @@ -183,8 +188,15 @@ public: } } - static const char *mapAddressToName(const void* pc, const char* def) { - return sMapInfo.map_to_name((uint64_t)pc, def); + static const char *mapAddressToName(const void* pc, const char* def, + void const** start) + { + uint64_t s; + char const* name = sMapInfo.map_to_name(uint64_t(uintptr_t(pc)), def, &s); + if (start) { + *start = (void*)s; + } + return name; } }; @@ -297,8 +309,9 @@ String8 CallStack::toStringSingleLevel(const char* prefix, int32_t level) const res.append(name); res.append(tmp2); } else { - name = MapInfo::mapAddressToName(ip, ""); - snprintf(tmp, 256, "pc %p %s", ip, name); + void const* start = 0; + name = MapInfo::mapAddressToName(ip, "", &start); + snprintf(tmp, 256, "pc %08lx %s", uintptr_t(ip)-uintptr_t(start), name); res.append(tmp); } res.append("\n"); diff --git a/libs/utils/Parcel.cpp b/libs/utils/Parcel.cpp index 2962b25aeae247f15714121c6581a7fe9fbc905e..4225e67283fac8096329ad04f35d5a8b9ae58f31 100644 --- a/libs/utils/Parcel.cpp +++ b/libs/utils/Parcel.cpp @@ -658,15 +658,20 @@ status_t Parcel::writeNativeHandle(const native_handle& handle) status_t err; err = writeInt32(handle.numFds); if (err != NO_ERROR) return err; - + err = writeInt32(handle.numInts); if (err != NO_ERROR) return err; - + for (int i=0 ; err==NO_ERROR && iconfig); - + if (outSpecFlags != NULL) { if (typeClass->typeSpecFlags != NULL) { *outSpecFlags |= dtohl(typeClass->typeSpecFlags[e]); @@ -1834,6 +1836,9 @@ ssize_t ResTable::getResource(uint32_t resID, Res_value* outValue, bool mayBeBag outValue->res0 = bestValue->res0; outValue->dataType = bestValue->dataType; outValue->data = dtohl(bestValue->data); + if (outConfig != NULL) { + *outConfig = bestItem; + } TABLE_NOISY(size_t len; printf("Found value: pkg=%d, type=%d, str=%s, int=%d\n", bestPackage->header->index, @@ -3147,13 +3152,13 @@ bool ResTable::stringToValue(Res_value* outValue, String16* outString, const char16_t* pos = s; while (pos < end && !failed) { const char16_t* start = pos; - end++; + pos++; while (pos < end && *pos != '|') { pos++; } - //printf("Looking for: %s\n", String8(start, pos-start).string()); + //printf("Looking for: %s\n", String8(start, pos-start).string()); const bag_entry* bagi = bag; - ssize_t i; + ssize_t i; for (i=0; imap.name.ident)) { //printf("Trying attr #%08x\n", bagi->map.name.ident); @@ -3181,7 +3186,7 @@ bool ResTable::stringToValue(Res_value* outValue, String16* outString, } unlockBag(bag); if (!failed) { - //printf("Final flag value: 0x%lx\n", outValue->data); + //printf("Final flag value: 0x%lx\n", outValue->data); return true; } } @@ -3189,7 +3194,7 @@ bool ResTable::stringToValue(Res_value* outValue, String16* outString, if (fromAccessor) { if (accessor->getAttributeFlags(attrID, s, len, outValue)) { - //printf("Final flag value: 0x%lx\n", outValue->data); + //printf("Final flag value: 0x%lx\n", outValue->data); return true; } } @@ -3484,7 +3489,7 @@ ssize_t ResTable::getEntry( ResTable_config thisConfig; thisConfig.copyFromDtoH(thisType->config); - + TABLE_GETENTRY(LOGI("Match entry 0x%x in type 0x%x (sz 0x%x): imsi:%d/%d=%d/%d lang:%c%c=%c%c cnt:%c%c=%c%c " "orien:%d=%d touch:%d=%d density:%d=%d key:%d=%d inp:%d=%d nav:%d=%d w:%d=%d h:%d=%d\n", entryIndex, typeIndex+1, dtohl(thisType->config.size), diff --git a/libs/utils/String16.cpp b/libs/utils/String16.cpp index 1f81cadb7a4cbd1709c4753af046c81d88672394..aef67f22af95118fccc42e0a3a7c39b834d4dc09 100644 --- a/libs/utils/String16.cpp +++ b/libs/utils/String16.cpp @@ -244,7 +244,6 @@ void terminate_string16() // --------------------------------------------------------------------------- -// Note: not dealing with generating surrogate pairs. static char16_t* allocFromUTF8(const char* in, size_t len) { if (len == 0) return getEmptyString(); @@ -255,7 +254,10 @@ static char16_t* allocFromUTF8(const char* in, size_t len) while (p < end) { chars++; - p += utf8_char_len(*p); + int utf8len = utf8_char_len(*p); + uint32_t codepoint = utf8_to_utf32((const uint8_t*)p, utf8len); + if (codepoint > 0xFFFF) chars++; // this will be a surrogate pair in utf16 + p += utf8len; } SharedBuffer* buf = SharedBuffer::alloc((chars+1)*sizeof(char16_t)); @@ -265,7 +267,19 @@ static char16_t* allocFromUTF8(const char* in, size_t len) char16_t* d = str; while (p < end) { size_t len = utf8_char_len(*p); - *d++ = (char16_t)utf8_to_utf32((const uint8_t*)p, len); + uint32_t codepoint = utf8_to_utf32((const uint8_t*)p, len); + + // Convert the UTF32 codepoint to one or more UTF16 codepoints + if (codepoint <= 0xFFFF) { + // Single UTF16 character + *d++ = (char16_t) codepoint; + } else { + // Multiple UTF16 characters with surrogates + codepoint = codepoint - 0x10000; + *d++ = (char16_t) ((codepoint >> 10) + 0xD800); + *d++ = (char16_t) ((codepoint & 0x3FF) + 0xDC00); + } + p += len; } *d = 0; @@ -388,7 +402,7 @@ status_t String16::setTo(const char16_t* other, size_t len) ->editResize((len+1)*sizeof(char16_t)); if (buf) { char16_t* str = (char16_t*)buf->data(); - memcpy(str, other, len*sizeof(char16_t)); + memmove(str, other, len*sizeof(char16_t)); str[len] = 0; mString = str; return NO_ERROR; diff --git a/libs/utils/String8.cpp b/libs/utils/String8.cpp index ab843f6e798b82ebdc769d6b27f633f752a021d3..c50d343a731b4498797569aacb1d298743340f58 100644 --- a/libs/utils/String8.cpp +++ b/libs/utils/String8.cpp @@ -317,8 +317,10 @@ status_t String8::real_append(const char* other, size_t otherLen) ->editResize(myLen+otherLen+1); if (buf) { char* str = (char*)buf->data(); - memcpy(str+myLen, other, otherLen+1); mString = str; + str += myLen; + memcpy(str, other, otherLen); + str[otherLen] = '\0'; return NO_ERROR; } return NO_MEMORY; diff --git a/libs/utils/Threads.cpp b/libs/utils/Threads.cpp index 74271ba3b41bcf7356a45c713c34b11c3a3afc10..9287c0bbab3cd079e6f3a28dd7f34980a86eaa88 100644 --- a/libs/utils/Threads.cpp +++ b/libs/utils/Threads.cpp @@ -14,6 +14,7 @@ * limitations under the License. */ +// #define LOG_NDEBUG 0 #define LOG_TAG "libutils.threads" #include @@ -838,146 +839,6 @@ void Condition::broadcast() #error "condition variables not supported on this platform" #endif - -/* - * =========================================================================== - * ReadWriteLock class - * =========================================================================== - */ - -#if 0 -#pragma mark - -#pragma mark ReadWriteLock -#endif - -/* - * Add a reader. Readers are nice. They share. - */ -void ReadWriteLock::lockForRead() -{ - mLock.lock(); - while (mNumWriters > 0) { - LOG(LOG_DEBUG, "thread", "+++ lockForRead: waiting\n"); - mReadWaiter.wait(mLock); - } - assert(mNumWriters == 0); - mNumReaders++; -#if defined(PRINT_RENDER_TIMES) - if (mNumReaders == 1) - mDebugTimer.start(); -#endif - mLock.unlock(); -} - -/* - * Try to add a reader. If it doesn't work right away, return "false". - */ -bool ReadWriteLock::tryLockForRead() -{ - mLock.lock(); - if (mNumWriters > 0) { - mLock.unlock(); - return false; - } - assert(mNumWriters == 0); - mNumReaders++; -#if defined(PRINT_RENDER_TIMES) - if (mNumReaders == 1) - mDebugTimer.start(); -#endif - mLock.unlock(); - return true; -} - -/* - * Remove a reader. - */ -void ReadWriteLock::unlockForRead() -{ - mLock.lock(); - if (mNumReaders == 0) { - LOG(LOG_WARN, "thread", - "WARNING: unlockForRead requested, but not locked\n"); - return; - } - assert(mNumReaders > 0); - assert(mNumWriters == 0); - mNumReaders--; - if (mNumReaders == 0) { // last reader? -#if defined(PRINT_RENDER_TIMES) - mDebugTimer.stop(); - printf(" rdlk held %.3f msec\n", - (double) mDebugTimer.durationUsecs() / 1000.0); -#endif - //printf("+++ signaling writers (if any)\n"); - mWriteWaiter.signal(); // wake one writer (if any) - } - mLock.unlock(); -} - -/* - * Add a writer. This requires exclusive access to the object. - */ -void ReadWriteLock::lockForWrite() -{ - mLock.lock(); - while (mNumReaders > 0 || mNumWriters > 0) { - LOG(LOG_DEBUG, "thread", "+++ lockForWrite: waiting\n"); - mWriteWaiter.wait(mLock); - } - assert(mNumReaders == 0); - assert(mNumWriters == 0); - mNumWriters++; -#if defined(PRINT_RENDER_TIMES) - mDebugTimer.start(); -#endif - mLock.unlock(); -} - -/* - * Try to add a writer. If it doesn't work right away, return "false". - */ -bool ReadWriteLock::tryLockForWrite() -{ - mLock.lock(); - if (mNumReaders > 0 || mNumWriters > 0) { - mLock.unlock(); - return false; - } - assert(mNumReaders == 0); - assert(mNumWriters == 0); - mNumWriters++; -#if defined(PRINT_RENDER_TIMES) - mDebugTimer.start(); -#endif - mLock.unlock(); - return true; -} - -/* - * Remove a writer. - */ -void ReadWriteLock::unlockForWrite() -{ - mLock.lock(); - if (mNumWriters == 0) { - LOG(LOG_WARN, "thread", - "WARNING: unlockForWrite requested, but not locked\n"); - return; - } - assert(mNumWriters == 1); - mNumWriters--; -#if defined(PRINT_RENDER_TIMES) - mDebugTimer.stop(); - //printf(" wrlk held %.3f msec\n", - // (double) mDebugTimer.durationUsecs() / 1000.0); -#endif - // mWriteWaiter.signal(); // should other writers get first dibs? - //printf("+++ signaling readers (if any)\n"); - mReadWaiter.broadcast(); // wake all readers (if any) - mLock.unlock(); -} - // ---------------------------------------------------------------------------- #if 0 @@ -1025,6 +886,8 @@ status_t Thread::run(const char* name, int32_t priority, size_t stack) // hold a strong reference on ourself mHoldSelf = this; + mRunning = true; + bool res; if (mCanCallJava) { res = createThreadEtc(_threadLoop, @@ -1038,14 +901,16 @@ status_t Thread::run(const char* name, int32_t priority, size_t stack) mStatus = UNKNOWN_ERROR; // something happened! mRunning = false; mThread = thread_id_t(-1); + mHoldSelf.clear(); // "this" may have gone away after this. + + return UNKNOWN_ERROR; } - if (mStatus < 0) { - // something happened, don't leak - mHoldSelf.clear(); - } - - return mStatus; + // Do not refer to mStatus here: The thread is already running (may, in fact + // already have exited with a valid mStatus result). The NO_ERROR indication + // here merely indicates successfully starting the thread and does not + // imply successful termination/execution. + return NO_ERROR; } int Thread::_threadLoop(void* user) @@ -1055,20 +920,32 @@ int Thread::_threadLoop(void* user) wp weak(strong); self->mHoldSelf.clear(); - // we're about to run... - self->mStatus = self->readyToRun(); - if (self->mStatus!=NO_ERROR || self->mExitPending) { - // pretend the thread never started... - self->mExitPending = false; - self->mRunning = false; - return 0; - } - - // thread is running now - self->mRunning = true; + bool first = true; do { - bool result = self->threadLoop(); + bool result; + if (first) { + first = false; + self->mStatus = self->readyToRun(); + result = (self->mStatus == NO_ERROR); + + if (result && !self->mExitPending) { + // Binder threads (and maybe others) rely on threadLoop + // running at least once after a successful ::readyToRun() + // (unless, of course, the thread has already been asked to exit + // at that point). + // This is because threads are essentially used like this: + // (new ThreadSubclass())->run(); + // The caller therefore does not retain a strong reference to + // the thread and the thread would simply disappear after the + // successful ::readyToRun() call instead of entering the + // threadLoop at least once. + result = self->threadLoop(); + } + } else { + result = self->threadLoop(); + } + if (result == false || self->mExitPending) { self->mExitPending = true; self->mLock.lock(); @@ -1095,24 +972,23 @@ void Thread::requestExit() status_t Thread::requestExitAndWait() { - if (mStatus == OK) { - - if (mThread == getThreadId()) { - LOGW( - "Thread (this=%p): don't call waitForExit() from this " - "Thread object's thread. It's a guaranteed deadlock!", - this); - return WOULD_BLOCK; - } - - requestExit(); + if (mThread == getThreadId()) { + LOGW( + "Thread (this=%p): don't call waitForExit() from this " + "Thread object's thread. It's a guaranteed deadlock!", + this); - Mutex::Autolock _l(mLock); - while (mRunning == true) { - mThreadExitedCondition.wait(mLock); - } - mExitPending = false; + return WOULD_BLOCK; } + + requestExit(); + + Mutex::Autolock _l(mLock); + while (mRunning == true) { + mThreadExitedCondition.wait(mLock); + } + mExitPending = false; + return mStatus; } diff --git a/location/data/Android.mk b/location/data/Android.mk index befd79299a47284cd5fcb70daec7a2069c027bba..794e6c7bf0d8d187ef9f7416b1d898c7524212ae 100644 --- a/location/data/Android.mk +++ b/location/data/Android.mk @@ -13,7 +13,7 @@ include $(CLEAR_VARS) LOCAL_MODULE := nmea -LOCAL_MODULE_TAGS := development +LOCAL_MODULE_TAGS := tests LOCAL_MODULE_CLASS := ETC LOCAL_MODULE_PATH := $(local_target_dir)/gps @@ -27,7 +27,7 @@ include $(CLEAR_VARS) LOCAL_MODULE := location -LOCAL_MODULE_TAGS := development +LOCAL_MODULE_TAGS := tests LOCAL_MODULE_CLASS := ETC LOCAL_MODULE_PATH := $(local_target_dir)/gps @@ -41,7 +41,7 @@ include $(CLEAR_VARS) LOCAL_MODULE := properties -LOCAL_MODULE_TAGS := development +LOCAL_MODULE_TAGS := tests LOCAL_MODULE_CLASS := ETC LOCAL_MODULE_PATH := $(local_target_dir)/gps diff --git a/location/java/android/location/Location.java b/location/java/android/location/Location.java index d381f6eedd8000fdc744c8b33c8945cda3a4eae8..aacf8572fcadefee516489790c248627bc4794c3 100644 --- a/location/java/android/location/Location.java +++ b/location/java/android/location/Location.java @@ -19,6 +19,7 @@ package android.location; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; +import android.util.Printer; import java.text.DecimalFormat; import java.util.StringTokenizer; @@ -81,6 +82,16 @@ public class Location implements Parcelable { // Scratchpad private float[] mResults = new float[2]; + public void dump(Printer pw, String prefix) { + pw.println(prefix + "mProvider=" + mProvider + " mTime=" + mTime); + pw.println(prefix + "mLatitude=" + mLatitude + " mLongitude=" + mLongitude); + pw.println(prefix + "mHasAltitude=" + mHasAltitude + " mAltitude=" + mAltitude); + pw.println(prefix + "mHasSpeed=" + mHasSpeed + " mSpeed=" + mSpeed); + pw.println(prefix + "mHasBearing=" + mHasBearing + " mBearing=" + mBearing); + pw.println(prefix + "mHasAccuracy=" + mHasAccuracy + " mAccuracy=" + mAccuracy); + pw.println(prefix + "mExtras=" + mExtras); + } + /** * Constructs a new Location. By default, time, latitude, * longitude, and numSatellites are 0; hasAltitude, hasSpeed, and diff --git a/location/java/com/android/internal/location/CellState.java b/location/java/com/android/internal/location/CellState.java index 8f6ca1f498a5c067f70a3c74dd6a08f2bd1a07a7..eb6535e8c4288d86f860d8db18b46af6cf65a991 100644 --- a/location/java/com/android/internal/location/CellState.java +++ b/location/java/com/android/internal/location/CellState.java @@ -168,15 +168,8 @@ public class CellState { } } - public void updateRadioType(TelephonyManager telephonyManager) { - // Get radio type - int radioType = telephonyManager.getNetworkType(); - if (radioType == TelephonyManager.NETWORK_TYPE_GPRS || - radioType == TelephonyManager.NETWORK_TYPE_EDGE) { - mRadioType = RADIO_TYPE_GPRS; - } else if (radioType == TelephonyManager.NETWORK_TYPE_UMTS) { - mRadioType = RADIO_TYPE_WCDMA; - } + public void updateRadioType(int radioType) { + mRadioType = radioType; if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.d(TAG, "updateRadioType(): " + mLac +"," + mCid + "," + mMnc +"," + mMcc + "," + diff --git a/location/java/com/android/internal/location/GpsLocationProvider.java b/location/java/com/android/internal/location/GpsLocationProvider.java index c6f13c943127a8e5b425861cd22099e12d491182..6672e299fe797b837065f84a7849ebaf08319391 100644 --- a/location/java/com/android/internal/location/GpsLocationProvider.java +++ b/location/java/com/android/internal/location/GpsLocationProvider.java @@ -164,16 +164,15 @@ public class GpsLocationProvider extends LocationProviderImpl { // current setting - 5 minutes private static final long RETRY_INTERVAL = 5*60*1000; - private LocationCollector mCollector; + private ILocationCollector mCollector; public static boolean isSupported() { return native_is_supported(); } - public GpsLocationProvider(Context context, LocationCollector collector) { + public GpsLocationProvider(Context context) { super(LocationManager.GPS_PROVIDER); mContext = context; - mCollector = collector; mProperties = new Properties(); try { @@ -183,10 +182,14 @@ public class GpsLocationProvider extends LocationProviderImpl { stream.close(); mNtpServer = mProperties.getProperty("NTP_SERVER", null); } catch (IOException e) { - Log.e(TAG, "Could not open GPS configuration file " + PROPERTIES_FILE, e); + Log.w(TAG, "Could not open GPS configuration file " + PROPERTIES_FILE); } } + public void setLocationCollector(ILocationCollector collector) { + mCollector = collector; + } + /** * Returns true if the provider requires access to a * data network (e.g., the Internet), false otherwise. @@ -623,7 +626,8 @@ public class GpsLocationProvider extends LocationProviderImpl { } // Send to collector - if ((flags & LOCATION_HAS_LAT_LONG) == LOCATION_HAS_LAT_LONG) { + if ((flags & LOCATION_HAS_LAT_LONG) == LOCATION_HAS_LAT_LONG + && mCollector != null) { mCollector.updateLocation(mLocation); } } @@ -644,7 +648,7 @@ public class GpsLocationProvider extends LocationProviderImpl { if (Config.LOGV) Log.v(TAG, "reportStatus status: " + status); boolean wasNavigating = mNavigating; - mNavigating = (status == GPS_STATUS_SESSION_BEGIN || status == GPS_STATUS_ENGINE_ON); + mNavigating = (status == GPS_STATUS_SESSION_BEGIN); if (wasNavigating != mNavigating) { synchronized(mListeners) { diff --git a/location/java/com/android/internal/location/ILocationCollector.java b/location/java/com/android/internal/location/ILocationCollector.java new file mode 100644 index 0000000000000000000000000000000000000000..8a7cdcce1ed39695028ebf06423547c21b3ce602 --- /dev/null +++ b/location/java/com/android/internal/location/ILocationCollector.java @@ -0,0 +1,73 @@ +/* + * 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. + */ + +package com.android.internal.location; + +import android.location.Location; +import android.net.wifi.ScanResult; + +import com.android.internal.location.CellState; + +import java.util.List; + +/** + * Listens for GPS and cell/wifi changes and anonymously uploads to server for + * improving quality of service of NetworkLocationProvider. This service is only enabled when + * the user has enabled the network location provider. + * + * {@hide} + */ +public interface ILocationCollector { + /** + * Updates GPS location if collection is enabled + * + * @param location location object + */ + abstract public void updateLocation(Location location); + + /** + * Updates wifi scan results if collection is enabled + * + * @param currentScanResults scan results + */ + abstract public void updateWifiScanResults(List currentScanResults); + + /** + * Updates the status of the network location provider. + * + * @param enabled true if user has enabled network location based on Google's database + * of wifi points and cell towers. + */ + abstract public void updateNetworkProviderStatus(boolean enabled); + + /** + * Updates cell tower state. This is usually always up to date so should be uploaded + * each time a new location is available. + * + * @param newState cell state + */ + abstract public void updateCellState(CellState newState); + + /** + * Updates the battery health. Battery level is healthy if there is greater than + * {@link #MIN_BATTERY_LEVEL} percentage left or if the device is plugged in + * + * @param scale maximum scale for battery + * @param level current level + * @param plugged true if device is plugged in + */ + abstract public void updateBatteryState(int scale, int level, boolean plugged); +} diff --git a/location/java/com/android/internal/location/INetworkLocationManager.java b/location/java/com/android/internal/location/INetworkLocationManager.java new file mode 100644 index 0000000000000000000000000000000000000000..d85ff0a5c79a92f7c14f18b1fb0469fc1396c02c --- /dev/null +++ b/location/java/com/android/internal/location/INetworkLocationManager.java @@ -0,0 +1,37 @@ + /* + * 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. + */ + +package com.android.internal.location; + +import android.content.Context; + +/** + * Used to register network location and collection services + * with the Location Manager Service. + * + * {@hide} + */ +public interface INetworkLocationManager { + + /* callback to allow installation to occur in Location Manager's thread */ + public interface InstallCallback { + void installNetworkLocationProvider(INetworkLocationManager manager); + } + + void setInstallCallback(InstallCallback callback); + void setNetworkLocationProvider(INetworkLocationProvider provider); + void setLocationCollector(ILocationCollector collector); +} \ No newline at end of file diff --git a/location/java/com/android/internal/location/INetworkLocationProvider.java b/location/java/com/android/internal/location/INetworkLocationProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..730cb480a4d6ca10650fcf43a014c377271103fc --- /dev/null +++ b/location/java/com/android/internal/location/INetworkLocationProvider.java @@ -0,0 +1,95 @@ +/* + * 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. + */ + +package com.android.internal.location; + +import android.location.Address; +import android.location.Location; +import android.net.wifi.ScanResult; + +import com.google.common.io.protocol.ProtoBuf; + +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Locale; + +/** + * Interface for network location provider + * + * {@hide} + */ +public interface INetworkLocationProvider { + + public interface Callback { + + /** + * Callback function to notify of a received network location + * + * @param location location object that is received. may be null if not a valid location + * @param successful true if network query was successful, even if no location was found + */ + void locationReceived(Location location, boolean successful); + } + + /** + * Updates the current cell lock status. + * + * @param acquired true if a cell lock has been acquired + */ + abstract public void updateCellLockStatus(boolean acquired); + + /** + * Notifies the provider if Wifi has been enabled or disabled + * by the user + * + * @param enabled true if wifi is enabled; false otherwise + */ + abstract public void updateWifiEnabledState(boolean enabled); + + /** + * Notifies the provider that there are scan results available. + * + * @param scanResults list of wifi scan results + */ + abstract public void updateWifiScanResults(List scanResults); + + /** + * Adds a list of application clients + * Only used by the NetworkLocationProvider + * + * @param applications list of package names + */ + abstract public void addListener(String[] applications); + + /** + * Removes a list of application clients + * Only used by the NetworkLocationProvider + * + * @param applications list of package names + */ + abstract public void removeListener(String[] applications); + + + abstract public String getFromLocation(double latitude, double longitude, int maxResults, + String language, String country, String variant, String appName, List
                addrs); + + abstract public String getFromLocationName(String locationName, + double lowerLeftLatitude, double lowerLeftLongitude, + double upperRightLatitude, double upperRightLongitude, int maxResults, + String language, String country, String variant, String appName, List
                addrs); + +} diff --git a/location/java/com/android/internal/location/LocationCache.java b/location/java/com/android/internal/location/LocationCache.java deleted file mode 100644 index 079c9c7e1306e316c53920137d1dc3ae032e60bb..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/LocationCache.java +++ /dev/null @@ -1,608 +0,0 @@ -// Copyright 2007 The Android Open Source Project - -package com.android.internal.location; - -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import android.location.Location; -import android.location.LocationManager; -import android.net.wifi.ScanResult; -import android.os.Bundle; -import android.util.Log; - -/** - * Data store to cache cell-id and wifi locations from the network - * - * {@hide} - */ -public class LocationCache { - private static final String TAG = "LocationCache"; - - // Version of cell cache - private static final int CACHE_DB_VERSION = 1; - - // Don't save cache more than once every minute - private static final long SAVE_FREQUENCY = 60 * 1000; - - // Location of the cache file; - private static final String mCellCacheFile = "cache.cell"; - private static final String mWifiCacheFile = "cache.wifi"; - - // Maximum time (in millis) that a record is valid for, before it needs - // to be refreshed from the server. - private static final long MAX_CELL_REFRESH_RECORD_AGE = 12 * 60 * 60 * 1000; // 12 hours - private static final long MAX_WIFI_REFRESH_RECORD_AGE = 48 * 60 * 60 * 1000; // 48 hours - - // Cache sizes - private static final int MAX_CELL_RECORDS = 50; - private static final int MAX_WIFI_RECORDS = 200; - - // Cache constants - private static final long CELL_SMOOTHING_WINDOW = 30 * 1000; // 30 seconds - private static final int WIFI_MIN_AP_REQUIRED = 2; - private static final int WIFI_MAX_MISS_ALLOWED = 5; - private static final int MAX_ACCURACY_ALLOWED = 5000; // 5km - - // Caches - private final Cache mCellCache; - private final Cache mWifiCache; - - // Currently calculated centroids - private final LocationCentroid mCellCentroid = new LocationCentroid(); - private final LocationCentroid mWifiCentroid = new LocationCentroid(); - - // Extra key and values - private final String EXTRA_KEY_LOCATION_TYPE = "networkLocationType"; - private final String EXTRA_VALUE_LOCATION_TYPE_CELL = "cell"; - private final String EXTRA_VALUE_LOCATION_TYPE_WIFI = "wifi"; - - public LocationCache() { - mCellCache = new Cache(LocationManager.SYSTEM_DIR, mCellCacheFile, - MAX_CELL_RECORDS, MAX_CELL_REFRESH_RECORD_AGE); - mWifiCache = new Cache(LocationManager.SYSTEM_DIR, mWifiCacheFile, - MAX_WIFI_RECORDS, MAX_WIFI_REFRESH_RECORD_AGE); - } - - /** - * Looks up network location on device cache - * - * @param cellState primary cell state - * @param cellHistory history of cell states - * @param scanResults wifi scan results - * @param result location object to fill if location is found - * @return true if cache was able to answer query (successfully or not), false if call to - * server is required - */ - public synchronized boolean lookup(CellState cellState, List cellHistory, - List scanResults, Location result) { - - if (Log.isLoggable(TAG, Log.VERBOSE)) { - Log.d(TAG, "including cell:" + (cellState != null) + - ", wifi:" + ((scanResults != null)? scanResults.size() : "null")); - } - - long now = System.currentTimeMillis(); - - mCellCentroid.reset(); - mWifiCentroid.reset(); - - if (cellState != null && cellState.isValid()) { - String primaryCellKey = getCellCacheKey(cellState.getMcc(), cellState.getMnc(), - cellState.getLac(), cellState.getCid()); - Record record = mCellCache.lookup(primaryCellKey); - - // Relax MCC/MNC condition - if (record == null) { - primaryCellKey = getCellCacheKey(-1, -1, cellState.getLac(), cellState.getCid()); - record = mCellCache.lookup(primaryCellKey); - } - - if (record == null) { - // Make a server request if primary cell doesn't exist in DB - return false; - } - - if (record.isValid()) { - mCellCentroid.addLocation(record.getLat(), record.getLng(), record.getAccuracy(), - record.getConfidence()); - } - } - - if (cellHistory != null) { - for (CellState historicalCell : cellHistory) { - // Cell location might need to be smoothed if you are on the border of two cells - if (now - historicalCell.getTime() < CELL_SMOOTHING_WINDOW) { - String historicalCellKey = getCellCacheKey(historicalCell.getMcc(), - historicalCell.getMnc(), historicalCell.getLac(), historicalCell.getCid()); - Record record = mCellCache.lookup(historicalCellKey); - - // Relax MCC/MNC condition - if (record == null) { - historicalCellKey = getCellCacheKey(-1, -1, historicalCell.getLac(), - historicalCell.getCid()); - record = mCellCache.lookup(historicalCellKey); - } - - if (record != null && record.isValid()) { - mCellCentroid.addLocation(record.getLat(), record.getLng(), - record.getAccuracy(), record.getConfidence()); - } - } - } - } - - if (scanResults != null) { - int miss = 0; - for (ScanResult scanResult : scanResults) { - String wifiKey = scanResult.BSSID; - Record record = mWifiCache.lookup(wifiKey); - if (record == null) { - miss++; - } else { - if (record.isValid()) { - mWifiCentroid.addLocation(record.getLat(), record.getLng(), - record.getAccuracy(), record.getConfidence()); - } - } - } - - if (mWifiCentroid.getNumber() >= WIFI_MIN_AP_REQUIRED) { - // Try to return best out of the available cell or wifi location - } else if (miss > Math.min(WIFI_MAX_MISS_ALLOWED, (scanResults.size()+1)/2)) { - // Make a server request - return false; - } else { - // Don't use wifi location, only consider using cell location - mWifiCache.save(); - mWifiCentroid.reset(); - } - } - - if (mCellCentroid.getNumber() > 0) { - mCellCache.save(); - } - if (mWifiCentroid.getNumber() > 0) { - mWifiCache.save(); - } - - int cellAccuracy = mCellCentroid.getAccuracy(); - int wifiAccuracy = mWifiCentroid.getAccuracy(); - - int cellConfidence = mCellCentroid.getConfidence(); - int wifiConfidence = mWifiCentroid.getConfidence(); - - if (Log.isLoggable(TAG, Log.VERBOSE)) { - Log.d(TAG, "cellAccuracy:" + cellAccuracy+ ", wifiAccuracy:" + wifiAccuracy); - } - - if ((mCellCentroid.getNumber() == 0 || cellAccuracy > MAX_ACCURACY_ALLOWED) && - (mWifiCentroid.getNumber() == 0 || wifiAccuracy > MAX_ACCURACY_ALLOWED)) { - // Return invalid location if neither location is valid - result.setAccuracy(-1); - - // don't make server request - return true; - } - - float[] distance = new float[1]; - Location.distanceBetween(mCellCentroid.getCentroidLat(), mCellCentroid.getCentroidLng(), - mWifiCentroid.getCentroidLat(), mWifiCentroid.getCentroidLng(), - distance); - - boolean consistent = distance[0] <= (cellAccuracy + wifiAccuracy); - - boolean useCell = true; - - if (consistent) { - // If consistent locations, use one with greater accuracy - useCell = (cellAccuracy <= wifiAccuracy); - } else { - // If inconsistent locations, use one with greater confidence - useCell = (cellConfidence >= wifiConfidence); - } - - if (useCell) { - // Use cell results - result.setAccuracy(cellAccuracy); - result.setLatitude(mCellCentroid.getCentroidLat()); - result.setLongitude(mCellCentroid.getCentroidLng()); - result.setTime(now); - - Bundle extras = result.getExtras() == null ? new Bundle() : result.getExtras(); - extras.putString(EXTRA_KEY_LOCATION_TYPE, EXTRA_VALUE_LOCATION_TYPE_CELL); - result.setExtras(extras); - - } else { - // Use wifi results - result.setAccuracy(wifiAccuracy); - result.setLatitude(mWifiCentroid.getCentroidLat()); - result.setLongitude(mWifiCentroid.getCentroidLng()); - result.setTime(now); - - Bundle extras = result.getExtras() == null ? new Bundle() : result.getExtras(); - extras.putString(EXTRA_KEY_LOCATION_TYPE, EXTRA_VALUE_LOCATION_TYPE_WIFI); - result.setExtras(extras); - - } - - // don't make a server request - return true; - } - - public synchronized void insert(int mcc, int mnc, int lac, int cid, double lat, double lng, - int accuracy, int confidence, long time) { - String key = getCellCacheKey(mcc, mnc, lac, cid); - if (accuracy <= 0) { - mCellCache.insert(key, new Record()); - } else { - mCellCache.insert(key, new Record(accuracy, confidence, lat, lng, time)); - } - } - - public synchronized void insert(String bssid, double lat, double lng, int accuracy, - int confidence, long time) { - if (accuracy <= 0) { - mWifiCache.insert(bssid, new Record()); - } else { - mWifiCache.insert(bssid, new Record(accuracy, confidence, lat, lng, time)); - } - } - - public synchronized void save() { - mCellCache.save(); - mWifiCache.save(); - } - - /** - * Cell or Wifi location record - */ - public static class Record { - - private final double lat; - private final double lng; - private final int accuracy; - private final int confidence; - - // Time (since the epoch) of original reading. - private final long originTime; - - public static Record read(DataInput dataInput) throws IOException { - final int accuracy = dataInput.readInt(); - final int confidence = dataInput.readInt(); - final double lat = dataInput.readDouble(); - final double lng = dataInput.readDouble(); - final long readingTime = dataInput.readLong(); - return new Record(accuracy, confidence, lat, lng, readingTime); - } - - /** - * Creates an "invalid" record indicating there was no location data - * available for the given data - */ - public Record() { - this(-1, 0, 0, 0, System.currentTimeMillis()); - } - - /** - * Creates a Record - * - * @param accuracy acuracy in meters. If < 0, then this is an invalid record. - * @param confidence confidence (0-100) - * @param lat latitude - * @param lng longitude - * @param time Time of the original location reading from the server - */ - public Record(int accuracy, int confidence, double lat, double lng, long time) { - this.accuracy = accuracy; - this.confidence = confidence; - this.originTime = time; - this.lat = lat; - this.lng = lng; - } - - public double getLat() { - return lat; - } - - public double getLng() { - return lng; - } - - public int getAccuracy() { - return accuracy; - } - - public int getConfidence() { - return confidence; - } - - public boolean isValid() { - return accuracy > 0; - } - - public long getTime() { - return originTime; - } - - public void write(DataOutput dataOut) throws IOException { - dataOut.writeInt(accuracy); - dataOut.writeInt(confidence); - dataOut.writeDouble(lat); - dataOut.writeDouble(lng); - dataOut.writeLong(originTime); - } - - @Override - public String toString() { - return lat + "," + lng + "," + originTime +"," + accuracy + "," + confidence; - } - } - - public class Cache extends LinkedHashMap { - private final long mMaxAge; - private final int mCapacity; - private final String mDir; - private final String mFile; - private long mLastSaveTime = 0; - - public Cache(String dir, String file, int capacity, long maxAge) { - super(capacity + 1, 1.1f, true); - this.mCapacity = capacity; - this.mDir = dir; - this.mFile = file; - this.mMaxAge = maxAge; - load(); - } - - private LocationCache.Record lookup(String key) { - LocationCache.Record result = (LocationCache.Record) get(key); - - if (result == null) { - if (Log.isLoggable(TAG, Log.VERBOSE)) { - Log.d(TAG, "lookup: " + key + " failed"); - } - return null; - } - - // Cache entry needs refresh - if (result.getTime() + mMaxAge < System.currentTimeMillis()) { - if (Log.isLoggable(TAG, Log.VERBOSE)) { - Log.d(TAG, "lookup: " + key + " expired"); - } - return null; - } - - if (Log.isLoggable(TAG, Log.VERBOSE)) { - Log.d(TAG, "lookup: " + key + " " + result.toString()); - } - - return result; - } - - private void insert(String key, LocationCache.Record record) { - remove(key); - put(key, record); - - if (Log.isLoggable(TAG, Log.VERBOSE)) { - Log.d(TAG, "insert: " + key + " " + record.toString()); - } - } - - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - // Remove cache entries when it has more than capacity - return size() > mCapacity; - } - - private void load() { - FileInputStream istream; - try { - File f = new File(mDir, mFile); - istream = new FileInputStream(f); - } catch (FileNotFoundException e) { - // No existing DB - return new CellCache - return; - } - - DataInputStream dataInput = new DataInputStream(istream); - - try { - int version = dataInput.readUnsignedShort(); - if (version != CACHE_DB_VERSION) { - // Ignore records - invalid version ID. - dataInput.close(); - return; - } - int records = dataInput.readUnsignedShort(); - - for (int i = 0; i < records; i++) { - final String key = dataInput.readUTF(); - final LocationCache.Record record = LocationCache.Record.read(dataInput); - //Log.d(TAG, key + " " + record.toString()); - put(key, record); - } - - dataInput.close(); - } catch (IOException e) { - // Something's corrupted - return a new CellCache - } - } - - private void save() { - long now = System.currentTimeMillis(); - if (mLastSaveTime != 0 && (now - mLastSaveTime < SAVE_FREQUENCY)) { - // Don't save to file more often than SAVE_FREQUENCY - return; - } - - FileOutputStream ostream; - - File systemDir = new File(mDir); - if (!systemDir.exists()) { - if (!systemDir.mkdirs()) { - Log.e(TAG, "Cache.save(): couldn't create directory"); - return; - } - } - - try { - File f = new File(mDir, mFile); - ostream = new FileOutputStream(f); - } catch (FileNotFoundException e) { - Log.d(TAG, "Cache.save(): unable to create cache file", e); - return; - } - - DataOutputStream dataOut = new DataOutputStream(ostream); - try { - dataOut.writeShort(CACHE_DB_VERSION); - - dataOut.writeShort(size()); - - for (Iterator iter = entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - String key = (String) entry.getKey(); - LocationCache.Record record = (LocationCache.Record) entry.getValue(); - dataOut.writeUTF(key); - record.write(dataOut); - } - - dataOut.close(); - mLastSaveTime = now; - - } catch (IOException e) { - Log.e(TAG, "Cache.save(): unable to write cache", e); - // This should never happen - } - } - } - - public class LocationCentroid { - - double mLatSum = 0; - double mLngSum = 0; - int mNumber = 0; - int mConfidence = 0; - - double mCentroidLat = 0; - double mCentroidLng = 0; - - // Probably never have to calculate centroid for more than 10 locations - final static int MAX_SIZE = 10; - double[] mLats = new double[MAX_SIZE]; - double[] mLngs = new double[MAX_SIZE]; - int[] mRadii = new int[MAX_SIZE]; - - LocationCentroid() { - reset(); - } - - public void reset() { - mLatSum = 0; - mLngSum = 0; - mNumber = 0; - mConfidence = 0; - - mCentroidLat = 0; - mCentroidLng = 0; - - for (int i = 0; i < MAX_SIZE; i++) { - mLats[i] = 0; - mLngs[i] = 0; - mRadii[i] = 0; - } - } - - public void addLocation(double lat, double lng, int accuracy, int confidence) { - if (mNumber < MAX_SIZE && accuracy <= MAX_ACCURACY_ALLOWED) { - mLatSum += lat; - mLngSum += lng; - if (confidence > mConfidence) { - mConfidence = confidence; - } - - mLats[mNumber] = lat; - mLngs[mNumber] = lng; - mRadii[mNumber] = accuracy; - mNumber++; - } - } - - public int getNumber() { - return mNumber; - } - - public double getCentroidLat() { - if (mCentroidLat == 0 && mNumber != 0) { - mCentroidLat = mLatSum/mNumber; - } - return mCentroidLat; - } - - public double getCentroidLng() { - if (mCentroidLng == 0 && mNumber != 0) { - mCentroidLng = mLngSum/mNumber; - } - return mCentroidLng; - } - - public int getConfidence() { - return mConfidence; - } - - public int getAccuracy() { - if (mNumber == 0) { - return 0; - } - - if (mNumber == 1) { - return mRadii[0]; - } - - double cLat = getCentroidLat(); - double cLng = getCentroidLng(); - - int meanDistanceSum = 0; - int smallestCircle = MAX_ACCURACY_ALLOWED; - int smallestCircleDistance = MAX_ACCURACY_ALLOWED; - float[] distance = new float[1]; - boolean outlierExists = false; - - for (int i = 0; i < mNumber; i++) { - Location.distanceBetween(cLat, cLng, mLats[i], mLngs[i], distance); - meanDistanceSum += (int)distance[0]; - if (distance[0] > mRadii[i]) { - outlierExists = true; - } - if (mRadii[i] < smallestCircle) { - smallestCircle = mRadii[i]; - smallestCircleDistance = (int)distance[0]; - } - } - - if (outlierExists) { - return meanDistanceSum/mNumber; - } else { - return Math.max(smallestCircle, smallestCircleDistance); - } - } - - } - - private String getCellCacheKey(int mcc, int mnc, int lac, int cid) { - return mcc + ":" + mnc + ":" + lac + ":" + cid; - } - -} diff --git a/location/java/com/android/internal/location/LocationCollector.java b/location/java/com/android/internal/location/LocationCollector.java deleted file mode 100644 index 39f432f14b822f54967a41b211860baeba36e4d9..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/LocationCollector.java +++ /dev/null @@ -1,499 +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. - */ - -package com.android.internal.location; - -import com.android.internal.location.protocol.GDebugProfile; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import android.location.Location; -import android.net.wifi.ScanResult; -import android.os.SystemClock; -import android.os.SystemProperties; -import android.util.Log; - -/** - * Listens for GPS and cell/wifi changes and anonymously uploads to server for - * improving quality of service of NetworkLocationProvider. This service is only enabled when - * the user has enabled the network location provider. - * - * {@hide} - */ -public class LocationCollector { - - private static final String TAG = "LocationCollector"; - - // last location valid for 12 minutes - private static final long MIN_VALID_LOCATION_TIME = 12 * 60 * 1000L; - - // don't send wifi more than every 10 min - private static final long MIN_TIME_BETWEEN_WIFI_REPORTS = 10 * 60 * 1000L; - - // atleast 5 changed APs for wifi collection - private static final int MIN_CHANGED_WIFI_POINTS = 5; - - // don't collect if distance moved less than 200 meters - private static final int MIN_DISTANCE_BETWEEN_REPORTS = 200; - - // don't collect if battery level less than 20% - private static final double MIN_BATTERY_LEVEL = 0.2; - - // if battery level is greater than 90% and plugged in, collect more frequently - private static final double CHARGED_BATTERY_LEVEL = 0.9; - - // collect bursts every 15 minutes (running on battery) - private static final long BURST_REST_TIME_ON_BATTERY = 15 * 60 * 1000L; - - // collect bursts every 8 minutes (when plugged in) - private static final long BURST_REST_TIME_PLUGGED = 8 * 60 * 1000L; - - // collect burst samples every 12 seconds - private static final int BURST_MEASUREMENT_INTERVAL = 12 * 1000; - - // collect 11 burst samples before resting (11 samples every 12 seconds = 2 minute bursts) - private static final int BURST_NUM_SAMPLES = 11; - - // don't collect bursts if user in same loc for 2 bursts - private static final int MAX_BURSTS_FROM_SAME_LOCATION = 2; - - // don't send more than 2 bursts if user hasn't moved more than 25 meters - private static final int MIN_DISTANCE_BETWEEN_BURSTS = 25; - - // Cell State - private CellState mCellState = null; - private CellUploads mCellUploads = new CellUploads(); - - // GPS state - private Location mLastKnownLocation = null; - private Location mLastUploadedLocation = null; - private long mLastKnownLocationTime = 0; - private long mLastUploadedLocationTime = 0; - - // Burst state - private Location mLastBurstLocation = null; - private long mLastBurstEndTime = 0; - private long mCurrentBurstStartTime = 0; - private int mCurrentBurstNumSamples = 0; - private int mNumBurstsFromLastLocation = 0; - - // WiFi state - private List mWifiLastScanResults = null; - private List mWifiCurrentScanResults = null; - private long mLastWifiScanElapsedTime = 0; - private long mLastWifiScanRealTime = 0; - private boolean mWifiUploadedWithoutLocation = false; - - // Collection state - private boolean mNetworkProviderIsEnabled = true; - private boolean mBatteryLevelIsHealthy = true; - private boolean mBatteryChargedAndPlugged = false; - - // Location masf service - private LocationMasfClient mMasfClient; - - public LocationCollector(LocationMasfClient masfClient) { - mMasfClient = masfClient; - } - - /** - * Updates cell tower state. This is usually always up to date so should be uploaded - * each time a new location is available. - * - * @param newState cell state - */ - public synchronized void updateCellState(CellState newState) { - if (newState == null) { - throw new IllegalArgumentException("cell state is null"); - } - - if (!newState.isValid()) { - return; - } - - if (mCellState != null && mCellState.equals(newState)) { - return; - } - - mCellState = newState; - log("updateCellState(): Updated to " + mCellState.getCid() + "," + mCellState.getLac()); - - if (isCollectionEnabled()) { - addToQueue(GDebugProfile.TRIGGER_CELL_CHANGE); - } - } - - /** - * Updates GPS location if collection is enabled - * - * @param location location object - */ - public synchronized void updateLocation(Location location) { - - // Don't do anything if collection is disabled - if (!isCollectionEnabled()) { - return; - } - - long now = SystemClock.elapsedRealtime(); - - // Update last known location - if (mLastKnownLocation == null) { - mLastKnownLocation = new Location(location); - } else { - mLastKnownLocation.set(location); - } - mLastKnownLocationTime = now; - - // Burst rest time depends on battery state - long restTime = BURST_REST_TIME_ON_BATTERY; - if (mBatteryChargedAndPlugged) { - restTime = BURST_REST_TIME_PLUGGED; - } - - int trigger; - - // In burst mode if either first burst or enough time has passed since last burst - if (mLastBurstEndTime == 0 || (now - mLastBurstEndTime > restTime)) { - - // If location is too recent, then don't do anything! - if (now - mLastUploadedLocationTime < BURST_MEASUREMENT_INTERVAL) { - return; - } - - int distanceFromLastBurst = -1; - if (mLastBurstLocation != null) { - distanceFromLastBurst = (int) mLastBurstLocation.distanceTo(location); - - // Too many bursts from same location, don't upload - if (distanceFromLastBurst < MIN_DISTANCE_BETWEEN_BURSTS && - mNumBurstsFromLastLocation >= MAX_BURSTS_FROM_SAME_LOCATION) { - log("NO UPLOAD: Too many bursts from same location."); - return; - } - } - - if (mCurrentBurstStartTime == 0) { - // Start the burst! - mCurrentBurstStartTime = now; - mCurrentBurstNumSamples = 1; - trigger = GDebugProfile.TRIGGER_COLLECTION_START_BURST; - - } else if (now - mCurrentBurstStartTime > restTime) { - // Burst got old, start a new one - mCurrentBurstStartTime = now; - mCurrentBurstNumSamples = 1; - trigger = GDebugProfile.TRIGGER_COLLECTION_RESTART_BURST; - - } else if (mCurrentBurstNumSamples == BURST_NUM_SAMPLES - 1) { - // Finished a burst - mLastBurstEndTime = now; - mCurrentBurstStartTime = 0; - mCurrentBurstNumSamples = 0; - - // Make sure we don't upload too many bursts from same location - if (mLastBurstLocation == null) { - mLastBurstLocation = new Location(location); - mNumBurstsFromLastLocation = 1; - trigger = GDebugProfile.TRIGGER_COLLECTION_END_BURST; - - } else { - - if (distanceFromLastBurst != -1 && - distanceFromLastBurst < MIN_DISTANCE_BETWEEN_BURSTS) { - // User hasnt moved much from last location, keep track of count, - // don't update last burst loc - mNumBurstsFromLastLocation++; - trigger = GDebugProfile.TRIGGER_COLLECTION_END_BURST_AT_SAME_LOCATION; - - } else { - // User has moved enough, update last burst loc - mLastBurstLocation.set(location); - mNumBurstsFromLastLocation = 1; - trigger = GDebugProfile.TRIGGER_COLLECTION_END_BURST; - } - } - - } else { - // Increment burst sample count - mCurrentBurstNumSamples++; - trigger = GDebugProfile.TRIGGER_COLLECTION_CONTINUE_BURST; - } - - } else if (mLastUploadedLocation != null - && (mLastUploadedLocation.distanceTo(location) > MIN_DISTANCE_BETWEEN_REPORTS)) { - // If not in burst mode but has moved a reasonable distance, upload! - trigger = GDebugProfile.TRIGGER_COLLECTION_MOVED_DISTANCE; - - } else { - // Not in burst mode or hasn't moved enough - log("NO UPLOAD: Not in burst or moving mode. Resting for " + restTime + " ms"); - return; - } - - log("updateLocation(): Updated location with trigger " + trigger); - addToQueue(trigger); - } - - /** - * Updates wifi scan results if collection is enabled - * - * @param currentScanResults scan results - */ - public synchronized void updateWifiScanResults(List currentScanResults) { - if (!isCollectionEnabled()) { - return; - } - - if (currentScanResults == null || currentScanResults.size() == 0) { - return; - } - - long now = SystemClock.elapsedRealtime(); - - // If wifi scan recently received, then don't upload - if ((mLastWifiScanElapsedTime != 0) - && ((now - mLastWifiScanElapsedTime) <= MIN_TIME_BETWEEN_WIFI_REPORTS)) { - return; - } - - if (mWifiCurrentScanResults == null) { - mWifiCurrentScanResults = new ArrayList(); - } else { - mWifiCurrentScanResults.clear(); - } - mWifiCurrentScanResults.addAll(currentScanResults); - - // If wifi has changed enough - boolean wifiHasChanged = false; - - if (mWifiLastScanResults == null) { - wifiHasChanged = true; - } else { - // Calculate the number of new AP points received - HashSet previous = new HashSet(); - HashSet current = new HashSet(); - for (ScanResult s : mWifiLastScanResults) { - previous.add(s.BSSID); - } - for (ScanResult s : mWifiCurrentScanResults) { - current.add(s.BSSID); - } - current.removeAll(previous); - - if (current.size() > - Math.min(MIN_CHANGED_WIFI_POINTS, ((mWifiCurrentScanResults.size()+1)/2))) { - wifiHasChanged = true; - } - } - - if (!wifiHasChanged) { - log("updateWifiScanResults(): Wifi results haven't changed much"); - return; - } - - if (mWifiLastScanResults == null) { - mWifiLastScanResults = new ArrayList(); - } else { - mWifiLastScanResults.clear(); - } - mWifiLastScanResults.addAll(mWifiCurrentScanResults); - - mLastWifiScanElapsedTime = now; - mLastWifiScanRealTime = System.currentTimeMillis(); - - log("updateWifiScanResults(): Updated " + mWifiLastScanResults.size() + " APs"); - addToQueue(GDebugProfile.TRIGGER_WIFI_CHANGE); - } - - /** - * Updates the status of the network location provider. - * - * @param enabled true if user has enabled network location based on Google's database - * of wifi points and cell towers. - */ - public void updateNetworkProviderStatus(boolean enabled) { - mNetworkProviderIsEnabled = enabled; - } - - /** - * Updates the battery health. Battery level is healthy if there is greater than - * {@link #MIN_BATTERY_LEVEL} percentage left or if the device is plugged in - * - * @param scale maximum scale for battery - * @param level current level - * @param plugged true if device is plugged in - */ - public void updateBatteryState(int scale, int level, boolean plugged) { - mBatteryLevelIsHealthy = (plugged || (level >= (MIN_BATTERY_LEVEL * scale))); - mBatteryChargedAndPlugged = (plugged && (level >= (CHARGED_BATTERY_LEVEL * scale))); - } - - /** - * Anonymous data collection is only enabled when the user has enabled the network - * location provider, i.e. is making use of the service and if the device battery level - * is healthy. - * - * Additionally, data collection will *never* happen if the system - * property ro.com.google.locationfeatures is not set. - * - * @return true if anonymous location collection is enabled - */ - private boolean isCollectionEnabled() { - // This class provides a Google-specific location feature, so it's enabled only - // when the system property ro.com.google.locationfeatures is set. - if (!SystemProperties.get("ro.com.google.locationfeatures").equals("1")) { - return false; - } - return mBatteryLevelIsHealthy && mNetworkProviderIsEnabled; - } - - /** - * Adds to the MASF request queue - * - * @param trigger the event that triggered this collection event - */ - private synchronized void addToQueue(int trigger) { - - long now = SystemClock.elapsedRealtime(); - - // Include location if: - // It has been received in the last 12 minutes. - boolean includeLocation = false; - if (mLastKnownLocation != null && - (now - mLastKnownLocationTime <= MIN_VALID_LOCATION_TIME)) { - includeLocation = true; - } - - // Include wifi if: - // Wifi is new OR - // Wifi is old but last wifi upload was without location - boolean includeWifi = false; - if (trigger == GDebugProfile.TRIGGER_WIFI_CHANGE || (mWifiUploadedWithoutLocation && - includeLocation && (now - mLastWifiScanElapsedTime < MIN_VALID_LOCATION_TIME))) { - includeWifi = true; - mWifiUploadedWithoutLocation = !includeLocation; - } - - // Include cell if: - // Wifi or location information is already being included - // The cell hasn't been uploaded with the same location recently - boolean includeCell = false; - - if (mCellState != null && (includeWifi || includeLocation)) { - includeCell = true; - - if (!includeWifi && includeLocation) { - if (mCellUploads.contains(mCellState, mLastKnownLocation)) { - includeCell = false; - } - } - } - - if (!includeLocation && !includeWifi) { - log("NO UPLOAD: includeLocation=false, includeWifi=false"); - return; - } else if (!includeCell && trigger == GDebugProfile.TRIGGER_CELL_CHANGE) { - log("NO UPLOAD: includeCell=false"); - return; - } else { - log("UPLOAD: includeLocation=" + includeLocation + ", includeWifi=" + - includeWifi + ", includeCell=" + includeCell); - } - - if (includeLocation) { - // Update last uploaded location - if (mLastUploadedLocation == null) { - mLastUploadedLocation = new Location(mLastKnownLocation); - } else { - mLastUploadedLocation.set(mLastKnownLocation); - } - mLastUploadedLocationTime = now; - } - - // Immediately send output if finishing a burst for live traffic requirements - boolean immediate = false; - if (trigger == GDebugProfile.TRIGGER_COLLECTION_END_BURST|| - trigger == GDebugProfile.TRIGGER_COLLECTION_END_BURST_AT_SAME_LOCATION) { - immediate = true; - } - - try { - CellState cell = includeCell ? mCellState : null; - List wifi = includeWifi ? mWifiLastScanResults : null; - Location loc = includeLocation ? mLastUploadedLocation : null; - - mMasfClient.queueCollectionReport( - trigger, loc, cell, wifi, mLastWifiScanRealTime, immediate); - - } catch(Exception e) { - Log.e(TAG, "addToQueue got exception:", e); - } - } - - private class CellUploads { - - private final int MIN_DISTANCE = MIN_DISTANCE_BETWEEN_REPORTS / 4; // 50 meters - private final int SIZE = 5; - private final String[] cells = new String[SIZE]; - private final boolean[] valid = new boolean[SIZE]; - private final double[] latitudes = new double[SIZE]; - private final double[] longitudes = new double[SIZE]; - private final float[] distance = new float[1]; - private int index = 0; - - private CellUploads() { - for (int i = 0; i < SIZE; i++) { - valid[i] = false; - } - } - - private boolean contains(CellState cellState, Location loc) { - String cell = - cellState.getCid() + ":" + cellState.getLac() + ":" + - cellState.getMnc() + ":" + cellState.getMcc(); - double lat = loc.getLatitude(); - double lng = loc.getLongitude(); - - for (int i = 0; i < SIZE; i++) { - if (valid[i] && cells[i].equals(cell)) { - Location.distanceBetween(latitudes[i], longitudes[i], lat, lng, distance); - if (distance[0] < MIN_DISTANCE) { - return true; - } - } - } - cells[index] = cell; - latitudes[index] = lat; - longitudes[index] = lng; - valid[index] = true; - - index++; - if (index == SIZE) { - index = 0; - } - return false; - } - } - - private void log(String string) { - if (Log.isLoggable(TAG, Log.VERBOSE)) { - Log.d(TAG, string); - } - } -} diff --git a/location/java/com/android/internal/location/LocationMasfClient.java b/location/java/com/android/internal/location/LocationMasfClient.java deleted file mode 100644 index 179c6300136d6acdcb0e4e0da9e7ca12ad0cca5c..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/LocationMasfClient.java +++ /dev/null @@ -1,1194 +0,0 @@ -// Copyright 2008 The Android Open Source Project - -package com.android.internal.location; - -import com.google.common.Config; -import com.google.common.android.AndroidConfig; -import com.google.common.io.protocol.ProtoBuf; -import com.google.masf.MobileServiceMux; -import com.google.masf.ServiceCallback; -import com.google.masf.protocol.PlainRequest; -import com.google.masf.protocol.Request; - -import com.android.internal.location.protocol.GAddress; -import com.android.internal.location.protocol.GAddressComponent; -import com.android.internal.location.protocol.GAppProfile; -import com.android.internal.location.protocol.GCell; -import com.android.internal.location.protocol.GCellularPlatformProfile; -import com.android.internal.location.protocol.GCellularProfile; -import com.android.internal.location.protocol.GDebugProfile; -import com.android.internal.location.protocol.GDeviceLocation; -import com.android.internal.location.protocol.GFeature; -import com.android.internal.location.protocol.GGeocodeRequest; -import com.android.internal.location.protocol.GLatLng; -import com.android.internal.location.protocol.GLocReply; -import com.android.internal.location.protocol.GLocReplyElement; -import com.android.internal.location.protocol.GLocRequest; -import com.android.internal.location.protocol.GLocRequestElement; -import com.android.internal.location.protocol.GLocation; -import com.android.internal.location.protocol.GPlatformProfile; -import com.android.internal.location.protocol.GPrefetchMode; -import com.android.internal.location.protocol.GRectangle; -import com.android.internal.location.protocol.GWifiDevice; -import com.android.internal.location.protocol.GWifiProfile; -import com.android.internal.location.protocol.GcellularMessageTypes; -import com.android.internal.location.protocol.GdebugprofileMessageTypes; -import com.android.internal.location.protocol.GlatlngMessageTypes; -import com.android.internal.location.protocol.GlocationMessageTypes; -import com.android.internal.location.protocol.GrectangleMessageTypes; -import com.android.internal.location.protocol.GwifiMessageTypes; -import com.android.internal.location.protocol.LocserverMessageTypes; -import com.android.internal.location.protocol.ResponseCodes; - -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; - -import android.content.Context; -import android.location.Address; -import android.location.Location; -import android.location.LocationManager; -import android.net.wifi.ScanResult; -import android.os.Build; -import android.os.Bundle; -import android.os.SystemClock; -import android.text.TextUtils; -import android.util.EventLog; -import android.util.Log; -import android.telephony.NeighboringCellInfo; - -/** - * Service to communicate to the Google Location Server (GLS) via MASF server - * - * {@hide} - */ -public class LocationMasfClient { - - static final String TAG = "LocationMasfClient"; - - // Address of the MASF server to connect to. - private static final String MASF_SERVER_ADDRESS = "http://www.google.com/loc/m/api"; - - // MobileServiceMux app/platform-specific values (application name matters!) - private static final String APPLICATION_NAME = "location"; - private static final String APPLICATION_VERSION = "1.0"; - private static final String PLATFORM_ID = "android"; - private static final String DISTRIBUTION_CHANNEL = "android"; - private static String PLATFORM_BUILD = null; - - // Methods exposed by the MASF server - private static final String REQUEST_QUERY_LOC = "g:loc/ql"; - private static final String REQUEST_UPLOAD_LOC = "g:loc/ul"; - - // Max time to wait for request to end - private static final long REQUEST_TIMEOUT = 5000; - - // Constant to divide Lat, Lng returned by server - private static final double E7 = 10000000.0; - - // Max wifi points to include - private static final int MAX_WIFI_TO_INCLUDE = 25; - - // Location of GLS cookie - private static final String PLATFORM_KEY_FILE = "gls.platform.key"; - private String mPlatformKey; - - // Cell cache - private LocationCache mLocationCache; - - // Location object that the cache manages - private Location mLocation = new Location(LocationManager.NETWORK_PROVIDER); - - // ProtoBuf objects we can reuse for subsequent requests - private final int MAX_COLLECTION_BUFFER_SIZE = 30; - private final long MIN_COLLECTION_INTERVAL = 15 * 60 * 1000; // 15 minutes - private ProtoBuf mPlatformProfile = null; - private ProtoBuf mCellularPlatformProfile = null; - private ProtoBuf mCurrentCollectionRequest = null; - private long mLastCollectionUploadTime = 0; - - // Objects for current request - private List mWifiScanResults = new ArrayList(); - private CellState mCellState = null; - private List mCellHistory; - - // This tag is used for the event log. - private static final int COLLECTION_EVENT_LOG_TAG = 2740; - - // Extra values to designate whether location is from cache or network request - private static final String EXTRA_KEY_LOCATION_SOURCE = "networkLocationSource"; - private static final String EXTRA_VALUE_LOCATION_SOURCE_CACHED = "cached"; - private static final String EXTRA_VALUE_LOCATION_SOURCE_SERVER = "server"; - - // Maximum accuracy tolerated for a valid location - private static final int MAX_ACCURACY_ALLOWED = 5000; // 5km - - // Indicates whether this is the first message after a device restart - private boolean mDeviceRestart = true; - - /** - * Initializes the MobileServiceMux. Must be called before using any other function in the - * class. - */ - public LocationMasfClient(Context context) { - MobileServiceMux mux = MobileServiceMux.getSingleton(); - if (mux == null) { - AndroidConfig config = new AndroidConfig(context); - Config.setConfig(config); - - MobileServiceMux.initialize - (MASF_SERVER_ADDRESS, - APPLICATION_NAME, - APPLICATION_VERSION, - PLATFORM_ID, - DISTRIBUTION_CHANNEL); - } - mLocationCache = new LocationCache(); - - if (Build.FINGERPRINT != null) { - PLATFORM_BUILD = PLATFORM_ID + "/" + Build.FINGERPRINT; - } else { - PLATFORM_BUILD = PLATFORM_ID; - } - } - - /** - * Returns the location for the given cell or wifi information. - * - * @param apps list of apps requesting location - * @param trigger event that triggered this network request - * @param cellState cell tower state - * @param cellHistory history of acquired cell states - * @param scanResults list of wifi scan results - * @param scanTime time at which wireless scan was triggered - * @param callback function to call with received location - */ - public synchronized void getNetworkLocation(Collection apps, int trigger, - CellState cellState, List cellHistory, List scanResults, - long scanTime, NetworkLocationProvider.Callback callback) { - - final NetworkLocationProvider.Callback finalCallback = callback; - - boolean foundInCache = - mLocationCache.lookup(cellState, cellHistory, scanResults, mLocation); - - if (foundInCache) { - - if (SystemClock.elapsedRealtime() - mLastCollectionUploadTime > MIN_COLLECTION_INTERVAL) { - uploadCollectionReport(true); - } - - Bundle extras = mLocation.getExtras() == null ? new Bundle() : mLocation.getExtras(); - extras.putString(EXTRA_KEY_LOCATION_SOURCE, EXTRA_VALUE_LOCATION_SOURCE_CACHED); - mLocation.setExtras(extras); - - Log.d(TAG, "getNetworkLocation(): Returning cache location with accuracy " + - mLocation.getAccuracy()); - finalCallback.locationReceived(mLocation, true); - return; - } - - Log.d(TAG, "getNetworkLocation(): Location not found in cache, making network request"); - - // Copy over to objects for this request - mWifiScanResults.clear(); - if (scanResults != null) { - mWifiScanResults.addAll(scanResults); - } - mCellState = cellState; - mCellHistory = cellHistory; - - // Create a RequestElement - ProtoBuf requestElement = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST_ELEMENT); - - // Debug profile - ProtoBuf debugProfile = new ProtoBuf(GdebugprofileMessageTypes.GDEBUG_PROFILE); - requestElement.setProtoBuf(GLocRequestElement.DEBUG_PROFILE, debugProfile); - - if (mDeviceRestart) { - debugProfile.setBool(GDebugProfile.DEVICE_RESTART, true); - mDeviceRestart = false; - } - - if (trigger != -1) { - debugProfile.setInt(GDebugProfile.TRIGGER, trigger); - } - - // Cellular profile - if (mCellState != null && mCellState.isValid()) { - ProtoBuf cellularProfile = new ProtoBuf(GcellularMessageTypes.GCELLULAR_PROFILE); - cellularProfile.setLong(GCellularProfile.TIMESTAMP, mCellState.getTime()); - cellularProfile.setInt(GCellularProfile.PREFETCH_MODE, - GPrefetchMode.PREFETCH_MODE_MORE_NEIGHBORS); - - // Primary cell - ProtoBuf primaryCell = new ProtoBuf(GcellularMessageTypes.GCELL); - primaryCell.setInt(GCell.LAC, mCellState.getLac()); - primaryCell.setInt(GCell.CELLID, mCellState.getCid()); - - if ((mCellState.getMcc() != -1) && (mCellState.getMnc() != -1)) { - primaryCell.setInt(GCell.MCC, mCellState.getMcc()); - primaryCell.setInt(GCell.MNC, mCellState.getMnc()); - } - - if (mCellState.getSignalStrength() != -1) { - primaryCell.setInt(GCell.RSSI, mCellState.getSignalStrength()); - } - - cellularProfile.setProtoBuf(GCellularProfile.PRIMARY_CELL, primaryCell); - - // History of cells - for (CellState c : cellHistory) { - ProtoBuf pastCell = new ProtoBuf(GcellularMessageTypes.GCELL); - pastCell.setInt(GCell.LAC, c.getLac()); - pastCell.setInt(GCell.CELLID, c.getCid()); - if ((c.getMcc() != -1) && (c.getMnc() != -1)) { - pastCell.setInt(GCell.MCC, c.getMcc()); - pastCell.setInt(GCell.MNC, c.getMnc()); - } - - if (c.getSignalStrength() != -1) { - pastCell.setInt(GCell.RSSI, c.getSignalStrength()); - } - - pastCell.setInt(GCell.AGE, (int)(mCellState.getTime() - c.getTime())); - cellularProfile.addProtoBuf(GCellularProfile.HISTORICAL_CELLS, pastCell); - } - - // Neighboring Cells - addNeighborsToCellProfile(mCellState, cellularProfile); - - requestElement.setProtoBuf(GLocRequestElement.CELLULAR_PROFILE, cellularProfile); - } - - // Wifi profile - if (mWifiScanResults != null && mWifiScanResults.size() > 0) { - ProtoBuf wifiProfile = new ProtoBuf(GwifiMessageTypes.GWIFI_PROFILE); - wifiProfile.setLong(GWifiProfile.TIMESTAMP, scanTime); - wifiProfile.setInt(GWifiProfile.PREFETCH_MODE, - GPrefetchMode.PREFETCH_MODE_MORE_NEIGHBORS); - - int count = 0; - for (ScanResult s : mWifiScanResults) { - ProtoBuf wifiDevice = new ProtoBuf(GwifiMessageTypes.GWIFI_DEVICE); - wifiDevice.setString(GWifiDevice.MAC, s.BSSID); - wifiProfile.addProtoBuf(GWifiProfile.WIFI_DEVICES, wifiDevice); - count++; - if (count >= MAX_WIFI_TO_INCLUDE) { - break; - } - } - - requestElement.setProtoBuf(GLocRequestElement.WIFI_PROFILE, wifiProfile); - } - - // Request to send over wire - ProtoBuf request = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST); - request.addProtoBuf(GLocRequest.REQUEST_ELEMENTS, requestElement); - - // Create a Platform Profile - ProtoBuf platformProfile = createPlatformProfile(); - if (mCellState != null && mCellState.isValid()) { - // Include cellular platform Profile - ProtoBuf cellularPlatform = createCellularPlatformProfile(mCellState); - platformProfile.setProtoBuf(GPlatformProfile.CELLULAR_PLATFORM_PROFILE, - cellularPlatform); - } - request.setProtoBuf(GLocRequest.PLATFORM_PROFILE, platformProfile); - - // Include App Profiles - if (apps != null) { - for (String app : apps) { - ProtoBuf appProfile = new ProtoBuf(GlocationMessageTypes.GAPP_PROFILE); - appProfile.setString(GAppProfile.APP_NAME, app); - request.addProtoBuf(GLocRequest.APP_PROFILES, appProfile); - } - } - - // Queue any waiting collection events as well - uploadCollectionReport(false); - - ByteArrayOutputStream payload = new ByteArrayOutputStream(); - try { - request.outputTo(payload); - } catch (IOException e) { - Log.e(TAG, "getNetworkLocation(): unable to write request to payload", e); - return; - } - - // Creates request and a listener with a call back function - ProtoBuf reply = new ProtoBuf(LocserverMessageTypes.GLOC_REPLY); - Request plainRequest = - new PlainRequest(REQUEST_QUERY_LOC, (short)0, payload.toByteArray()); - - ProtoRequestListener listener = new ProtoRequestListener(reply, new ServiceCallback() { - public void onRequestComplete(Object result) { - ProtoBuf response = (ProtoBuf) result; - boolean successful = parseNetworkLocationReply(response); - finalCallback.locationReceived(mLocation, successful); - - } - }); - plainRequest.setListener(listener); - - // Send request - MobileServiceMux serviceMux = MobileServiceMux.getSingleton(); - serviceMux.submitRequest(plainRequest, true); - } - - private synchronized boolean parseNetworkLocationReply(ProtoBuf response) { - if (response == null) { - Log.e(TAG, "getNetworkLocation(): response is null"); - return false; - } - - int status1 = response.getInt(GLocReply.STATUS); - if (status1 != ResponseCodes.STATUS_STATUS_SUCCESS) { - Log.e(TAG, "getNetworkLocation(): RPC failed with status " + status1); - return false; - } - - if (response.has(GLocReply.PLATFORM_KEY)) { - String platformKey = response.getString(GLocReply.PLATFORM_KEY); - if (!TextUtils.isEmpty(platformKey)) { - setPlatformKey(platformKey); - } - } - - if (!response.has(GLocReply.REPLY_ELEMENTS)) { - Log.e(TAG, "getNetworkLocation(): no ReplyElement"); - return false; - } - ProtoBuf replyElement = response.getProtoBuf(GLocReply.REPLY_ELEMENTS); - - // Get prefetched data to add to the device cache - Log.d(TAG, "getNetworkLocation(): Number of prefetched entries " + - replyElement.getCount(GLocReplyElement.DEVICE_LOCATION)); - long now = System.currentTimeMillis(); - for (int i = 0; i < replyElement.getCount(GLocReplyElement.DEVICE_LOCATION); i++ ) { - ProtoBuf device = replyElement.getProtoBuf(GLocReplyElement.DEVICE_LOCATION, i); - double lat = 0; - double lng = 0; - int accuracy = -1; - int confidence = -1; - int locType = -1; - if (device.has(GDeviceLocation.LOCATION)) { - ProtoBuf deviceLocation = device.getProtoBuf(GDeviceLocation.LOCATION); - if (deviceLocation.has(GLocation.ACCURACY) && - deviceLocation.has(GLocation.LAT_LNG) - && deviceLocation.has(GLocation.CONFIDENCE)) { - lat = deviceLocation.getProtoBuf(GLocation.LAT_LNG). - getInt(GLatLng.LAT_E7) / E7; - lng = deviceLocation.getProtoBuf(GLocation.LAT_LNG). - getInt(GLatLng.LNG_E7) / E7; - accuracy = deviceLocation.getInt(GLocation.ACCURACY); - confidence = deviceLocation.getInt(GLocation.CONFIDENCE); - } - if (deviceLocation.has(GLocation.LOC_TYPE)) { - locType = deviceLocation.getInt(GLocation.LOC_TYPE); - } - } - - // Get cell key - if (device.has(GDeviceLocation.CELL) && locType != GLocation.LOCTYPE_TOWER_LOCATION) { - ProtoBuf deviceCell = device.getProtoBuf(GDeviceLocation.CELL); - int cid = deviceCell.getInt(GCell.CELLID); - int lac = deviceCell.getInt(GCell.LAC); - int mcc = -1; - int mnc = -1; - if (deviceCell.has(GCell.MNC) && deviceCell.has(GCell.MCC)) { - mcc = deviceCell.getInt(GCell.MCC); - mnc = deviceCell.getInt(GCell.MNC); - } - mLocationCache. - insert(mcc, mnc, lac, cid, lat, lng, accuracy, confidence, now); - } - - // Get wifi key - if (device.has(GDeviceLocation.WIFI_DEVICE)) { - ProtoBuf deviceWifi = device.getProtoBuf(GDeviceLocation.WIFI_DEVICE); - String bssid = deviceWifi.getString(GWifiDevice.MAC); - mLocationCache.insert(bssid, lat, lng, accuracy, confidence, now); - } - } - - mLocationCache.save(); - - int status2 = replyElement.getInt(GLocReplyElement.STATUS); - if (status2 != ResponseCodes.STATUS_STATUS_SUCCESS && - status2 != ResponseCodes.STATUS_STATUS_FAILED) { - Log.e(TAG, "getNetworkLocation(): GLS failed with status " + status2); - return false; - } - - // For consistent results for user, always return cache computed location - boolean foundInCache = - mLocationCache.lookup(mCellState, mCellHistory, mWifiScanResults, mLocation); - - if (foundInCache) { - - Bundle extras = mLocation.getExtras() == null ? new Bundle() : mLocation.getExtras(); - extras.putString(EXTRA_KEY_LOCATION_SOURCE, EXTRA_VALUE_LOCATION_SOURCE_SERVER); - mLocation.setExtras(extras); - - Log.d(TAG, "getNetworkLocation(): Returning network location with accuracy " + - mLocation.getAccuracy()); - return true; - } - - if (status2 == ResponseCodes.STATUS_STATUS_FAILED) { - Log.e(TAG, "getNetworkLocation(): GLS does not have location"); - // We return true here since even though there is no location, there is no need to retry - // since server doesn't have location - return true; - } - - // Get server computed location to return for now - if (!replyElement.has(GLocReplyElement.LOCATION)) { - Log.e(TAG, "getNetworkLocation(): no location in ReplyElement"); - return false; - } - ProtoBuf location = replyElement.getProtoBuf(GLocReplyElement.LOCATION); - - if (!location.has(GLocation.LAT_LNG)) { - Log.e(TAG, "getNetworkLocation(): no Lat,Lng in location"); - return false; - } - - ProtoBuf point = location.getProtoBuf(GLocation.LAT_LNG); - double lat = point.getInt(GLatLng.LAT_E7) / E7; - double lng = point.getInt(GLatLng.LNG_E7) / E7; - - int accuracy = 0; - if (location.has(GLocation.ACCURACY)) { - accuracy = location.getInt(GLocation.ACCURACY); - } - - if (accuracy > MAX_ACCURACY_ALLOWED) { - Log.e(TAG, "getNetworkLocation(): accuracy is too high " + accuracy); - return false; - } - - mLocation.setLatitude(lat); - mLocation.setLongitude(lng); - mLocation.setTime(System.currentTimeMillis()); - mLocation.setAccuracy(accuracy); - - Bundle extras = mLocation.getExtras() == null ? new Bundle() : mLocation.getExtras(); - extras.putString(EXTRA_KEY_LOCATION_SOURCE, EXTRA_VALUE_LOCATION_SOURCE_SERVER); - mLocation.setExtras(extras); - - Log.e(TAG, "getNetworkLocation(): Returning *server* computed location with accuracy " + - accuracy); - - return true; - } - - /** - * Gets a reverse geocoded location from the given lat,lng point. Also attaches the name - * of the requesting application with the request - * - * @param locale locale for geocoded location - * @param appPackageName name of the package, may be null - * @param lat latitude - * @param lng longitude - * @param maxResults maximum number of addresses to return - * @param addrs the list of addresses to fill up - * @throws IOException if network is unavailable or some other issue - */ - public void reverseGeocode(Locale locale, String appPackageName, - double lat, double lng, int maxResults, List
                addrs) throws IOException { - - // Reverse geocoding request element - ProtoBuf requestElement = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST_ELEMENT); - - ProtoBuf latlngElement = new ProtoBuf(GlatlngMessageTypes.GLAT_LNG); - latlngElement.setInt(GLatLng.LAT_E7, (int)(lat * E7)); - latlngElement.setInt(GLatLng.LNG_E7, (int)(lng * E7)); - - ProtoBuf locationElement = new ProtoBuf(GlocationMessageTypes.GLOCATION); - locationElement.setProtoBuf(GLocation.LAT_LNG, latlngElement); - locationElement.setLong(GLocation.TIMESTAMP, System.currentTimeMillis()); - requestElement.setProtoBuf(GLocRequestElement.LOCATION, locationElement); - - ProtoBuf geocodeElement = - new ProtoBuf(LocserverMessageTypes.GGEOCODE_REQUEST); - geocodeElement.setInt(GGeocodeRequest.NUM_FEATURE_LIMIT, maxResults); - requestElement.setProtoBuf(GLocRequestElement.GEOCODE, geocodeElement); - - // Request to send over wire - ProtoBuf request = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST); - request.addProtoBuf(GLocRequest.REQUEST_ELEMENTS, requestElement); - - // Create platform profile - ProtoBuf platformProfile = createPlatformProfile(locale); - request.setProtoBuf(GLocRequest.PLATFORM_PROFILE, platformProfile); - - // Include app name - if (appPackageName != null) { - ProtoBuf appProfile = new ProtoBuf(GlocationMessageTypes.GAPP_PROFILE); - appProfile.setString(GAppProfile.APP_NAME, appPackageName); - request.setProtoBuf(GLocRequest.APP_PROFILES, appProfile); - } - - // Queue any waiting collection events as well - uploadCollectionReport(false); - - ByteArrayOutputStream payload = new ByteArrayOutputStream(); - try { - request.outputTo(payload); - } catch (IOException e) { - Log.e(TAG, "reverseGeocode(): unable to write request to payload"); - throw e; - } - - // Creates request and a listener with no callback function - ProtoBuf reply = new ProtoBuf(LocserverMessageTypes.GLOC_REPLY); - Request plainRequest = - new PlainRequest(REQUEST_QUERY_LOC, (short)0, payload.toByteArray()); - ProtoRequestListener listener = new ProtoRequestListener(reply, null); - plainRequest.setListener(listener); - - // Immediately send request and block for response until REQUEST_TIMEOUT - MobileServiceMux serviceMux = MobileServiceMux.getSingleton(); - serviceMux.submitRequest(plainRequest, true); - ProtoBuf response; - try { - response = (ProtoBuf)listener.getAsyncResult().get(REQUEST_TIMEOUT); - } catch (InterruptedException e) { - Log.e(TAG, "reverseGeocode(): response timeout"); - throw new IOException("response time-out"); - } - - if (response == null) { - throw new IOException("Unable to parse response from server"); - } - - // Parse the response - int status1 = response.getInt(GLocReply.STATUS); - if (status1 != ResponseCodes.STATUS_STATUS_SUCCESS) { - Log.e(TAG, "reverseGeocode(): RPC failed with status " + status1); - throw new IOException("RPC failed with status " + status1); - } - - if (response.has(GLocReply.PLATFORM_KEY)) { - String platformKey = response.getString(GLocReply.PLATFORM_KEY); - if (!TextUtils.isEmpty(platformKey)) { - setPlatformKey(platformKey); - } - } - - if (!response.has(GLocReply.REPLY_ELEMENTS)) { - Log.e(TAG, "reverseGeocode(): no ReplyElement"); - return; - } - ProtoBuf replyElement = response.getProtoBuf(GLocReply.REPLY_ELEMENTS); - - int status2 = replyElement.getInt(GLocReplyElement.STATUS); - if (status2 != ResponseCodes.STATUS_STATUS_SUCCESS) { - Log.e(TAG, "reverseGeocode(): GLS failed with status " + status2); - return; - } - - if (!replyElement.has(GLocReplyElement.LOCATION)) { - Log.e(TAG, "reverseGeocode(): no location in ReplyElement"); - return; - } - - ProtoBuf location = replyElement.getProtoBuf(GLocReplyElement.LOCATION); - if (!location.has(GLocation.FEATURE)) { - Log.e(TAG, "reverseGeocode(): no feature in GLocation"); - return; - } - - getAddressFromProtoBuf(location, locale, addrs); - } - - /** - * Gets a forward geocoded location from the given location string. Also attaches the name - * of the requesting application with the request - * - * Optionally, can specify the bounding box that the search results should be restricted to - * - * @param locale locale for geocoded location - * @param appPackageName name of the package, may be null - * @param locationString string to forward geocode - * @param lowerLeftLatitude latitude of lower left point of bounding box - * @param lowerLeftLongitude longitude of lower left point of bounding box - * @param upperRightLatitude latitude of upper right point of bounding box - * @param upperRightLongitude longitude of upper right point of bounding box - * @param maxResults maximum number of results to return - * @param addrs the list of addresses to fill up - * @throws IOException if network is unavailable or some other issue - */ - public void forwardGeocode(Locale locale, String appPackageName, String locationString, - double lowerLeftLatitude, double lowerLeftLongitude, - double upperRightLatitude, double upperRightLongitude, int maxResults, List
                addrs) - throws IOException { - - // Forward geocoding request element - ProtoBuf requestElement = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST_ELEMENT); - - ProtoBuf locationElement = new ProtoBuf(GlocationMessageTypes.GLOCATION); - locationElement.setLong(GLocation.TIMESTAMP, System.currentTimeMillis()); - locationElement.setString(GLocation.LOCATION_STRING, locationString); - requestElement.setProtoBuf(GLocRequestElement.LOCATION, locationElement); - - ProtoBuf geocodeElement = - new ProtoBuf(LocserverMessageTypes.GGEOCODE_REQUEST); - geocodeElement.setInt(GGeocodeRequest.NUM_FEATURE_LIMIT, maxResults); - - if (lowerLeftLatitude != 0 && lowerLeftLongitude !=0 && - upperRightLatitude !=0 && upperRightLongitude !=0) { - ProtoBuf lowerLeft = new ProtoBuf(GlatlngMessageTypes.GLAT_LNG); - lowerLeft.setInt(GLatLng.LAT_E7, (int)(lowerLeftLatitude * E7)); - lowerLeft.setInt(GLatLng.LNG_E7, (int)(lowerLeftLongitude * E7)); - - ProtoBuf upperRight = new ProtoBuf(GlatlngMessageTypes.GLAT_LNG); - upperRight.setInt(GLatLng.LAT_E7, (int)(upperRightLatitude * E7)); - upperRight.setInt(GLatLng.LNG_E7, (int)(upperRightLongitude * E7)); - - ProtoBuf boundingBox = new ProtoBuf(GrectangleMessageTypes.GRECTANGLE); - boundingBox.setProtoBuf(GRectangle.LOWER_LEFT, lowerLeft); - boundingBox.setProtoBuf(GRectangle.UPPER_RIGHT, upperRight); - geocodeElement.setProtoBuf(GGeocodeRequest.BOUNDING_BOX, boundingBox); - } - requestElement.setProtoBuf(GLocRequestElement.GEOCODE, geocodeElement); - - // Request to send over wire - ProtoBuf request = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST); - request.addProtoBuf(GLocRequest.REQUEST_ELEMENTS, requestElement); - - // Create platform profile - ProtoBuf platformProfile = createPlatformProfile(locale); - request.setProtoBuf(GLocRequest.PLATFORM_PROFILE, platformProfile); - - // Include app name - if (appPackageName != null) { - ProtoBuf appProfile = new ProtoBuf(GlocationMessageTypes.GAPP_PROFILE); - appProfile.setString(GAppProfile.APP_NAME, appPackageName); - request.setProtoBuf(GLocRequest.APP_PROFILES, appProfile); - } - - // Queue any waiting collection events as well - uploadCollectionReport(false); - - ByteArrayOutputStream payload = new ByteArrayOutputStream(); - try { - request.outputTo(payload); - } catch (IOException e) { - Log.e(TAG, "forwardGeocode(): unable to write request to payload"); - throw e; - } - - // Creates request and a listener with no callback function - ProtoBuf reply = new ProtoBuf(LocserverMessageTypes.GLOC_REPLY); - Request plainRequest = - new PlainRequest(REQUEST_QUERY_LOC, (short)0, payload.toByteArray()); - ProtoRequestListener listener = new ProtoRequestListener(reply, null); - plainRequest.setListener(listener); - - // Immediately send request and block for response until REQUEST_TIMEOUT - MobileServiceMux serviceMux = MobileServiceMux.getSingleton(); - serviceMux.submitRequest(plainRequest, true); - ProtoBuf response; - try { - response = (ProtoBuf)listener.getAsyncResult().get(REQUEST_TIMEOUT); - } catch (InterruptedException e) { - Log.e(TAG, "forwardGeocode(): response timeout"); - throw new IOException("response time-out"); - } - - if (response == null) { - throw new IOException("Unable to parse response from server"); - } - - // Parse the response - int status1 = response.getInt(GLocReply.STATUS); - if (status1 != ResponseCodes.STATUS_STATUS_SUCCESS) { - Log.e(TAG, "forwardGeocode(): RPC failed with status " + status1); - throw new IOException("RPC failed with status " + status1); - } - - if (response.has(GLocReply.PLATFORM_KEY)) { - String platformKey = response.getString(GLocReply.PLATFORM_KEY); - if (!TextUtils.isEmpty(platformKey)) { - setPlatformKey(platformKey); - } - } - - if (!response.has(GLocReply.REPLY_ELEMENTS)) { - Log.e(TAG, "forwardGeocode(): no ReplyElement"); - return; - } - ProtoBuf replyElement = response.getProtoBuf(GLocReply.REPLY_ELEMENTS); - - int status2 = replyElement.getInt(GLocReplyElement.STATUS); - if (status2 != ResponseCodes.STATUS_STATUS_SUCCESS) { - Log.e(TAG, "forwardGeocode(): GLS failed with status " + status2); - return; - } - - if (!replyElement.has(GLocReplyElement.LOCATION)) { - Log.e(TAG, "forwardGeocode(): no location in ReplyElement"); - return; - } - - ProtoBuf location = replyElement.getProtoBuf(GLocReplyElement.LOCATION); - if (!location.has(GLocation.FEATURE)) { - Log.e(TAG, "forwardGeocode(): no feature in GLocation"); - return; - } - - getAddressFromProtoBuf(location, locale, addrs); - } - - /** - * Queues a location collection request to be sent to the server - * - * @param trigger what triggered this collection event - * @param location last known location - * @param cellState cell tower state - * @param scanResults list of wifi points - * @param scanTime real time at which wifi scan happened - * @param immediate true if request should be sent immediately instead of being queued - */ - public synchronized void queueCollectionReport(int trigger, Location location, - CellState cellState, List scanResults, long scanTime, boolean immediate) { - - // Create a RequestElement - ProtoBuf requestElement = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST_ELEMENT); - - // Include debug profile - ProtoBuf debugProfile = new ProtoBuf(GdebugprofileMessageTypes.GDEBUG_PROFILE); - requestElement.setProtoBuf(GLocRequestElement.DEBUG_PROFILE, debugProfile); - - if (mDeviceRestart) { - debugProfile.setBool(GDebugProfile.DEVICE_RESTART, true); - mDeviceRestart = false; - } - - if (trigger != -1) { - debugProfile.setInt(GDebugProfile.TRIGGER, trigger); - EventLog.writeEvent(COLLECTION_EVENT_LOG_TAG, trigger); - } - - // Include cell profile - if (cellState != null && cellState.isValid()) { - ProtoBuf cellularProfile = new ProtoBuf(GcellularMessageTypes.GCELLULAR_PROFILE); - cellularProfile.setLong(GCellularProfile.TIMESTAMP, cellState.getTime()); - - // Primary cell - ProtoBuf primaryCell = new ProtoBuf(GcellularMessageTypes.GCELL); - primaryCell.setInt(GCell.LAC, cellState.getLac()); - primaryCell.setInt(GCell.CELLID, cellState.getCid()); - if ((cellState.getMcc() != -1) && (cellState.getMnc() != -1)) { - primaryCell.setInt(GCell.MCC, cellState.getMcc()); - primaryCell.setInt(GCell.MNC, cellState.getMnc()); - } - - if (cellState.getSignalStrength() != -1) { - primaryCell.setInt(GCell.RSSI, cellState.getSignalStrength()); - } - - cellularProfile.setProtoBuf(GCellularProfile.PRIMARY_CELL, primaryCell); - - // Cell neighbors - addNeighborsToCellProfile(cellState, cellularProfile); - - requestElement.setProtoBuf(GLocRequestElement.CELLULAR_PROFILE, cellularProfile); - } - - // Include Wifi profile - if (scanResults != null && scanResults.size() > 0) { - ProtoBuf wifiProfile = new ProtoBuf(GwifiMessageTypes.GWIFI_PROFILE); - wifiProfile.setLong(GWifiProfile.TIMESTAMP, scanTime); - - int count = 0; - for (ScanResult s : scanResults) { - ProtoBuf wifiDevice = new ProtoBuf(GwifiMessageTypes.GWIFI_DEVICE); - wifiDevice.setString(GWifiDevice.MAC, s.BSSID); - wifiDevice.setString(GWifiDevice.SSID, s.SSID); - wifiDevice.setInt(GWifiDevice.RSSI, s.level); - wifiProfile.addProtoBuf(GWifiProfile.WIFI_DEVICES, wifiDevice); - count++; - if (count >= MAX_WIFI_TO_INCLUDE) { - break; - } - } - - requestElement.setProtoBuf(GLocRequestElement.WIFI_PROFILE, wifiProfile); - } - - // Location information - if (location != null) { - ProtoBuf latlngElement = new ProtoBuf(GlatlngMessageTypes.GLAT_LNG); - latlngElement.setInt(GLatLng.LAT_E7, (int)(location.getLatitude() * E7)); - latlngElement.setInt(GLatLng.LNG_E7, (int)(location.getLongitude() * E7)); - - ProtoBuf locationElement = new ProtoBuf(GlocationMessageTypes.GLOCATION); - locationElement.setProtoBuf(GLocation.LAT_LNG, latlngElement); - locationElement.setInt(GLocation.LOC_TYPE, GLocation.LOCTYPE_GPS); - locationElement.setLong(GLocation.TIMESTAMP, location.getTime()); - if (location.hasAccuracy()) { - locationElement.setInt(GLocation.ACCURACY, (int)location.getAccuracy()); - } - if (location.hasSpeed()) { - locationElement.setInt(GLocation.VELOCITY, (int)location.getSpeed()); - } - if (location.hasBearing()) { - locationElement.setInt(GLocation.HEADING, (int)location.getBearing()); - } - - requestElement.setProtoBuf(GLocRequestElement.LOCATION, locationElement); - } - - if (mCurrentCollectionRequest == null) { - mCurrentCollectionRequest = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST); - - // Create a Platform Profile - ProtoBuf platformProfile = createPlatformProfile(); - if (cellState != null && cellState.isValid()) { - ProtoBuf cellularPlatform = createCellularPlatformProfile(cellState); - platformProfile.setProtoBuf(GPlatformProfile.CELLULAR_PLATFORM_PROFILE, - cellularPlatform); - } - - mCurrentCollectionRequest.setProtoBuf(GLocRequest.PLATFORM_PROFILE, platformProfile); - - } else { - - ProtoBuf platformProfile = - mCurrentCollectionRequest.getProtoBuf(GLocRequest.PLATFORM_PROFILE); - if (platformProfile == null) { - platformProfile = createPlatformProfile(); - mCurrentCollectionRequest.setProtoBuf( - GLocRequest.PLATFORM_PROFILE, platformProfile); - } - - // Add cellular platform profile is not already included - if (platformProfile.getProtoBuf(GPlatformProfile.CELLULAR_PLATFORM_PROFILE) == null && - cellState != null && cellState.isValid()) { - ProtoBuf cellularPlatform = createCellularPlatformProfile(cellState); - platformProfile.setProtoBuf(GPlatformProfile.CELLULAR_PLATFORM_PROFILE, - cellularPlatform); - } - } - - mCurrentCollectionRequest.addProtoBuf(GLocRequest.REQUEST_ELEMENTS, requestElement); - - // Immediately upload collection events if buffer exceeds certain size - if (mCurrentCollectionRequest.getCount(GLocRequest.REQUEST_ELEMENTS) - >= MAX_COLLECTION_BUFFER_SIZE) { - immediate = true; - } - - if (immediate) { - // Request to send over wire - uploadCollectionReport(immediate); - } - } - - /** - * Uploads the collection report either immediately or based on MASF's queueing logic. - * Does not need a reply back - * - * @param immediate true if request should be sent immediately instead of being queued - */ - private synchronized void uploadCollectionReport(boolean immediate) { - // There may be nothing to upload - if (mCurrentCollectionRequest == null || - mCurrentCollectionRequest.getCount(GLocRequest.REQUEST_ELEMENTS) == 0) { - return; - } - - ByteArrayOutputStream payload = new ByteArrayOutputStream(); - try { - mCurrentCollectionRequest.outputTo(payload); - } catch (IOException e) { - Log.e(TAG, "uploadCollectionReport(): unable to write request to payload"); - return; - } - - mLastCollectionUploadTime = SystemClock.elapsedRealtime(); - - // Since this has already been written to the wire, we can clear this request - int count = mCurrentCollectionRequest.getCount(GLocRequest.REQUEST_ELEMENTS); - while (count > 0) { - mCurrentCollectionRequest.remove(GLocRequest.REQUEST_ELEMENTS, count - 1); - count--; - } - - // Creates request and a listener with a call back function - ProtoBuf reply = new ProtoBuf(LocserverMessageTypes.GLOC_REPLY); - Request plainRequest = - new PlainRequest(REQUEST_UPLOAD_LOC, (short)0, payload.toByteArray()); - - ProtoRequestListener listener = new ProtoRequestListener(reply, new ServiceCallback() { - public void onRequestComplete(Object result) { - ProtoBuf response = (ProtoBuf) result; - - if (response == null) { - Log.e(TAG, "uploadCollectionReport(): response is null"); - return; - } - - int status1 = response.getInt(GLocReply.STATUS); - if (status1 != ResponseCodes.STATUS_STATUS_SUCCESS) { - Log.w(TAG, "uploadCollectionReport(): RPC failed with status " + status1); - return; - } - - if (response.has(GLocReply.PLATFORM_KEY)) { - String platformKey = response.getString(GLocReply.PLATFORM_KEY); - if (!TextUtils.isEmpty(platformKey)) { - setPlatformKey(platformKey); - } - } - - if (!response.has(GLocReply.REPLY_ELEMENTS)) { - Log.w(TAG, "uploadCollectionReport(): no ReplyElement"); - return; - } - - int count = response.getCount(GLocReply.REPLY_ELEMENTS); - for (int i = 0; i < count; i++) { - ProtoBuf replyElement = response.getProtoBuf(GLocReply.REPLY_ELEMENTS, i); - int status2 = replyElement.getInt(GLocReplyElement.STATUS); - if (status2 != ResponseCodes.STATUS_STATUS_SUCCESS) { - Log.w(TAG, "uploadCollectionReport(): GLS failed with " + status2); - } - } - - } - }); - plainRequest.setListener(listener); - - // Send request - MobileServiceMux serviceMux = MobileServiceMux.getSingleton(); - serviceMux.submitRequest(plainRequest, immediate); - - } - - private String getPlatformKey() { - if (mPlatformKey != null) { - return mPlatformKey; - } - - try { - File file = new File(LocationManager.SYSTEM_DIR, PLATFORM_KEY_FILE); - FileInputStream istream = new FileInputStream(file); - DataInputStream dataInput = new DataInputStream(istream); - String platformKey = dataInput.readUTF(); - dataInput.close(); - mPlatformKey = platformKey; - return mPlatformKey; - } catch(FileNotFoundException e) { - // No file, just ignore - return null; - } catch(IOException e) { - // Unable to read from file, just ignore - return null; - } - } - - private void setPlatformKey(String platformKey) { - File systemDir = new File(LocationManager.SYSTEM_DIR); - if (!systemDir.exists()) { - if (!systemDir.mkdirs()) { - Log.w(TAG, "setPlatformKey(): couldn't create directory"); - return; - } - } - - try { - File file = new File(LocationManager.SYSTEM_DIR, PLATFORM_KEY_FILE); - FileOutputStream ostream = new FileOutputStream(file); - DataOutputStream dataOut = new DataOutputStream(ostream); - dataOut.writeUTF(platformKey); - dataOut.close(); - mPlatformKey = platformKey; - } catch (FileNotFoundException e) { - Log.w(TAG, "setPlatformKey(): unable to create platform key file"); - } catch (IOException e) { - Log.w(TAG, "setPlatformKey(): unable to write to platform key"); - } - } - - private ProtoBuf createPlatformProfile() { - Locale locale = Locale.getDefault(); - return createPlatformProfile(locale); - } - - private ProtoBuf createPlatformProfile(Locale locale) { - if (mPlatformProfile == null) { - mPlatformProfile = new ProtoBuf(GlocationMessageTypes.GPLATFORM_PROFILE); - mPlatformProfile.setString(GPlatformProfile.VERSION, APPLICATION_VERSION); - mPlatformProfile.setString(GPlatformProfile.PLATFORM, PLATFORM_BUILD); - } - - // Add Locale - if ((locale != null) && (locale.toString() != null)) { - mPlatformProfile.setString(GPlatformProfile.LOCALE, locale.toString()); - } - - // Add Platform Key - String platformKey = getPlatformKey(); - if (!TextUtils.isEmpty(platformKey)) { - mPlatformProfile.setString(GPlatformProfile.PLATFORM_KEY, platformKey); - } - - // Clear out cellular platform profile - mPlatformProfile.setProtoBuf(GPlatformProfile.CELLULAR_PLATFORM_PROFILE, null); - - return mPlatformProfile; - } - - private ProtoBuf createCellularPlatformProfile(CellState cellState) { - // Radio type - int radioType = -1; - if (cellState.getRadioType() == CellState.RADIO_TYPE_GPRS) { - radioType = GCellularPlatformProfile.RADIO_TYPE_GPRS; - } else if (cellState.getRadioType() == CellState.RADIO_TYPE_CDMA) { - radioType = GCellularPlatformProfile.RADIO_TYPE_CDMA; - } else if (cellState.getRadioType() == CellState.RADIO_TYPE_WCDMA) { - radioType = GCellularPlatformProfile.RADIO_TYPE_WCDMA; - } - - if (mCellularPlatformProfile == null) { - mCellularPlatformProfile = - new ProtoBuf(GlocationMessageTypes.GCELLULAR_PLATFORM_PROFILE); - } - - mCellularPlatformProfile.setInt(GCellularPlatformProfile.RADIO_TYPE, radioType); - if ((cellState.getHomeMcc() != -1) && (cellState.getHomeMnc() != -1)) { - mCellularPlatformProfile.setInt(GCellularPlatformProfile.HOME_MCC, - cellState.getHomeMcc()); - mCellularPlatformProfile.setInt(GCellularPlatformProfile.HOME_MNC, - cellState.getHomeMnc()); - } - if (cellState.getCarrier() != null) { - mCellularPlatformProfile.setString(GCellularPlatformProfile.CARRIER, - cellState.getCarrier()); - } - - return mCellularPlatformProfile; - } - - private void getAddressFromProtoBuf(ProtoBuf location, Locale locale, List
                addrs) { - - double lat = -1; - double lng = -1; - - if (location.has(GLocation.LAT_LNG)) { - ProtoBuf latlng = location.getProtoBuf(GLocation.LAT_LNG); - lat = latlng.getInt(GLatLng.LAT_E7)/E7; - lng = latlng.getInt(GLatLng.LNG_E7)/E7; - } - - for (int a = 0; a < location.getCount(GLocation.FEATURE); a++) { - - Address output = new Address(locale); - - ProtoBuf feature = location.getProtoBuf(GLocation.FEATURE, a); - output.setFeatureName(feature.getString(GFeature.NAME)); - - if (feature.has(GFeature.CENTER)) { - ProtoBuf center = feature.getProtoBuf(GFeature.CENTER); - output.setLatitude(center.getInt(GLatLng.LAT_E7)/E7); - output.setLongitude(center.getInt(GLatLng.LNG_E7)/E7); - - } else if (location.has(GLocation.LAT_LNG)) { - output.setLatitude(lat); - output.setLongitude(lng); - } - - ProtoBuf address = feature.getProtoBuf(GFeature.ADDRESS); - - for (int i = 0; i < address.getCount(GAddress.FORMATTED_ADDRESS_LINE); i++) { - String line = address.getString(GAddress.FORMATTED_ADDRESS_LINE, i); - output.setAddressLine(i, line); - } - - for (int i = 0; i < address.getCount(GAddress.COMPONENT); i++) { - ProtoBuf component = address.getProtoBuf(GAddress.COMPONENT, i); - int type = component.getInt(GAddressComponent.FEATURE_TYPE); - String name = component.getString(GAddressComponent.NAME); - - switch(type) { - case GFeature.FEATURE_TYPE_ADMINISTRATIVE_AREA : - output.setAdminArea(name); - break; - - case GFeature.FEATURE_TYPE_SUB_ADMINISTRATIVE_AREA : - output.setSubAdminArea(name); - break; - - case GFeature.FEATURE_TYPE_LOCALITY : - output.setLocality(name); - break; - - case GFeature.FEATURE_TYPE_THOROUGHFARE : - output.setThoroughfare(name); - break; - - case GFeature.FEATURE_TYPE_POST_CODE : - output.setPostalCode(name); - break; - - case GFeature.FEATURE_TYPE_COUNTRY : - output.setCountryName(name); - break; - - case GFeature.FEATURE_TYPE_COUNTRY_CODE : - output.setCountryCode(name); - break; - - default : - if (android.util.Config.LOGD) { - Log.d(TAG, "getAddressFromProtoBuf(): Ignore feature " + type + "," + name); - } - break; - } - } - - addrs.add(output); - } - } - - private void addNeighborsToCellProfile(CellState cellState, ProtoBuf cellularProfile) { - List neighbors = cellState.getNeighbors(); - - int mPrimaryMcc = cellState.getMcc(); - int mPrimaryMnc = cellState.getMnc(); - - if (neighbors != null) { - for (CellState.NeighborCell neighbor : neighbors) { - ProtoBuf nCell = new ProtoBuf(GcellularMessageTypes.GCELL); - nCell.setInt(GCell.CELLID, neighbor.getCid()); - nCell.setInt(GCell.LAC, neighbor.getLac()); - nCell.setInt(GCell.RSSI, neighbor.getRssi()); - if (neighbor.getPsc() != -1) { - nCell.setInt(GCell.PRIMARY_SCRAMBLING_CODE, neighbor.getPsc()); - } - if (mPrimaryMcc != -1) { - nCell.setInt(GCell.MCC, mPrimaryMcc); - } - if (mPrimaryMnc != -1) { - nCell.setInt(GCell.MNC, mPrimaryMnc); - } - cellularProfile.addProtoBuf(GCellularProfile.NEIGHBORS, nCell); - } - } - } - -} diff --git a/location/java/com/android/internal/location/NetworkLocationProvider.java b/location/java/com/android/internal/location/NetworkLocationProvider.java deleted file mode 100644 index d0a59b943d60aefc778bbbd240ee5fb08cc984f6..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/NetworkLocationProvider.java +++ /dev/null @@ -1,561 +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. - */ - -package com.android.internal.location; - -import com.android.internal.location.protocol.GDebugProfile; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -import android.content.Context; -import android.location.Criteria; -import android.location.Location; -import android.location.LocationManager; -import android.location.LocationProviderImpl; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiManager; -import android.os.Bundle; -import android.os.SystemClock; -import android.os.SystemProperties; -import android.util.Log; - -/** - * A location provider which gets approximate location from Google's - * database of cell-tower and wi-fi locations. - * - *

                It is the responsibility of the LocationManagerService to - * notify this class of any changes in the radio information - * by calling {@link #updateCellState} and of data state - * changes by calling {@link #updateNetworkState} - * - *

                The LocationManagerService must also notify the provider - * of Wifi updates using the {@link #updateWifiScanResults} - * and {@link #updateWifiEnabledState} - * methods. - * - *

                The provider uses whichever radio is available - Cell - * or WiFi. If neither is available, it does NOT attempt to - * switch them on. - * - * {@hide} - */ -public class NetworkLocationProvider extends LocationProviderImpl { - private static final String TAG = "NetworkLocationProvider"; - - // Wait at least 60 seconds between network queries - private static final int MIN_NETWORK_RETRY_MILLIS = 60000; - - // Max time to wait for radio update - private static final long MAX_TIME_TO_WAIT_FOR_RADIO = 5 * 1000; // 5 seconds - - // State of entire provider - private int mStatus = AVAILABLE; - private long mStatusUpdateTime = 0; - - // Network state - private int mNetworkState = TEMPORARILY_UNAVAILABLE; - - // Cell state - private static final int MAX_CELL_HISTORY_TO_KEEP = 4; - private LinkedList mCellHistory = new LinkedList(); - private CellState mCellState = null; - private long mLastCellStateChangeTime = 0; - private long mLastCellLockTime = 0; - - // Wifi state - private static final long MIN_TIME_BETWEEN_WIFI_REPORTS = 45 * 1000; // 45 seconds - private List mWifiLastScanResults = null; - private long mLastWifiScanTriggerTime = 0; - private long mLastWifiScanElapsedTime = 0; - private long mLastWifiScanRealTime = 0; - private long mWifiScanFrequency = MIN_TIME_BETWEEN_WIFI_REPORTS; - private boolean mWifiEnabled = false; - - // Last known location state - private Location mLocation = new Location(LocationManager.NETWORK_PROVIDER); - private long mLastNetworkQueryTime = 0; // Last network request, successful or not - private long mLastSuccessfulNetworkQueryTime = 0; // Last successful network query time - - // Is provider enabled by user -- ignored by this class - private boolean mEnabled; - - // Is provider being used by an application - private HashSet mApplications = new HashSet(); - private boolean mTracking = false; - - // Location masf service - private LocationMasfClient mMasfClient; - - // Context of location manager service - private Context mContext; - - public static boolean isSupported() { - // This class provides a Google-specific location feature, so it's enabled only - // when the system property ro.com.google.locationfeatures is set. - if (!SystemProperties.get("ro.com.google.locationfeatures").equals("1")) { - return false; - } - - // Otherwise, assume cell location should work if we are not running in the emulator - return !SystemProperties.get("ro.kernel.qemu").equals("1"); - } - - public NetworkLocationProvider(Context context, LocationMasfClient masfClient) { - super(LocationManager.NETWORK_PROVIDER); - mContext = context; - mMasfClient = masfClient; - } - - @Override - public void updateNetworkState(int state) { - if (state == mNetworkState) { - return; - } - log("updateNetworkState(): Updating network state to " + state); - mNetworkState = state; - - updateStatus(mNetworkState); - } - - @Override - public void updateCellState(CellState newState) { - if (newState == null) { - log("updateCellState(): Cell state is invalid"); - return; - } - - if (mCellState != null && mCellState.equals(newState)) { - log("updateCellState(): Cell state is the same"); - return; - } - - // Add previous state to history - if ((mCellState != null) && mCellState.isValid()) { - if (mCellHistory.size() >= MAX_CELL_HISTORY_TO_KEEP) { - mCellHistory.remove(0); - } - mCellHistory.add(mCellState); - } - - mCellState = newState; - log("updateCellState(): Received"); - - mLastCellLockTime = 0; - mLastCellStateChangeTime = SystemClock.elapsedRealtime(); - } - - public void updateCellLockStatus(boolean acquired) { - if (acquired) { - mLastCellLockTime = SystemClock.elapsedRealtime(); - } else { - mLastCellLockTime = 0; - } - } - - @Override - public boolean requiresNetwork() { - return true; - } - - @Override - public boolean requiresSatellite() { - return false; - } - - @Override - public boolean requiresCell() { - return true; - } - - @Override - public boolean hasMonetaryCost() { - return true; - } - - @Override - public boolean supportsAltitude() { - return false; - } - - @Override - public boolean supportsSpeed() { - return false; - } - - @Override - public boolean supportsBearing() { - return false; - } - - @Override - public int getPowerRequirement() { - return Criteria.POWER_LOW; - } - - @Override - public void enable() { - // Nothing else needs to be done - mEnabled = true; - } - - @Override - public void disable() { - // Nothing else needs to be done - mEnabled = false; - } - - @Override - public boolean isEnabled() { - return mEnabled; - } - - @Override - public int getAccuracy() { - return Criteria.ACCURACY_COARSE; - } - - @Override - public int getStatus(Bundle extras) { - return mStatus; - } - - @Override - public long getStatusUpdateTime() { - return mStatusUpdateTime; - } - - @Override - public void setMinTime(long minTime) { - if (minTime < MIN_TIME_BETWEEN_WIFI_REPORTS) { - mWifiScanFrequency = MIN_TIME_BETWEEN_WIFI_REPORTS; - } else { - mWifiScanFrequency = minTime; - } - super.setMinTime(minTime); - } - - @Override - public boolean getLocation(Location l) { - - long now = SystemClock.elapsedRealtime(); - - // Trigger a wifi scan and wait for its results if necessary - if ((mWifiEnabled) && - (mWifiLastScanResults == null || - ((now - mLastWifiScanElapsedTime) > mWifiScanFrequency))) { - - boolean fallback = false; - - // If scan has been recently triggered - if (mLastWifiScanTriggerTime != 0 && - ((now - mLastWifiScanTriggerTime) < mWifiScanFrequency)) { - if ((now - mLastWifiScanTriggerTime) > MAX_TIME_TO_WAIT_FOR_RADIO) { - // If no results from last trigger available, use cell results - // This will also trigger a new scan - log("getLocation(): falling back to cell"); - fallback = true; - } else { - // Just wait for the Wifi results to be available - return false; - } - } - - WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); - log("getLocation(): triggering a wifi scan"); - mLastWifiScanTriggerTime = now; - boolean succeeded = wifiManager.startScan(); - if (!succeeded) { - log("getLocation(): wifi scan did not succeed"); - // Wifi trigger failed, use cell results - fallback = true; - } - - // Wait for scan results - if (!fallback) { - return false; - } - } - - // If waiting for cell location - if (mLastCellLockTime != 0 && ((now - mLastCellLockTime) < MAX_TIME_TO_WAIT_FOR_RADIO)) { - return false; - } - - // Update Location - // 1) If there has been a cell state change - // 2) If there was no successful reply for last network request - if (mLastCellStateChangeTime > mLastNetworkQueryTime) { - updateLocation(); - return false; - - } else if ((mLastNetworkQueryTime != 0) - && (mLastNetworkQueryTime > mLastSuccessfulNetworkQueryTime) - && ((now - mLastNetworkQueryTime) > MIN_NETWORK_RETRY_MILLIS)) { - updateLocation(); - return false; - } - - if (mLocation != null && mLocation.getAccuracy() > 0) { - - // We could have a Cell Id location which hasn't changed in a - // while because we haven't switched towers so if the last location - // time + mWifiScanFrequency is less than current time update the - // locations time. - long currentTime = System.currentTimeMillis(); - if ((mLocation.getTime() + mWifiScanFrequency) < currentTime) { - mLocation.setTime(currentTime); - } - l.set(mLocation); - return true; - } else { - return false; - } - } - - @Override - public void enableLocationTracking(boolean enable) { - if (enable == mTracking) { - return; - } - - log("enableLocationTracking(): " + enable); - mTracking = enable; - - if (!enable) { - // When disabling the location provider, be sure to clear out old location - clearLocation(); - } else { - // When enabling provider, force location - forceLocation(); - } - } - - @Override - public boolean isLocationTracking() { - return mTracking; - } - - /** - * Notifies the provider that there are scan results available. - * - * @param scanResults list of wifi scan results - */ - public void updateWifiScanResults(List scanResults) { - if (!mTracking) { - return; - } - - long now = SystemClock.elapsedRealtime(); - - if (scanResults == null) { - mWifiLastScanResults = null; - mLastWifiScanElapsedTime = now; - mLastWifiScanRealTime = System.currentTimeMillis(); - - log("updateWifIScanResults(): NULL APs"); - - // Force cell location since no wifi results available - if (mWifiEnabled) { - mLastCellLockTime = 0; - mLastCellStateChangeTime = SystemClock.elapsedRealtime(); - } - - } else if ((mWifiLastScanResults == null) - || (mWifiLastScanResults.size() <= 2 && scanResults.size() > mWifiLastScanResults.size()) - || ((now - mLastWifiScanElapsedTime) > mWifiScanFrequency)) { - - if (mWifiLastScanResults == null) { - mWifiLastScanResults = new ArrayList(); - } else { - mWifiLastScanResults.clear(); - } - mWifiLastScanResults.addAll(scanResults); - mLastWifiScanElapsedTime = now; - mLastWifiScanRealTime = System.currentTimeMillis(); - - log("updateWifIScanResults(): " + mWifiLastScanResults.size() + " APs"); - updateLocation(); - - } - } - - /** - * Notifies the provider if Wifi has been enabled or disabled - * by the user - * - * @param enabled true if wifi is enabled; false otherwise - */ - public void updateWifiEnabledState(boolean enabled) { - mWifiEnabled = enabled; - - log("updateWifiEnabledState(): " + enabled); - - // Force location update - forceLocation(); - } - - public void addListener(String[] applications) { - if (applications != null) { - for (String app : applications) { - String a = app.replaceAll("com.google.android.", ""); - a = a.replaceAll("com.android.", ""); - mApplications.add(a); - log("addListener(): " + a); - } - } - } - - public void removeListener(String[] applications) { - if (applications != null) { - for (String app : applications) { - String a = app.replaceAll("com.google.android.", ""); - a = a.replaceAll("com.android.", ""); - mApplications.remove(a); - log("removeListener(): " + a); - } - } - } - - private void clearLocation() { - mLocation.setAccuracy(-1); - updateStatus(TEMPORARILY_UNAVAILABLE); - } - - private void forceLocation() { - if (mWifiEnabled) { - // Force another wifi scan - mWifiLastScanResults = null; - mLastWifiScanTriggerTime = 0; - mLastWifiScanElapsedTime = 0; - mLastWifiScanRealTime = 0; - } else { - // Force another cell location request - mLastCellLockTime = 0; - mLastCellStateChangeTime = SystemClock.elapsedRealtime(); - } - } - - private void updateStatus(int status) { - if (status != mStatus) { - mStatus = status; - mStatusUpdateTime = SystemClock.elapsedRealtime(); - } - } - - /** - * Gets location from the server is applications are tracking this provider - * - */ - private void updateLocation() { - - // If not being tracked, no need to do anything. - if (!mTracking) { - return; - } - - // If network is not available, can't do anything - if (mNetworkState != AVAILABLE) { - return; - } - - final long now = SystemClock.elapsedRealtime(); - - // There is a pending network request - if ((mLastNetworkQueryTime != 0) && - (mLastNetworkQueryTime > mLastSuccessfulNetworkQueryTime) && - ((now - mLastNetworkQueryTime) <= MIN_NETWORK_RETRY_MILLIS)) { - return; - } - - // Don't include wifi points if they're too old - List scanResults = null; - if (mWifiEnabled && (mWifiLastScanResults != null && - ((now - mLastWifiScanElapsedTime) < (mWifiScanFrequency + MAX_TIME_TO_WAIT_FOR_RADIO)))) { - scanResults = mWifiLastScanResults; - } - - // If no valid cell information available - boolean noCell = mCellState == null || !mCellState.isValid(); - - // If no valid wifi information available - boolean noWifi = scanResults == null || (scanResults.size() == 0); - - // If no cell-id or wi-fi update, just return invalid location - if (noCell && noWifi) { - clearLocation(); - return; - } - - // What kind of a network location request was it - int trigger; - if (!mWifiEnabled) { - if (!noCell) { - trigger = GDebugProfile.TRIGGER_CELL_AND_WIFI_CHANGE; - } else { - trigger = GDebugProfile.TRIGGER_WIFI_CHANGE; - } - } else { - trigger = GDebugProfile.TRIGGER_CELL_CHANGE; - } - - try { - mLastNetworkQueryTime = now; - mMasfClient.getNetworkLocation(mApplications, trigger, mCellState, mCellHistory, - scanResults, mLastWifiScanRealTime, new Callback() { - public void locationReceived(Location location, boolean networkSuccessful) { - // If location is valid and not the same as previously known location - if ((location != null) && (location.getAccuracy() > 0) && - (location.getTime() != mLocation.getTime())) { - mLocation.set(location); - updateStatus(AVAILABLE); - } else { - // Location is unavailable - clearLocation(); - } - - // Even if no location is available, network request could have succeeded - if (networkSuccessful) { - mLastSuccessfulNetworkQueryTime = SystemClock.elapsedRealtime(); - } - - } - }); - } catch(Exception e) { - Log.e(TAG, "updateLocation got exception:", e); - } - } - - public interface Callback { - - /** - * Callback function to notify of a received network location - * - * @param location location object that is received. may be null if not a valid location - * @param successful true if network query was successful, even if no location was found - */ - void locationReceived(Location location, boolean successful); - } - - private void log(String log) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, log); - } - } - -} diff --git a/location/java/com/android/internal/location/ProtoRequestListener.java b/location/java/com/android/internal/location/ProtoRequestListener.java deleted file mode 100644 index d73cd057a0c97cd616cf0df1ae4e761f0101d84f..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/ProtoRequestListener.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2007 The Android Open Source Project - -package com.android.internal.location; - -import com.google.common.io.GoogleHttpConnection; -import com.google.common.io.protocol.ProtoBuf; -import com.google.masf.ServiceCallback; -import com.google.masf.protocol.Request; -import com.google.masf.protocol.Response; -import com.google.masf.services.AsyncResult; - -import java.io.IOException; -import java.io.InputStream; - -import android.util.Log; - -/** - * Listener for protocol buffer requests - * - * {@hide} - */ - -public class ProtoRequestListener implements Request.Listener { - private final static String TAG = "ProtoRequestListener"; - private AsyncResult result; - private ProtoBuf protoResponse; - - /** - * @return the asynchronous result object - */ - public AsyncResult getAsyncResult() { - return result; - } - - /** - * Constructor for a ProtoRequestListener - * - * @param protoResponse ProtoBuf with correct type to fill response with - * @param callback function to call after completed request (may be null) - */ - public ProtoRequestListener(ProtoBuf protoResponse, ServiceCallback callback) { - this.result = new AsyncResult(callback); - this.protoResponse = protoResponse; - } - - public boolean requestComplete(Request request, Response response) - throws IOException { - InputStream is = response.getInputStream(); - if (response.getStatusCode() == GoogleHttpConnection.HTTP_OK) { - protoResponse.parse(is); - result.setResult(protoResponse); - } else { - result.setResult(null); - } - return true; - } - - public void requestException(Request request, Exception exception) { - Log.e(TAG, "requestException()", exception); - } -} diff --git a/location/java/com/android/internal/location/protocol/GAddressComponent.java b/location/java/com/android/internal/location/protocol/GAddressComponent.java deleted file mode 100644 index a06a23dd3252286b3b1c7ec36c7a6bfec790367f..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GAddressComponent.java +++ /dev/null @@ -1,23 +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. - */ - -package com.android.internal.location.protocol; - -public interface GAddressComponent { - static final int NAME = 1; - static final int FEATURE_TYPE = 2; -} - diff --git a/location/java/com/android/internal/location/protocol/GAppProfile.java b/location/java/com/android/internal/location/protocol/GAppProfile.java deleted file mode 100644 index e3332eb4377f1e0b5fe06eda5e4ad2aa945a2bb1..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GAppProfile.java +++ /dev/null @@ -1,26 +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. - */ - -package com.android.internal.location.protocol; - -public interface GAppProfile { - static final int APP_NAME = 1; - static final int APP_KEY = 2; - static final int REQUEST_TYPE = 3; - static final int SEARCH_TYPE = 4; - static final int SEARCH_TERM = 5; -} - diff --git a/location/java/com/android/internal/location/protocol/GCell.java b/location/java/com/android/internal/location/protocol/GCell.java deleted file mode 100644 index 21d1c48e78284632b3c635a9619ca2aa534cbf72..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GCell.java +++ /dev/null @@ -1,29 +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. - */ - -package com.android.internal.location.protocol; - -public interface GCell { - static final int LAC = 1; - static final int CELLID = 2; - static final int MNC = 3; - static final int MCC = 4; - static final int RSSI = 5; - static final int AGE = 6; - static final int TIMING_ADVANCE = 7; - static final int PRIMARY_SCRAMBLING_CODE = 8; -} - diff --git a/location/java/com/android/internal/location/protocol/GCellularPlatformProfile.java b/location/java/com/android/internal/location/protocol/GCellularPlatformProfile.java deleted file mode 100644 index a17da20ff1936042b639c8ce77b517b6c1449863..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GCellularPlatformProfile.java +++ /dev/null @@ -1,30 +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. - */ - -package com.android.internal.location.protocol; - -public interface GCellularPlatformProfile { - static final int RADIO_TYPE_GPRS = 3; - static final int RADIO_TYPE_CDMA = 4; - static final int RADIO_TYPE_WCDMA = 5; - - static final int RADIO_TYPE = 1; - static final int CARRIER = 2; - static final int IP = 3; - static final int HOME_MNC = 4; - static final int HOME_MCC = 5; -} - diff --git a/location/java/com/android/internal/location/protocol/GCellularProfile.java b/location/java/com/android/internal/location/protocol/GCellularProfile.java deleted file mode 100644 index 8c85bf7bc1d185691878305eac3795b8fd55738b..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GCellularProfile.java +++ /dev/null @@ -1,26 +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. - */ - -package com.android.internal.location.protocol; - -public interface GCellularProfile { - static final int PRIMARY_CELL = 1; - static final int TIMESTAMP = 2; - static final int NEIGHBORS = 3; - static final int HISTORICAL_CELLS = 4; - static final int PREFETCH_MODE = 5; -} - diff --git a/location/java/com/android/internal/location/protocol/GDebugProfile.java b/location/java/com/android/internal/location/protocol/GDebugProfile.java deleted file mode 100644 index b96438722c244249a396740a83e5f8e76154fc31..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GDebugProfile.java +++ /dev/null @@ -1,37 +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. - */ - -package com.android.internal.location.protocol; - -public interface GDebugProfile { - static final int TRIGGER_CELL_CHANGE = 1; - static final int TRIGGER_WIFI_CHANGE = 2; - static final int TRIGGER_CELL_AND_WIFI_CHANGE = 3; - static final int TRIGGER_GPS_CHANGE = 4; - static final int TRIGGER_OTHER = 5; - static final int TRIGGER_COLLECTION_START_BURST = 6; - static final int TRIGGER_COLLECTION_RESTART_BURST = 7; - static final int TRIGGER_COLLECTION_CONTINUE_BURST = 8; - static final int TRIGGER_COLLECTION_END_BURST = 9; - static final int TRIGGER_COLLECTION_END_BURST_AT_SAME_LOCATION = 10; - static final int TRIGGER_COLLECTION_MOVED_DISTANCE = 11; - - static final int TRIGGER = 1; - static final int ACTUAL_REQUEST = 2; - static final int CACHE_LOCATION = 3; - static final int DEVICE_RESTART = 4; -} - diff --git a/location/java/com/android/internal/location/protocol/GDeviceLocation.java b/location/java/com/android/internal/location/protocol/GDeviceLocation.java deleted file mode 100644 index 462ab073dbb874b0150ff0cb4b6f0a0c8baa4404..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GDeviceLocation.java +++ /dev/null @@ -1,24 +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. - */ - -package com.android.internal.location.protocol; - -public interface GDeviceLocation { - static final int LOCATION = 1; - static final int CELL = 2; - static final int WIFI_DEVICE = 3; -} - diff --git a/location/java/com/android/internal/location/protocol/GFeature.java b/location/java/com/android/internal/location/protocol/GFeature.java deleted file mode 100644 index 73fc1b347eb2054bfb5c73b23c8541076a084ae6..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GFeature.java +++ /dev/null @@ -1,38 +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. - */ - -package com.android.internal.location.protocol; - -public interface GFeature { - static final int NAME = 1; - static final int FEATURE_TYPE = 2; - static final int ADDRESS = 3; - static final int BOUNDS = 4; - static final int CENTER = 5; - - static final int FEATURE_TYPE_UNKNOWN_TYPE = 0; - static final int FEATURE_TYPE_COUNTRY = 1; - static final int FEATURE_TYPE_COUNTRY_CODE = 2; - static final int FEATURE_TYPE_ADMINISTRATIVE_AREA = 3; - static final int FEATURE_TYPE_SUB_ADMINISTRATIVE_AREA = 4; - static final int FEATURE_TYPE_LOCALITY = 5; - static final int FEATURE_TYPE_SUB_LOCALITY = 6; - static final int FEATURE_TYPE_PREMISES = 7; - static final int FEATURE_TYPE_THOROUGHFARE = 8; - static final int FEATURE_TYPE_SUB_THOROUGHFARE = 9; - static final int FEATURE_TYPE_POST_CODE = 10; -} - diff --git a/location/java/com/android/internal/location/protocol/GGeocodeRequest.java b/location/java/com/android/internal/location/protocol/GGeocodeRequest.java deleted file mode 100644 index 4d56cc0e1b16fd2311796ea6989d4ddf375c8826..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GGeocodeRequest.java +++ /dev/null @@ -1,24 +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. - */ - -package com.android.internal.location.protocol; - -public interface GGeocodeRequest { - static final int NUM_FEATURE_LIMIT = 1; - static final int INCLUDE_BOUNDING_BOXES = 2; - static final int BOUNDING_BOX = 3; -} - diff --git a/location/java/com/android/internal/location/protocol/GGpsProfile.java b/location/java/com/android/internal/location/protocol/GGpsProfile.java deleted file mode 100644 index be69eb021d66ca718c1e20a2634dfbfd904a048f..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GGpsProfile.java +++ /dev/null @@ -1,29 +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. - */ - -package com.android.internal.location.protocol; - -public interface GGpsProfile { - static final int FIX_QUALITY_INVALID = 0; - static final int FIX_QUALITY_GPS_FIX = 1; - static final int FIX_QUALITY_DGPS_FIX = 2; - - static final int GPS_FIX_TYPE = 1; - static final int PDOP = 2; - static final int HDOP = 3; - static final int VDOP = 4; -} - diff --git a/location/java/com/android/internal/location/protocol/GLocReply.java b/location/java/com/android/internal/location/protocol/GLocReply.java deleted file mode 100644 index 7a0504fcb39f5ae47453eb303448a77c260049d8..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GLocReply.java +++ /dev/null @@ -1,24 +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. - */ - -package com.android.internal.location.protocol; - -public interface GLocReply { - static final int STATUS = 1; - static final int REPLY_ELEMENTS = 2; - static final int PLATFORM_KEY = 3; -} - diff --git a/location/java/com/android/internal/location/protocol/GLocReplyElement.java b/location/java/com/android/internal/location/protocol/GLocReplyElement.java deleted file mode 100644 index bc47fcfd45ae969d98dc1217719fa70771732698..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GLocReplyElement.java +++ /dev/null @@ -1,24 +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. - */ - -package com.android.internal.location.protocol; - -public interface GLocReplyElement { - static final int STATUS = 1; - static final int LOCATION = 2; - static final int DEVICE_LOCATION = 3; -} - diff --git a/location/java/com/android/internal/location/protocol/GLocRequest.java b/location/java/com/android/internal/location/protocol/GLocRequest.java deleted file mode 100644 index 7761c11413c7cbe4d47ea67fdd517b3b37dee78e..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GLocRequest.java +++ /dev/null @@ -1,26 +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. - */ - -package com.android.internal.location.protocol; - -public interface GLocRequest { - static final int PLATFORM_PROFILE = 1; - static final int APP_PROFILES = 2; - static final int USER_PROFILE = 3; - static final int REQUEST_ELEMENTS = 4; - static final int MASF_CLIENT_INFO = 257; -} - diff --git a/location/java/com/android/internal/location/protocol/GLocRequestElement.java b/location/java/com/android/internal/location/protocol/GLocRequestElement.java deleted file mode 100644 index d758953df6e64e1642fae90839d582d2c53a5381..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GLocRequestElement.java +++ /dev/null @@ -1,26 +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. - */ - -package com.android.internal.location.protocol; - -public interface GLocRequestElement { - static final int CELLULAR_PROFILE = 1; - static final int WIFI_PROFILE = 2; - static final int LOCATION = 3; - static final int GEOCODE = 4; - static final int DEBUG_PROFILE = 99; -} - diff --git a/location/java/com/android/internal/location/protocol/GLocation.java b/location/java/com/android/internal/location/protocol/GLocation.java deleted file mode 100644 index 9a1eb1f151aea5e73760bb4e22dfd24924872001..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GLocation.java +++ /dev/null @@ -1,41 +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. - */ - -package com.android.internal.location.protocol; - -public interface GLocation { - static final int LOCTYPE_GPS = 0; - static final int LOCTYPE_MAPCENTER = 1; - static final int LOCTYPE_CENTROID = 2; - static final int LOCTYPE_TOWER_LOCATION = 3; - - static final int LAT_LNG = 1; - static final int SOURCE = 2; - static final int ACCURACY = 3; - static final int CONFIDENCE = 4; - static final int FEATURE = 5; - static final int TIMESTAMP = 6; - static final int OBSOLETE = 7; - static final int LOC_TYPE = 8; - static final int MISC = 9; - static final int ALTITUDE = 10; - static final int VERTICAL_ACCURACY = 11; - static final int VELOCITY = 12; - static final int HEADING = 13; - static final int GPS_PROFILE = 14; - static final int LOCATION_STRING = 15; -} - diff --git a/location/java/com/android/internal/location/protocol/GPlatformProfile.java b/location/java/com/android/internal/location/protocol/GPlatformProfile.java deleted file mode 100644 index 32a1f8ffdcb73accbd9ac27333f1858e0d625c02..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GPlatformProfile.java +++ /dev/null @@ -1,28 +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. - */ - -package com.android.internal.location.protocol; - -public interface GPlatformProfile { - static final int VERSION = 1; - static final int PLATFORM = 2; - static final int PLATFORM_KEY = 3; - static final int DISTRIBUTION_CHANNEL = 4; - static final int LOCALE = 5; - static final int CELLULAR_PLATFORM_PROFILE = 6; - static final int WIFI_PLATFORM_PROFILE = 7; -} - diff --git a/location/java/com/android/internal/location/protocol/GPrefetchMode.java b/location/java/com/android/internal/location/protocol/GPrefetchMode.java deleted file mode 100644 index 041b68610df25a3586bc31de23cce99ff5c733f6..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GPrefetchMode.java +++ /dev/null @@ -1,25 +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. - */ - -package com.android.internal.location.protocol; - -public interface GPrefetchMode { - static final int PREFETCH_MODE_NO_PREFETCH = 0; - static final int PREFETCH_MODE_REQUESTED_NEIGHBORS_ONLY = 1; - static final int PREFETCH_MODE_MORE_NEIGHBORS = 2; - -} - diff --git a/location/java/com/android/internal/location/protocol/GRectangle.java b/location/java/com/android/internal/location/protocol/GRectangle.java deleted file mode 100644 index b8412e65e7cfbe45d5dd688280e1aca7d14d991d..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GRectangle.java +++ /dev/null @@ -1,23 +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. - */ - -package com.android.internal.location.protocol; - -public interface GRectangle { - static final int LOWER_LEFT = 1; - static final int UPPER_RIGHT = 2; -} - diff --git a/location/java/com/android/internal/location/protocol/GUserProfile.java b/location/java/com/android/internal/location/protocol/GUserProfile.java deleted file mode 100644 index 2ce962c6a553fb68992c80b73166e071b887b86d..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GUserProfile.java +++ /dev/null @@ -1,23 +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. - */ - -package com.android.internal.location.protocol; - -public interface GUserProfile { - static final int USER_NAME = 1; - static final int AUTH_TOKEN = 2; -} - diff --git a/location/java/com/android/internal/location/protocol/GWifiDevice.java b/location/java/com/android/internal/location/protocol/GWifiDevice.java deleted file mode 100644 index 62bd03a6b8066d54d418aa4dcefdd27115976800..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GWifiDevice.java +++ /dev/null @@ -1,26 +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. - */ - -package com.android.internal.location.protocol; - -public interface GWifiDevice { - static final int MAC = 1; - static final int SSID = 2; - static final int CHANNEL = 3; - static final int RSSI = 4; - static final int NOISE = 5; -} - diff --git a/location/java/com/android/internal/location/protocol/GWifiPlatformProfile.java b/location/java/com/android/internal/location/protocol/GWifiPlatformProfile.java deleted file mode 100644 index 7f1efcbf9c582afab5074d8ab3cfd837041d3796..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GWifiPlatformProfile.java +++ /dev/null @@ -1,29 +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. - */ - -package com.android.internal.location.protocol; - -public interface GWifiPlatformProfile { - static final int RADIO_TYPE_WIFI802_11_A = 1; - static final int RADIO_TYPE_WIFI802_11_B = 2; - static final int RADIO_TYPE_WIFI802_11_G = 3; - static final int RADIO_TYPE_WIFI802_11_N = 4; - - static final int SCANNER_MAC = 1; - static final int SCANNER_IP = 2; - static final int RADIO_TYPE = 3; -} - diff --git a/location/java/com/android/internal/location/protocol/GWifiProfile.java b/location/java/com/android/internal/location/protocol/GWifiProfile.java deleted file mode 100644 index e73102718e379f5ce2b20d21cb8b95aa41544260..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GWifiProfile.java +++ /dev/null @@ -1,24 +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. - */ - -package com.android.internal.location.protocol; - -public interface GWifiProfile { - static final int TIMESTAMP = 1; - static final int WIFI_DEVICES = 2; - static final int PREFETCH_MODE = 3; -} - diff --git a/location/java/com/android/internal/location/protocol/GaddressMessageTypes.java b/location/java/com/android/internal/location/protocol/GaddressMessageTypes.java deleted file mode 100644 index 7b6ffd018d93bd059185d1b31f8d29cfd96242ba..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GaddressMessageTypes.java +++ /dev/null @@ -1,39 +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. - */ - -package com.android.internal.location.protocol; - -import com.google.common.io.protocol.ProtoBufType; - -public class GaddressMessageTypes { - public static final ProtoBufType GADDRESS = new ProtoBufType(); - public static final ProtoBufType GADDRESS_COMPONENT = new ProtoBufType(); - - static { - GADDRESS - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_DATA, - GAddress.FORMATTED_ADDRESS_LINE, null) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GAddress.COMPONENT, GADDRESS_COMPONENT); - - GADDRESS_COMPONENT - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_DATA, - GAddressComponent.NAME, null) - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_INT32, - GAddressComponent.FEATURE_TYPE, null); - - } -} diff --git a/location/java/com/android/internal/location/protocol/GcellularMessageTypes.java b/location/java/com/android/internal/location/protocol/GcellularMessageTypes.java deleted file mode 100644 index 37a6d5274f6ea6e4cd403b5de54fd0862e65ea68..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GcellularMessageTypes.java +++ /dev/null @@ -1,57 +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. - */ - -package com.android.internal.location.protocol; - -import com.google.common.io.protocol.ProtoBufType; - -public class GcellularMessageTypes { - public static final ProtoBufType GCELL = new ProtoBufType(); - public static final ProtoBufType GCELLULAR_PROFILE = new ProtoBufType(); - - static { - GCELL - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_INT32, - GCell.LAC, null) - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_INT32, - GCell.CELLID, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCell.MNC, new Long(-1)) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCell.MCC, new Long(-1)) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCell.RSSI, new Long(-9999)) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCell.AGE, new Long(0)) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCell.TIMING_ADVANCE, new Long(-1)) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCell.PRIMARY_SCRAMBLING_CODE, null); - - GCELLULAR_PROFILE - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_MESSAGE, - GCellularProfile.PRIMARY_CELL, GCELL) - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_INT64, - GCellularProfile.TIMESTAMP, null) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GCellularProfile.NEIGHBORS, GCELL) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GCellularProfile.HISTORICAL_CELLS, GCELL) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCellularProfile.PREFETCH_MODE, null); - - } -} diff --git a/location/java/com/android/internal/location/protocol/GdebugprofileMessageTypes.java b/location/java/com/android/internal/location/protocol/GdebugprofileMessageTypes.java deleted file mode 100644 index 9a51efe8cc30c61d44a3b0df44c2bfcaef7ee643..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GdebugprofileMessageTypes.java +++ /dev/null @@ -1,37 +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. - */ - -package com.android.internal.location.protocol; - -import com.google.common.io.protocol.ProtoBuf; -import com.google.common.io.protocol.ProtoBufType; - -public class GdebugprofileMessageTypes { - public static final ProtoBufType GDEBUG_PROFILE = new ProtoBufType(); - - static { - GDEBUG_PROFILE - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GDebugProfile.TRIGGER, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_BOOL, - GDebugProfile.ACTUAL_REQUEST, ProtoBuf.TRUE) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GDebugProfile.CACHE_LOCATION, GlocationMessageTypes.GDEVICE_LOCATION) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_BOOL, - GDebugProfile.DEVICE_RESTART, ProtoBuf.FALSE); - - } -} diff --git a/location/java/com/android/internal/location/protocol/GfeatureMessageTypes.java b/location/java/com/android/internal/location/protocol/GfeatureMessageTypes.java deleted file mode 100644 index 24b182a2ce6d3b0dec8dc956e7c39da72692a4a9..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GfeatureMessageTypes.java +++ /dev/null @@ -1,39 +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. - */ - -package com.android.internal.location.protocol; - -import com.google.common.io.protocol.ProtoBufType; - -public class GfeatureMessageTypes { - public static final ProtoBufType GFEATURE_TYPE = new ProtoBufType(); - public static final ProtoBufType GFEATURE = new ProtoBufType(); - - static { - GFEATURE - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_DATA, - GFeature.NAME, null) - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_INT32, - GFeature.FEATURE_TYPE, null) - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_MESSAGE, - GFeature.ADDRESS, GaddressMessageTypes.GADDRESS) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GFeature.BOUNDS, GrectangleMessageTypes.GRECTANGLE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GFeature.CENTER, GlatlngMessageTypes.GLAT_LNG); - - } -} diff --git a/location/java/com/android/internal/location/protocol/GlocationMessageTypes.java b/location/java/com/android/internal/location/protocol/GlocationMessageTypes.java deleted file mode 100644 index 067d47c84b4bd08661d110fb22adb781790c5269..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GlocationMessageTypes.java +++ /dev/null @@ -1,138 +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. - */ - -package com.android.internal.location.protocol; - -import com.google.common.io.protocol.ProtoBufType; - -public class GlocationMessageTypes { - public static final ProtoBufType GGPS_PROFILE = new ProtoBufType(); - public static final ProtoBufType GLOCATION = new ProtoBufType(); - public static final ProtoBufType GDEVICE_LOCATION = new ProtoBufType(); - public static final ProtoBufType GCELLULAR_PLATFORM_PROFILE = new ProtoBufType(); - public static final ProtoBufType GWIFI_PLATFORM_PROFILE = new ProtoBufType(); - public static final ProtoBufType GPREFETCH_MODE = new ProtoBufType(); - public static final ProtoBufType GPLATFORM_PROFILE = new ProtoBufType(); - public static final ProtoBufType GAPP_PROFILE = new ProtoBufType(); - public static final ProtoBufType GUSER_PROFILE = new ProtoBufType(); - - static { - GGPS_PROFILE - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GGpsProfile.GPS_FIX_TYPE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GGpsProfile.PDOP, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GGpsProfile.HDOP, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GGpsProfile.VDOP, null); - - GLOCATION - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocation.LAT_LNG, GlatlngMessageTypes.GLAT_LNG) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GLocation.SOURCE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GLocation.ACCURACY, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GLocation.CONFIDENCE, null) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GLocation.FEATURE, GfeatureMessageTypes.GFEATURE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT64, - GLocation.TIMESTAMP, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_BOOL, - GLocation.OBSOLETE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GLocation.LOC_TYPE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GLocation.MISC, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GLocation.ALTITUDE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GLocation.VERTICAL_ACCURACY, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GLocation.VELOCITY, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GLocation.HEADING, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocation.GPS_PROFILE, GGPS_PROFILE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GLocation.LOCATION_STRING, null); - - GDEVICE_LOCATION - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GDeviceLocation.LOCATION, GLOCATION) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GDeviceLocation.CELL, GcellularMessageTypes.GCELL) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GDeviceLocation.WIFI_DEVICE, GwifiMessageTypes.GWIFI_DEVICE); - - GCELLULAR_PLATFORM_PROFILE - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCellularPlatformProfile.RADIO_TYPE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GCellularPlatformProfile.CARRIER, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GCellularPlatformProfile.IP, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCellularPlatformProfile.HOME_MNC, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GCellularPlatformProfile.HOME_MCC, null); - - GWIFI_PLATFORM_PROFILE - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GWifiPlatformProfile.SCANNER_MAC, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GWifiPlatformProfile.SCANNER_IP, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GWifiPlatformProfile.RADIO_TYPE, null); - - GPLATFORM_PROFILE - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_DATA, - GPlatformProfile.VERSION, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GPlatformProfile.PLATFORM, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GPlatformProfile.PLATFORM_KEY, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GPlatformProfile.DISTRIBUTION_CHANNEL, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GPlatformProfile.LOCALE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GPlatformProfile.CELLULAR_PLATFORM_PROFILE, GCELLULAR_PLATFORM_PROFILE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GPlatformProfile.WIFI_PLATFORM_PROFILE, GWIFI_PLATFORM_PROFILE); - - GAPP_PROFILE - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GAppProfile.APP_NAME, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GAppProfile.APP_KEY, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GAppProfile.REQUEST_TYPE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GAppProfile.SEARCH_TYPE, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GAppProfile.SEARCH_TERM, null); - - GUSER_PROFILE - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GUserProfile.USER_NAME, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GUserProfile.AUTH_TOKEN, null); - - } -} diff --git a/location/java/com/android/internal/location/protocol/GwifiMessageTypes.java b/location/java/com/android/internal/location/protocol/GwifiMessageTypes.java deleted file mode 100644 index cd7119bd8bf6c4fd399204fb7ac244054cc5fb37..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/GwifiMessageTypes.java +++ /dev/null @@ -1,47 +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. - */ - -package com.android.internal.location.protocol; - -import com.google.common.io.protocol.ProtoBufType; - -public class GwifiMessageTypes { - public static final ProtoBufType GWIFI_DEVICE = new ProtoBufType(); - public static final ProtoBufType GWIFI_PROFILE = new ProtoBufType(); - - static { - GWIFI_DEVICE - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_DATA, - GWifiDevice.MAC, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GWifiDevice.SSID, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GWifiDevice.CHANNEL, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GWifiDevice.RSSI, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GWifiDevice.NOISE, null); - - GWIFI_PROFILE - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_INT64, - GWifiProfile.TIMESTAMP, null) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GWifiProfile.WIFI_DEVICES, GWIFI_DEVICE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_INT32, - GWifiProfile.PREFETCH_MODE, null); - - } -} diff --git a/location/java/com/android/internal/location/protocol/LocserverMessageTypes.java b/location/java/com/android/internal/location/protocol/LocserverMessageTypes.java deleted file mode 100644 index 8ffd00409aaf9011cabbc4ba73187b7cd27d68c5..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/LocserverMessageTypes.java +++ /dev/null @@ -1,80 +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. - */ - -package com.android.internal.location.protocol; - -import com.google.common.io.protocol.ProtoBuf; -import com.google.common.io.protocol.ProtoBufType; - -public class LocserverMessageTypes { - public static final ProtoBufType RESPONSE_CODES = new ProtoBufType(); - public static final ProtoBufType GLOC_REQUEST_ELEMENT = new ProtoBufType(); - public static final ProtoBufType GLOC_REQUEST = new ProtoBufType(); - public static final ProtoBufType GGEOCODE_REQUEST = new ProtoBufType(); - public static final ProtoBufType GLOC_REPLY_ELEMENT = new ProtoBufType(); - public static final ProtoBufType GLOC_REPLY = new ProtoBufType(); - - static { - GLOC_REQUEST_ELEMENT - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocRequestElement.CELLULAR_PROFILE, GcellularMessageTypes.GCELLULAR_PROFILE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocRequestElement.WIFI_PROFILE, GwifiMessageTypes.GWIFI_PROFILE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocRequestElement.LOCATION, GlocationMessageTypes.GLOCATION) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocRequestElement.GEOCODE, GGEOCODE_REQUEST) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocRequestElement.DEBUG_PROFILE, GdebugprofileMessageTypes.GDEBUG_PROFILE); - - GLOC_REQUEST - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_MESSAGE, - GLocRequest.PLATFORM_PROFILE, GlocationMessageTypes.GPLATFORM_PROFILE) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GLocRequest.APP_PROFILES, GlocationMessageTypes.GAPP_PROFILE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocRequest.USER_PROFILE, GlocationMessageTypes.GUSER_PROFILE) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GLocRequest.REQUEST_ELEMENTS, GLOC_REQUEST_ELEMENT) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocRequest.MASF_CLIENT_INFO, null); - - GGEOCODE_REQUEST - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_FIXED32, - GGeocodeRequest.NUM_FEATURE_LIMIT, new Long(1)) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_BOOL, - GGeocodeRequest.INCLUDE_BOUNDING_BOXES, ProtoBuf.FALSE) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GGeocodeRequest.BOUNDING_BOX, GrectangleMessageTypes.GRECTANGLE); - - GLOC_REPLY_ELEMENT - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_INT32, - GLocReplyElement.STATUS, null) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_MESSAGE, - GLocReplyElement.LOCATION, GlocationMessageTypes.GLOCATION) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GLocReplyElement.DEVICE_LOCATION, GlocationMessageTypes.GDEVICE_LOCATION); - - GLOC_REPLY - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_INT32, - GLocReply.STATUS, null) - .addElement(ProtoBufType.REPEATED | ProtoBufType.TYPE_MESSAGE, - GLocReply.REPLY_ELEMENTS, GLOC_REPLY_ELEMENT) - .addElement(ProtoBufType.OPTIONAL | ProtoBufType.TYPE_DATA, - GLocReply.PLATFORM_KEY, null); - - } -} diff --git a/location/java/com/android/internal/location/protocol/ResponseCodes.java b/location/java/com/android/internal/location/protocol/ResponseCodes.java deleted file mode 100644 index 2ea9318460b43eebcad109e9a448a6bdb44bbc17..0000000000000000000000000000000000000000 --- a/location/java/com/android/internal/location/protocol/ResponseCodes.java +++ /dev/null @@ -1,45 +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. - */ - -package com.android.internal.location.protocol; - -public interface ResponseCodes { - static final int STATUS_STATUS_SUCCESS = 0; - static final int STATUS_STATUS_FAILED = 1; - static final int STATUS_AUTHORIZATION_REJECTED = 2; - static final int STATUS_NO_SOURCE_EXISTS = 3; - static final int STATUS_SIGNAL_TOO_WEAK = 4; - static final int STATUS_INVALID_REQUEST = 5; - static final int STATUS_INVALID_NUM_REQUESTS = 6; - static final int STATUS_INVALID_USERLOCATION_FORMAT = 7; - static final int STATUS_INVALID_OPERATION_CODE = 8; - static final int STATUS_INVALID_MAC_STRING_FORMAT = 9; - static final int STATUS_INVALID_CELLID_STRING_FORMAT = 10; - static final int STATUS_NON_EXISTENT_AP = 11; - static final int STATUS_NON_EXISTENT_CELLID = 12; - static final int STATUS_STATUS_FAILED_NO_SOURCE = 13; - static final int STATUS_STATUS_FAILED_NO_SAVE = 14; - static final int STATUS_PLATFORM_KEY_EXPIRED = 15; - static final int STATUS_NO_STORE_EXISTS = 16; - static final int STATUS_NO_CELLIDDATA_FOR_UPDATE = 17; - static final int STATUS_NON_SUPPORTED_OPERATION_IN_UPDATE = 18; - static final int STATUS_NON_SUPPORTED_OPERATION = 19; - static final int STATUS_STATUS_FAILED_NO_GEOCODE = 20; - static final int STATUS_BLACKLISTED_IP_CELLID = 100; - static final int STATUS_BLACKLISTED_IP_WIFI = 101; - -} - diff --git a/media/java/android/media/AsyncPlayer.java b/media/java/android/media/AsyncPlayer.java index 0620f3213c9a12a1e8589f06c6c0f071dfcaa447..35f0409d09a8a9bc636c23492d585d3dea6671a4 100644 --- a/media/java/android/media/AsyncPlayer.java +++ b/media/java/android/media/AsyncPlayer.java @@ -22,6 +22,7 @@ import android.os.PowerManager; import android.util.Log; import java.io.IOException; +import java.lang.IllegalStateException; /** * Plays a series of audio URIs, but does all the hard work on another thread @@ -71,20 +72,20 @@ public class AsyncPlayer { // is playing, let it continue until we're done, so there // is less of a glitch. MediaPlayer player = new MediaPlayer(); - player.setDataSource(cmd.context, cmd.uri); player.setAudioStreamType(cmd.stream); + player.setDataSource(cmd.context, cmd.uri); player.setLooping(cmd.looping); player.prepare(); + player.start(); if (mPlayer != null) { - // stop the previous one. - mPlayer.stop(); mPlayer.release(); } - player.start(); mPlayer = player; } catch (IOException e) { Log.w(mTag, "error loading sound for " + cmd.uri, e); + } catch (IllegalStateException e) { + Log.w(mTag, "IllegalStateException (content provider died?) " + cmd.uri, e); } break; case STOP: diff --git a/media/java/android/media/AudioFormat.java b/media/java/android/media/AudioFormat.java index c857e17bd7865ddc8c77d22846b08f2b4cf27d19..0732b615e7e5cacabcbffed91cc17fc6997418ce 100644 --- a/media/java/android/media/AudioFormat.java +++ b/media/java/android/media/AudioFormat.java @@ -18,9 +18,9 @@ package android.media; /** * The AudioFormat class is used to access a number of audio format and - * channel configuration constants. + * channel configuration constants. They are for instance used + * in __link AudioTrack} and __link AudioRecord}. * - * {@hide Pending API council review} */ public class AudioFormat { diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java index 52cf69f91a968e2da001d5c27df14515c579425b..077d016433af7db94e5a51ad84e63470b5a5b80c 100644 --- a/media/java/android/media/AudioManager.java +++ b/media/java/android/media/AudioManager.java @@ -48,38 +48,61 @@ public class AudioManager { private static boolean DEBUG = false; private static boolean localLOGV = DEBUG || android.util.Config.LOGV; + /** + * Broadcast intent, a hint for applications that audio is about to become + * 'noisy' due to a change in audio outputs. For example, this intent may + * be sent when a wired headset is unplugged, or when an A2DP audio + * sink is disconnected, and the audio system is about to automatically + * switch audio route to the speaker. Applications that are controlling + * audio streams may consider pausing, reducing volume or some other action + * on receipt of this intent so as not to surprise the user with audio + * from the speaker. + */ + @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String ACTION_AUDIO_BECOMING_NOISY = "android.media.AUDIO_BECOMING_NOISY"; + /** * Sticky broadcast intent action indicating that the ringer mode has * changed. Includes the new ringer mode. - * + * * @see #EXTRA_RINGER_MODE */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String RINGER_MODE_CHANGED_ACTION = "android.media.RINGER_MODE_CHANGED"; - + /** * The new ringer mode. - * + * * @see #RINGER_MODE_CHANGED_ACTION * @see #RINGER_MODE_NORMAL * @see #RINGER_MODE_SILENT * @see #RINGER_MODE_VIBRATE */ public static final String EXTRA_RINGER_MODE = "android.media.EXTRA_RINGER_MODE"; - + /** * Broadcast intent action indicating that the vibrate setting has * changed. Includes the vibrate type and its new setting. - * + * * @see #EXTRA_VIBRATE_TYPE * @see #EXTRA_VIBRATE_SETTING */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String VIBRATE_SETTING_CHANGED_ACTION = "android.media.VIBRATE_SETTING_CHANGED"; - + + /** + * @hide Broadcast intent when the volume for a particular stream type changes. + * Includes the stream and the new volume + * + * @see #EXTRA_VOLUME_STREAM_TYPE + * @see #EXTRA_VOLUME_STREAM_VALUE + */ + @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"; + /** * The new vibrate setting for a particular type. - * + * * @see #VIBRATE_SETTING_CHANGED_ACTION * @see #EXTRA_VIBRATE_TYPE * @see #VIBRATE_SETTING_ON @@ -87,21 +110,32 @@ public class AudioManager { * @see #VIBRATE_SETTING_ONLY_SILENT */ public static final String EXTRA_VIBRATE_SETTING = "android.media.EXTRA_VIBRATE_SETTING"; - + /** * The vibrate type whose setting has changed. - * + * * @see #VIBRATE_SETTING_CHANGED_ACTION * @see #VIBRATE_TYPE_NOTIFICATION * @see #VIBRATE_TYPE_RINGER */ public static final String EXTRA_VIBRATE_TYPE = "android.media.EXTRA_VIBRATE_TYPE"; - + + /** + * @hide The stream type for the volume changed intent. + */ + public static final String EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE"; + + /** + * @hide The volume associated with the stream for the volume changed intent. + */ + public static final String EXTRA_VOLUME_STREAM_VALUE = + "android.media.EXTRA_VOLUME_STREAM_VALUE"; + /** The audio stream for phone calls */ public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL; /** The audio stream for system sounds */ public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM; - /** The audio stream for the phone ring and message alerts */ + /** The audio stream for the phone ring */ public static final int STREAM_RING = AudioSystem.STREAM_RING; /** The audio stream for music playback */ public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC; @@ -109,6 +143,8 @@ public class AudioManager { public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM; /** The audio stream for notifications */ public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION; + /** @hide The audio stream for phone calls when connected to bluetooth */ + public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO; /** Number of audio streams */ /** * @deprecated Use AudioSystem.getNumStreamTypes() instead @@ -123,9 +159,10 @@ public class AudioManager { 8, // STREAM_RING 16, // STREAM_MUSIC 8, // STREAM_ALARM - 8 // STREAM_NOTIFICATION - }; - + 8, // STREAM_NOTIFICATION + 15, // STREAM_BLUETOOTH_SCO + }; + /** @hide Default volume index values for audio streams */ public static final int[] DEFAULT_STREAM_VOLUME = new int[] { 4, // STREAM_VOICE_CALL @@ -133,12 +170,13 @@ public class AudioManager { 5, // STREAM_RING 11, // STREAM_MUSIC 6, // STREAM_ALARM - 5 // STREAM_NOTIFICATION - }; - + 5, // STREAM_NOTIFICATION + 7 // STREAM_BLUETOOTH_SCO + }; + /** * Increase the ringer volume. - * + * * @see #adjustVolume(int, int) * @see #adjustStreamVolume(int, int, int) */ @@ -146,7 +184,7 @@ public class AudioManager { /** * Decrease the ringer volume. - * + * * @see #adjustVolume(int, int) * @see #adjustStreamVolume(int, int, int) */ @@ -155,17 +193,17 @@ public class AudioManager { /** * Maintain the previous ringer volume. This may be useful when needing to * show the volume toast without actually modifying the volume. - * + * * @see #adjustVolume(int, int) * @see #adjustStreamVolume(int, int, int) */ public static final int ADJUST_SAME = 0; // Flags should be powers of 2! - + /** * Show a toast containing the current volume. - * + * * @see #adjustStreamVolume(int, int, int) * @see #adjustVolume(int, int) * @see #setStreamVolume(int, int, int) @@ -176,19 +214,18 @@ public class AudioManager { /** * Whether to include ringer modes as possible options when changing volume. * For example, if true and volume level is 0 and the volume is adjusted - * with {@link #ADJUST_LOWER}, then the ringer mode may switch the silent - * or vibrate mode. + * with {@link #ADJUST_LOWER}, then the ringer mode may switch the silent or + * vibrate mode. *

                - * By default this is on for stream types that are affected by the ringer - * mode (for example, the ring stream type). If this flag is included, this - * behavior will be present regardless of the stream type being affected by - * the ringer mode. + * By default this is on for the ring stream. If this flag is included, + * this behavior will be present regardless of the stream type being + * affected by the ringer mode. * * @see #adjustVolume(int, int) * @see #adjustStreamVolume(int, int, int) */ public static final int FLAG_ALLOW_RINGER_MODES = 1 << 1; - + /** * Whether to play a sound when changing the volume. *

                @@ -197,28 +234,28 @@ public class AudioManager { * in some cases (for example, the decided stream type is not * {@link AudioManager#STREAM_RING}, or the volume is being adjusted * downward). - * + * * @see #adjustStreamVolume(int, int, int) * @see #adjustVolume(int, int) * @see #setStreamVolume(int, int, int) */ public static final int FLAG_PLAY_SOUND = 1 << 2; - + /** * Removes any sounds/vibrate that may be in the queue, or are playing (related to * changing volume). */ public static final int FLAG_REMOVE_SOUND_AND_VIBRATE = 1 << 3; - + /** * Whether to vibrate if going into the vibrate ringer mode. */ public static final int FLAG_VIBRATE = 1 << 4; - + /** * Ringer mode that will be silent and will not vibrate. (This overrides the * vibrate setting.) - * + * * @see #setRingerMode(int) * @see #getRingerMode() */ @@ -228,7 +265,7 @@ public class AudioManager { * Ringer mode that will be silent and will vibrate. (This will cause the * phone ringer to always vibrate, but the notification vibrate to only * vibrate if set.) - * + * * @see #setRingerMode(int) * @see #getRingerMode() */ @@ -238,7 +275,7 @@ public class AudioManager { * Ringer mode that may be audible and may vibrate. It will be audible if * the volume before changing out of this mode was audible. It will vibrate * if the vibrate setting is on. - * + * * @see #setRingerMode(int) * @see #getRingerMode() */ @@ -246,53 +283,53 @@ public class AudioManager { /** * Vibrate type that corresponds to the ringer. - * + * * @see #setVibrateSetting(int, int) * @see #getVibrateSetting(int) * @see #shouldVibrate(int) */ public static final int VIBRATE_TYPE_RINGER = 0; - + /** * Vibrate type that corresponds to notifications. - * + * * @see #setVibrateSetting(int, int) * @see #getVibrateSetting(int) * @see #shouldVibrate(int) */ public static final int VIBRATE_TYPE_NOTIFICATION = 1; - + /** * Vibrate setting that suggests to never vibrate. - * + * * @see #setVibrateSetting(int, int) * @see #getVibrateSetting(int) */ public static final int VIBRATE_SETTING_OFF = 0; - + /** * Vibrate setting that suggests to vibrate when possible. - * + * * @see #setVibrateSetting(int, int) * @see #getVibrateSetting(int) */ public static final int VIBRATE_SETTING_ON = 1; - + /** * Vibrate setting that suggests to only vibrate when in the vibrate ringer * mode. - * + * * @see #setVibrateSetting(int, int) * @see #getVibrateSetting(int) */ public static final int VIBRATE_SETTING_ONLY_SILENT = 2; - + /** * Suggests using the default stream type. This may not be used in all * places a stream type is needed. */ public static final int USE_DEFAULT_STREAM_TYPE = Integer.MIN_VALUE; - + private static IAudioService sService; /** @@ -315,8 +352,8 @@ public class AudioManager { /** * Adjusts the volume of a particular stream by one step in a direction. - * - * @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL}, + * + * @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL}, * {@link #STREAM_SYSTEM}, {@link #STREAM_RING}, {@link #STREAM_MUSIC} or * {@link #STREAM_ALARM} * @param direction The direction to adjust the volume. One of @@ -340,7 +377,7 @@ public class AudioManager { * active, it will have the highest priority regardless of if the in-call * screen is showing. Another example, if music is playing in the background * and a call is not active, the music stream will be adjusted. - * + * * @param direction The direction to adjust the volume. One of * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or * {@link #ADJUST_SAME}. @@ -361,7 +398,7 @@ public class AudioManager { /** * Adjusts the volume of the most relevant stream, or the given fallback * stream. - * + * * @param direction The direction to adjust the volume. One of * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or * {@link #ADJUST_SAME}. @@ -380,10 +417,10 @@ public class AudioManager { Log.e(TAG, "Dead object in adjustVolume", e); } } - + /** * Returns the current ringtone mode. - * + * * @return The current ringtone mode, one of {@link #RINGER_MODE_NORMAL}, * {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}. * @see #setRingerMode(int) @@ -400,7 +437,7 @@ public class AudioManager { /** * Returns the maximum volume index for a particular stream. - * + * * @param streamType The stream type whose maximum volume index is returned. * @return The maximum valid volume index for the stream. * @see #getStreamVolume(int) @@ -417,7 +454,7 @@ public class AudioManager { /** * Returns the current volume index for a particular stream. - * + * * @param streamType The stream type whose volume index is returned. * @return The current volume index for the stream. * @see #getStreamMaxVolume(int) @@ -439,7 +476,7 @@ public class AudioManager { * Silent mode will mute the volume and will not vibrate. Vibrate mode will * mute the volume and vibrate. Normal mode will be audible and may vibrate * according to user settings. - * + * * @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL}, * {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}. * @see #getRingerMode() @@ -455,7 +492,7 @@ public class AudioManager { /** * Sets the volume index for a particular stream. - * + * * @param streamType The stream whose volume index should be set. * @param index The volume index to set. See * {@link #getStreamMaxVolume(int)} for the largest valid value. @@ -471,7 +508,7 @@ public class AudioManager { Log.e(TAG, "Dead object in setStreamVolume", e); } } - + /** * Solo or unsolo a particular stream. All other streams are muted. *

                @@ -479,13 +516,13 @@ public class AudioManager { * with an active solo request on a stream dies, all streams that were muted * because of this request will be unmuted automatically. *

                - * The solo requests for a given stream are cumulative: the AudioManager + * The solo requests for a given stream are cumulative: the AudioManager * can receive several solo requests from one or more clients and the stream * will be unsoloed only when the same number of unsolo requests are received. *

                - * For a better user experience, applications MUST unsolo a soloed stream + * For a better user experience, applications MUST unsolo a soloed stream * in onPause() and solo is again in onResume() if appropriate. - * + * * @param streamType The stream to be soloed/unsoloed. * @param state The required solo state: true for solo ON, false for solo OFF */ @@ -497,7 +534,7 @@ public class AudioManager { Log.e(TAG, "Dead object in setStreamSolo", e); } } - + /** * Mute or unmute an audio stream. *

                @@ -505,13 +542,13 @@ public class AudioManager { * with an active mute request on a stream dies, this stream will be unmuted * automatically. *

                - * The mute requests for a given stream are cumulative: the AudioManager + * The mute requests for a given stream are cumulative: the AudioManager * can receive several mute requests from one or more clients and the stream * will be unmuted only when the same number of unmute requests are received. *

                - * For a better user experience, applications MUST unmute a muted stream + * For a better user experience, applications MUST unmute a muted stream * in onPause() and mute is again in onResume() if appropriate. - * + * * @param streamType The stream to be muted/unmuted. * @param state The required mute state: true for mute ON, false for mute OFF */ @@ -532,7 +569,7 @@ public class AudioManager { * vibrate. The notification manager will not vibrate if the policy doesn't * allow it, so the client should always set a vibrate pattern and let the * notification manager control whether or not to actually vibrate. - * + * * @param vibrateType The type of vibrate. One of * {@link #VIBRATE_TYPE_NOTIFICATION} or * {@link #VIBRATE_TYPE_RINGER}. @@ -550,13 +587,13 @@ public class AudioManager { return false; } } - + /** * Returns whether the user's vibrate setting for a vibrate type. *

                * This shouldn't be needed by most clients that want to vibrate, instead * see {@link #shouldVibrate(int)}. - * + * * @param vibrateType The type of vibrate. One of * {@link #VIBRATE_TYPE_NOTIFICATION} or * {@link #VIBRATE_TYPE_RINGER}. @@ -578,7 +615,7 @@ public class AudioManager { /** * Sets the setting for when the vibrate type should vibrate. - * + * * @param vibrateType The type of vibrate. One of * {@link #VIBRATE_TYPE_NOTIFICATION} or * {@link #VIBRATE_TYPE_RINGER}. @@ -597,11 +634,11 @@ public class AudioManager { Log.e(TAG, "Dead object in setVibrateSetting", e); } } - + /** * Sets the speakerphone on or off. * - * @param on set true to turn on speakerphone; + * @param on set true to turn on speakerphone; * false to turn it off */ public void setSpeakerphoneOn(boolean on){ @@ -620,17 +657,17 @@ public class AudioManager { /** * Sets audio routing to the Bluetooth headset on or off. * - * @param on set true to route SCO (voice) audio to/from Bluetooth + * @param on set true to route SCO (voice) audio to/from Bluetooth * headset; false to route audio to/from phone earpiece */ public void setBluetoothScoOn(boolean on){ // Don't disable A2DP when turning off SCO. // A2DP does not affect in-call routing. - setRouting(MODE_RINGTONE, + setRouting(MODE_RINGTONE, on ? ROUTE_BLUETOOTH_SCO: ROUTE_SPEAKER, ROUTE_ALL & ~ROUTE_BLUETOOTH_A2DP); - setRouting(MODE_NORMAL, + setRouting(MODE_NORMAL, on ? ROUTE_BLUETOOTH_SCO: ROUTE_SPEAKER, ROUTE_ALL & ~ROUTE_BLUETOOTH_A2DP); - setRouting(MODE_IN_CALL, + setRouting(MODE_IN_CALL, on ? ROUTE_BLUETOOTH_SCO: ROUTE_EARPIECE, ROUTE_ALL); } @@ -647,15 +684,15 @@ public class AudioManager { /** * Sets A2DP audio routing to the Bluetooth headset on or off. * - * @param on set true to route A2DP audio to/from Bluetooth + * @param on set true to route A2DP audio to/from Bluetooth * headset; false disable A2DP audio */ public void setBluetoothA2dpOn(boolean on){ // the audio flinger chooses A2DP as a higher priority, // so there is no need to disable other routes. - setRouting(MODE_RINGTONE, + setRouting(MODE_RINGTONE, on ? ROUTE_BLUETOOTH_A2DP: 0, ROUTE_BLUETOOTH_A2DP); - setRouting(MODE_NORMAL, + setRouting(MODE_NORMAL, on ? ROUTE_BLUETOOTH_A2DP: 0, ROUTE_BLUETOOTH_A2DP); } @@ -672,7 +709,7 @@ public class AudioManager { /** * Sets audio routing to the wired headset on or off. * - * @param on set true to route audio to/from wired + * @param on set true to route audio to/from wired * headset; false disable wired headset audio * @hide */ @@ -701,7 +738,7 @@ public class AudioManager { /** * Sets the microphone mute on or off. * - * @param on set true to mute the microphone; + * @param on set true to mute the microphone; * false to turn mute off */ public void setMicrophoneMute(boolean on){ @@ -762,57 +799,57 @@ public class AudioManager { /* modes for setMode/getMode/setRoute/getRoute */ /** - * Audio harware modes. - */ + * Audio harware modes. + */ /** - * Invalid audio mode. - */ + * Invalid audio mode. + */ public static final int MODE_INVALID = AudioSystem.MODE_INVALID; /** * Current audio mode. Used to apply audio routing to current mode. - */ + */ public static final int MODE_CURRENT = AudioSystem.MODE_CURRENT; /** * Normal audio mode: not ringing and no call established. - */ + */ public static final int MODE_NORMAL = AudioSystem.MODE_NORMAL; /** * Ringing audio mode. An incoming is being signaled. - */ + */ public static final int MODE_RINGTONE = AudioSystem.MODE_RINGTONE; /** * In call audio mode. A call is established. - */ + */ public static final int MODE_IN_CALL = AudioSystem.MODE_IN_CALL; /* Routing bits for setRouting/getRouting API */ /** * Routing audio output to earpiece - */ + */ public static final int ROUTE_EARPIECE = AudioSystem.ROUTE_EARPIECE; /** * Routing audio output to spaker - */ + */ public static final int ROUTE_SPEAKER = AudioSystem.ROUTE_SPEAKER; /** * @deprecated use {@link #ROUTE_BLUETOOTH_SCO} - */ + */ @Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO; /** * Routing audio output to bluetooth SCO - */ + */ public static final int ROUTE_BLUETOOTH_SCO = AudioSystem.ROUTE_BLUETOOTH_SCO; /** * Routing audio output to headset - */ + */ public static final int ROUTE_HEADSET = AudioSystem.ROUTE_HEADSET; /** * Routing audio output to bluetooth A2DP - */ + */ public static final int ROUTE_BLUETOOTH_A2DP = AudioSystem.ROUTE_BLUETOOTH_A2DP; /** * Used for mask parameter of {@link #setRouting(int,int,int)}. - */ + */ public static final int ROUTE_ALL = AudioSystem.ROUTE_ALL; /** @@ -892,33 +929,57 @@ public class AudioManager { /** * Keyboard and direction pad click sound * @see #playSoundEffect(int) - */ + */ public static final int FX_KEY_CLICK = 0; /** - * Focuse has moved up + * Focus has moved up * @see #playSoundEffect(int) - */ + */ public static final int FX_FOCUS_NAVIGATION_UP = 1; /** - * Focuse has moved down + * Focus has moved down * @see #playSoundEffect(int) - */ + */ public static final int FX_FOCUS_NAVIGATION_DOWN = 2; /** - * Focuse has moved left + * Focus has moved left * @see #playSoundEffect(int) - */ + */ public static final int FX_FOCUS_NAVIGATION_LEFT = 3; /** - * Focuse has moved right + * Focus has moved right * @see #playSoundEffect(int) - */ + */ public static final int FX_FOCUS_NAVIGATION_RIGHT = 4; /** - * @hide Number of sound effects - */ - public static final int NUM_SOUND_EFFECTS = 5; - + * IME standard keypress sound + * @see #playSoundEffect(int) + * @hide FIXME: Unhide before release + */ + public static final int FX_KEYPRESS_STANDARD = 5; + /** + * IME spacebar keypress sound + * @see #playSoundEffect(int) + * @hide FIXME: Unhide before release + */ + public static final int FX_KEYPRESS_SPACEBAR = 6; + /** + * IME delete keypress sound + * @see #playSoundEffect(int) + * @hide FIXME: Unhide before release + */ + public static final int FX_KEYPRESS_DELETE = 7; + /** + * IME return_keypress sound + * @see #playSoundEffect(int) + * @hide FIXME: Unhide before release + */ + public static final int FX_KEYPRESS_RETURN = 8; + /** + * @hide Number of sound effects + */ + public static final int NUM_SOUND_EFFECTS = 9; + /** * Plays a sound effect (Key clicks, lid open/close...) * @param effectType The type of sound effect. One of @@ -927,6 +988,13 @@ public class AudioManager { * {@link #FX_FOCUS_NAVIGATION_DOWN}, * {@link #FX_FOCUS_NAVIGATION_LEFT}, * {@link #FX_FOCUS_NAVIGATION_RIGHT}, + * FIXME: include links before release + * {link #FX_KEYPRESS_STANDARD}, + * {link #FX_KEYPRESS_SPACEBAR}, + * {link #FX_KEYPRESS_DELETE}, + * {link #FX_KEYPRESS_RETURN}, + * NOTE: This version uses the UI settings to determine + * whether sounds are heard or not. */ public void playSoundEffect(int effectType) { if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) { @@ -945,16 +1013,47 @@ public class AudioManager { } } + /** + * Plays a sound effect (Key clicks, lid open/close...) + * @param effectType The type of sound effect. One of + * {@link #FX_KEY_CLICK}, + * {@link #FX_FOCUS_NAVIGATION_UP}, + * {@link #FX_FOCUS_NAVIGATION_DOWN}, + * {@link #FX_FOCUS_NAVIGATION_LEFT}, + * {@link #FX_FOCUS_NAVIGATION_RIGHT}, + * FIXME: include links before release + * {link #FX_KEYPRESS_STANDARD}, + * {link #FX_KEYPRESS_SPACEBAR}, + * {link #FX_KEYPRESS_DELETE}, + * {link #FX_KEYPRESS_RETURN}, + * @param volume Sound effect volume + * NOTE: This version is for applications that have their own + * settings panel for enabling and controlling volume. + * @hide FIXME: Unhide before release + */ + public void playSoundEffect(int effectType, float volume) { + if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) { + return; + } + + IAudioService service = getService(); + try { + service.playSoundEffectVolume(effectType, volume); + } catch (RemoteException e) { + Log.e(TAG, "Dead object in playSoundEffect"+e); + } + } + /** * Settings has an in memory cache, so this is fast. */ private boolean querySoundEffectsEnabled() { return Settings.System.getInt(mContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 0) != 0; } - - + + /** - * Load Sound effects. + * Load Sound effects. * This method must be called when sound effects are enabled. */ public void loadSoundEffects() { @@ -965,9 +1064,9 @@ public class AudioManager { Log.e(TAG, "Dead object in loadSoundEffects"+e); } } - + /** - * Unload Sound effects. + * Unload Sound effects. * This method can be called to free some memory when * sound effects are disabled. */ diff --git a/media/java/android/media/AudioRecord.java b/media/java/android/media/AudioRecord.java index 7912003b3a2167bf6e14cd0f1372d1ef7319cfef..0ef7760987d630a444d65d5610632438abc68c2c 100644 --- a/media/java/android/media/AudioRecord.java +++ b/media/java/android/media/AudioRecord.java @@ -34,11 +34,14 @@ import android.util.Log; * to record audio from the audio input hardware of the platform. This is * achieved by "pulling" (reading) the data from the AudioRecord object. The * application is responsible for polling the AudioRecord object in time using one of - * the following three methods: {@link #read(byte[], int)}, {@link #read(short[], int)} + * the following three methods: {@link #read(byte[],int, int)}, {@link #read(short[], int, int)} * or {@link #read(ByteBuffer, int)}. The choice of which method to use will be based * on the audio data storage format that is the most convenient for the user of AudioRecord. - * - * {@hide Pending API council review} + *

                Upon creation, an AudioRecord object initializes its associated audio buffer that it will + * fill with the new audio data. The size of this buffer, specified during the construction, + * determines how long an AudioRecord can record before "over-running" data that has not + * been read yet. Data should be from the audio hardware in chunks of sizes inferior to + * the total recording buffer size. */ public class AudioRecord { @@ -82,22 +85,22 @@ public class AudioRecord */ public static final int ERROR_INVALID_OPERATION = -3; - private static final int AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT = -4; - private static final int AUDIORECORD_ERROR_SETUP_INVALIDCHANNELCOUNT = -5; - private static final int AUDIORECORD_ERROR_SETUP_INVALIDFORMAT = -6; - private static final int AUDIORECORD_ERROR_SETUP_INVALIDSTREAMTYPE = -7; - private static final int AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED = -8; + private static final int AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT = -16; + private static final int AUDIORECORD_ERROR_SETUP_INVALIDCHANNELCOUNT = -17; + private static final int AUDIORECORD_ERROR_SETUP_INVALIDFORMAT = -18; + private static final int AUDIORECORD_ERROR_SETUP_INVALIDSTREAMTYPE = -19; + private static final int AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED = -20; // Events: // to keep in sync with frameworks/base/include/media/AudioRecord.h /** * Event id for when the recording head has reached a previously set marker. */ - protected static final int EVENT_MARKER = 2; + private static final int NATIVE_EVENT_MARKER = 2; /** * Event id for when the previously set update period has passed during recording. */ - protected static final int EVENT_NEW_POS = 3; + private static final int NATIVE_EVENT_NEW_POS = 3; private final static String TAG = "AudioRecord-Java"; @@ -130,63 +133,63 @@ public class AudioRecord /** * The audio data sampling rate in Hz. */ - protected int mSampleRate = 22050; + private int mSampleRate = 22050; /** * The number of input audio channels (1 is mono, 2 is stereo) */ - protected int mChannelCount = 1; + private int mChannelCount = 1; /** * The current audio channel configuration */ - protected int mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; + private int mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; /** * The encoding of the audio samples. - * @see #AudioFormat.ENCODING_PCM_8BIT - * @see #AudioFormat.ENCODING_PCM_16BIT + * @see AudioFormat#ENCODING_PCM_8BIT + * @see AudioFormat#ENCODING_PCM_16BIT */ - protected int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; + private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; /** * Where the audio data is recorded from. */ - protected int mRecordSource = MediaRecorder.AudioSource.DEFAULT; + private int mRecordSource = MediaRecorder.AudioSource.DEFAULT; /** * Indicates the state of the AudioRecord instance. */ - protected int mState = STATE_UNINITIALIZED; + private int mState = STATE_UNINITIALIZED; /** * Indicates the recording state of the AudioRecord instance. */ - protected int mRecordingState = RECORDSTATE_STOPPED; + private int mRecordingState = RECORDSTATE_STOPPED; /** * Lock to make sure mRecordingState updates are reflecting the actual state of the object. */ - protected Object mRecordingStateLock = new Object(); + private Object mRecordingStateLock = new Object(); /** * The listener the AudioRecord notifies when a previously set marker is reached. * @see #setMarkerReachedListener(OnMarkerReachedListener) */ - protected OnMarkerReachedListener mMarkerListener = null; + private OnMarkerReachedListener mMarkerListener = null; /** * Lock to protect marker listener updates against event notifications */ - protected final Object mMarkerListenerLock = new Object(); + private final Object mMarkerListenerLock = new Object(); /** * The listener the AudioRecord notifies periodically during recording. * @see #setPeriodicNotificationListener(OnPeriodicNotificationListener) */ - protected OnPeriodicNotificationListener mPeriodicListener = null; + private OnPeriodicNotificationListener mPeriodicListener = null; /** * Lock to protect periodic listener updates against event notifications */ - protected final Object mPeriodicListenerLock = new Object(); + private final Object mPeriodicListenerLock = new Object(); /** * Handler for events coming from the native code */ - protected NativeEventHandler mNativeEventHandler = null; + private NativeEventHandler mNativeEventHandler = null; /** * Size of the native audio buffer. */ - protected int mNativeBufferSizeInBytes = 0; + private int mNativeBufferSizeInBytes = 0; //--------------------------------------------------------- @@ -194,30 +197,30 @@ public class AudioRecord //-------------------- /** * Class constructor. - * @param audioSource the recording source. See {@link MediaRecorder.AudioSource.DEFAULT} - * and {@link MediaRecorder.AudioSource.MIC}. + * @param audioSource the recording source. See {@link MediaRecorder.AudioSource} for + * recording source definitions. * @param sampleRateInHz the sample rate expressed in Hertz. Examples of rates are (but * not limited to) 44100, 22050 and 11025. * @param channelConfig describes the configuration of the audio channels. - * See {@link AudioFormat.CHANNEL_CONFIGURATION_MONO} and - * {@link AudioFormat.CHANNEL_CONFIGURATION_STEREO} + * See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} and + * {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO} * @param audioFormat the format in which the audio data is represented. - * See {@link AudioFormat.ENCODING_PCM_16BIT} and - * {@link AudioFormat.ENCODING_PCM_8BIT} + * See {@link AudioFormat#ENCODING_PCM_16BIT} and + * {@link AudioFormat#ENCODING_PCM_8BIT} * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is written * to during the recording. New audio data can be read from this buffer in smaller chunks * than this size. * @throws java.lang.IllegalArgumentException */ public AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat, - int blockSizeInBytes) + int bufferSizeInBytes) throws IllegalArgumentException { mState = STATE_UNINITIALIZED; mRecordingState = RECORDSTATE_STOPPED; audioParamCheck(audioSource, sampleRateInHz, channelConfig, audioFormat); - audioBuffSizeCheck(blockSizeInBytes); + audioBuffSizeCheck(bufferSizeInBytes); // native initialization //TODO: update native initialization when information about hardware init failure @@ -336,7 +339,11 @@ public class AudioRecord * Releases the native AudioRecord resources. */ public void release() { - stop(); + try { + stop(); + } catch(IllegalStateException ise) { + // don't raise an exception, we're releasing the resources. + } native_release(); mState = STATE_UNINITIALIZED; } @@ -367,8 +374,8 @@ public class AudioRecord } /** - * Returns the configured audio data format. See {@link #AudioFormat.ENCODING_PCM_16BIT} - * and {@link #AudioFormat.ENCODING_PCM_8BIT}. + * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT} + * and {@link AudioFormat#ENCODING_PCM_8BIT}. */ public int getAudioFormat() { return mAudioFormat; @@ -376,8 +383,8 @@ public class AudioRecord /** * Returns the configured channel configuration. - * See {@link #AudioFormat.CHANNEL_CONFIGURATION_MONO} - * and {@link #AudioFormat.CHANNEL_CONFIGURATION_STEREO}. + * See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} + * and {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO}. */ public int getChannelConfiguration() { return mChannelConfiguration; @@ -395,8 +402,8 @@ public class AudioRecord * AudioRecord instance has been created to check if it was initialized * properly. This ensures that the appropriate hardware resources have been * acquired. - * @see AudioRecord.STATE_INITIALIZED - * @see AudioRecord.STATE_UNINITIALIZED + * @see AudioRecord#STATE_INITIALIZED + * @see AudioRecord#STATE_UNINITIALIZED */ public int getState() { return mState; @@ -404,8 +411,8 @@ public class AudioRecord /** * Returns the recording state of the AudioRecord instance. - * @see AudioRecord.RECORDSTATE_STOPPED - * @see AudioRecord.RECORDSTATE_RECORDING + * @see AudioRecord#RECORDSTATE_STOPPED + * @see AudioRecord#RECORDSTATE_RECORDING */ public int getRecordingState() { return mRecordingState; @@ -424,6 +431,56 @@ public class AudioRecord public int getPositionNotificationPeriod() { return native_get_pos_update_period(); } + + /** + * {@hide} + * Returns the minimum buffer size required for the successful creation of an AudioRecord + * object. + * @param sampleRateInHz the sample rate expressed in Hertz. + * @param channelConfig describes the configuration of the audio channels. + * See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} and + * {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO} + * @param audioFormat the format in which the audio data is represented. + * See {@link AudioFormat#ENCODING_PCM_16BIT}. + * @return {@link #ERROR_BAD_VALUE} if the recording parameters are not supported by the + * hardware, or an invalid parameter was passed, + * or {@link #ERROR} if the implementation was unable to query the hardware for its + * output properties, + * or the minimum buffer size expressed in of bytes. + */ + static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) { + int channelCount = 0; + switch(channelConfig) { + case AudioFormat.CHANNEL_CONFIGURATION_DEFAULT: + case AudioFormat.CHANNEL_CONFIGURATION_MONO: + channelCount = 1; + break; + case AudioFormat.CHANNEL_CONFIGURATION_STEREO: + channelCount = 2; + break; + case AudioFormat.CHANNEL_CONFIGURATION_INVALID: + default: + loge("getMinBufferSize(): Invalid channel configuration."); + return AudioRecord.ERROR_BAD_VALUE; + } + + // PCM_8BIT is not supported at the moment + if (audioFormat != AudioFormat.ENCODING_PCM_16BIT) { + loge("getMinBufferSize(): Invalid audio format."); + return AudioRecord.ERROR_BAD_VALUE; + } + + int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat); + if (size == 0) { + return AudioRecord.ERROR_BAD_VALUE; + } + else if (size == -1) { + return AudioRecord.ERROR; + } + else { + return size; + } + } //--------------------------------------------------------- @@ -472,16 +529,22 @@ public class AudioRecord //-------------------- /** * Reads audio data from the audio hardware for recording into a buffer. - * @throws IllegalStateException * @param audioData the array to which the recorded audio data is written. * @param offsetInBytes index in audioData from which the data is written. * @param sizeInBytes the number of requested bytes. - * @return the number of bytes that were read. This will not exceed sizeInBytes + * @return the number of bytes that were read or or {@link #ERROR_INVALID_OPERATION} + * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if + * the parameters don't resolve to valid data and indexes. + * The number of bytes will not exceed sizeInBytes. */ - public int read(byte[] audioData, int offsetInBytes, int sizeInBytes) - throws IllegalStateException { + public int read(byte[] audioData, int offsetInBytes, int sizeInBytes) { if (mState != STATE_INITIALIZED) { - throw(new IllegalStateException("read() called on uninitialized AudioRecord.")); + return ERROR_INVALID_OPERATION; + } + + if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0) + || (offsetInBytes + sizeInBytes > audioData.length)) { + return ERROR_BAD_VALUE; } return native_read_in_byte_array(audioData, offsetInBytes, sizeInBytes); @@ -490,16 +553,22 @@ public class AudioRecord /** * Reads audio data from the audio hardware for recording into a buffer. - * @throws IllegalStateException * @param audioData the array to which the recorded audio data is written. * @param offsetInShorts index in audioData from which the data is written. * @param sizeInShorts the number of requested shorts. - * @return the number of shorts that were read. This will not exceed sizeInShorts + * @return the number of bytes that were read or or {@link #ERROR_INVALID_OPERATION} + * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if + * the parameters don't resolve to valid data and indexes. + * The number of shorts will not exceed sizeInShorts. */ - public int read(short[] audioData, int offsetInShorts, int sizeInShorts) - throws IllegalStateException { + public int read(short[] audioData, int offsetInShorts, int sizeInShorts) { if (mState != STATE_INITIALIZED) { - throw(new IllegalStateException("read() called on uninitialized AudioRecord.")); + return ERROR_INVALID_OPERATION; + } + + if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0) + || (offsetInShorts + sizeInShorts > audioData.length)) { + return ERROR_BAD_VALUE; } return native_read_in_short_array(audioData, offsetInShorts, sizeInShorts); @@ -509,15 +578,20 @@ public class AudioRecord /** * Reads audio data from the audio hardware for recording into a direct buffer. If this buffer * is not a direct buffer, this method will always return 0. - * @throws IllegalStateException * @param audioBuffer the direct buffer to which the recorded audio data is written. * @param sizeInBytes the number of requested bytes. - * @return the number of bytes that were read. This will not exceed sizeInBytes. + * @return the number of bytes that were read or or {@link #ERROR_INVALID_OPERATION} + * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if + * the parameters don't resolve to valid data and indexes. + * The number of bytes will not exceed sizeInBytes. */ - public int read(ByteBuffer audioBuffer, int sizeInBytes) - throws IllegalStateException { + public int read(ByteBuffer audioBuffer, int sizeInBytes) { if (mState != STATE_INITIALIZED) { - throw(new IllegalStateException("read() called on uninitialized AudioRecord.")); + return ERROR_INVALID_OPERATION; + } + + if ( (audioBuffer == null) || (sizeInBytes < 0) ) { + return ERROR_BAD_VALUE; } return native_read_in_direct_buffer(audioBuffer, sizeInBytes); @@ -590,7 +664,7 @@ public class AudioRecord * Called on the listener to notify it that the previously set marker has been reached * by the recording head. */ - void onMarkerReached(AudioRecord track); + void onMarkerReached(AudioRecord recorder); } @@ -603,7 +677,7 @@ public class AudioRecord * Called on the listener to periodically notify it that the recording head has reached * a multiple of the notification period. */ - void onPeriodicNotification(AudioRecord track); + void onPeriodicNotification(AudioRecord recorder); } @@ -628,14 +702,14 @@ public class AudioRecord return; } switch(msg.what) { - case EVENT_MARKER: + case NATIVE_EVENT_MARKER: synchronized (mMarkerListenerLock) { if (mAudioRecord.mMarkerListener != null) { mAudioRecord.mMarkerListener.onMarkerReached(mAudioRecord); } } break; - case EVENT_NEW_POS: + case NATIVE_EVENT_NEW_POS: synchronized (mPeriodicListenerLock) { if (mAudioRecord.mPeriodicListener != null) { mAudioRecord.mPeriodicListener.onPeriodicNotification(mAudioRecord); @@ -643,7 +717,7 @@ public class AudioRecord } break; default: - Log.e(TAG, "[ android.media.AudioTrack.NativeEventHandler ] " + + Log.e(TAG, "[ android.media.AudioRecord.NativeEventHandler ] " + "Unknown event type: " + msg.what); break; } @@ -658,14 +732,14 @@ public class AudioRecord private static void postEventFromNative(Object audiorecord_ref, int what, int arg1, int arg2, Object obj) { //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2); - AudioRecord track = (AudioRecord)((WeakReference)audiorecord_ref).get(); - if (track == null) { + AudioRecord recorder = (AudioRecord)((WeakReference)audiorecord_ref).get(); + if (recorder == null) { return; } - if (track.mNativeEventHandler != null) { - Message m = track.mNativeEventHandler.obtainMessage(what, arg1, arg2, obj); - track.mNativeEventHandler.sendMessage(m); + if (recorder.mNativeEventHandler != null) { + Message m = recorder.mNativeEventHandler.obtainMessage(what, arg1, arg2, obj); + recorder.mNativeEventHandler.sendMessage(m); } } @@ -699,6 +773,9 @@ public class AudioRecord private native final int native_set_pos_update_period(int updatePeriod); private native final int native_get_pos_update_period(); + + static private native final int native_get_min_buff_size( + int sampleRateInHz, int channelCount, int audioFormat); //--------------------------------------------------------- diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java index b39e7bb1911d6748788b4f409e8263504996f1da..83ede0d00157db9bd71c60979050e025818ffc61 100644 --- a/media/java/android/media/AudioService.java +++ b/media/java/android/media/AudioService.java @@ -16,8 +16,7 @@ package android.media; -import com.android.internal.telephony.ITelephony; - +import android.app.ActivityManagerNative; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; @@ -32,11 +31,13 @@ import android.os.Looper; import android.os.Message; import android.os.RemoteException; import android.os.ServiceManager; -import android.provider.Settings.System; import android.provider.Settings; +import android.provider.Settings.System; import android.util.Log; import android.view.VolumePanel; +import com.android.internal.telephony.ITelephony; + import java.io.IOException; import java.util.ArrayList; @@ -50,19 +51,19 @@ import java.util.ArrayList; * volume and later persist to the database. Similarly, setting the ringer mode * will update the state and broadcast a change and in a separate thread later * persist the ringer mode. - * + * * @hide */ public class AudioService extends IAudioService.Stub { - + private static final String TAG = "AudioService"; /** How long to delay before persisting a change in volume/ringer mode. */ private static final int PERSIST_DELAY = 3000; - + private Context mContext; private ContentResolver mContentResolver; - + /** The UI */ private VolumePanel mVolumePanel; @@ -75,7 +76,7 @@ public class AudioService extends IAudioService.Stub { private static final int SENDMSG_NOOP = 1; /** If the msg is already queued, queue this one and leave the old. */ private static final int SENDMSG_QUEUE = 2; - + // AudioHandler message.whats private static final int MSG_SET_SYSTEM_VOLUME = 0; private static final int MSG_PERSIST_VOLUME = 1; @@ -91,22 +92,26 @@ public class AudioService extends IAudioService.Stub { private AudioHandler mAudioHandler; /** @see VolumeStreamState */ private VolumeStreamState[] mStreamStates; - + private boolean mMicMute; private int mMode; private int[] mRoutes = new int[AudioSystem.NUM_MODES]; private Object mSettingsLock = new Object(); private boolean mMediaServerOk; - + private SoundPool mSoundPool; private Object mSoundEffectsLock = new Object(); private static final int NUM_SOUNDPOOL_CHANNELS = 4; - private static final float SOUND_EFFECT_VOLUME = 1.0f; - + private static final int SOUND_EFFECT_VOLUME = 1000; + /* Sound effect file names */ private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/"; private static final String[] SOUND_EFFECT_FILES = new String[] { - "Effect_Tick.ogg" + "Effect_Tick.ogg", + "KeypressStandard.ogg", + "KeypressSpacebar.ogg", + "KeypressDelete.ogg", + "KeypressReturn.ogg" }; /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to @@ -117,9 +122,13 @@ public class AudioService extends IAudioService.Stub { {0, -1}, // FX_FOCUS_NAVIGATION_UP {0, -1}, // FX_FOCUS_NAVIGATION_DOWN {0, -1}, // FX_FOCUS_NAVIGATION_LEFT - {0, -1} // FX_FOCUS_NAVIGATION_RIGHT + {0, -1}, // FX_FOCUS_NAVIGATION_RIGHT + {1, -1}, // FX_KEYPRESS_STANDARD + {2, -1}, // FX_KEYPRESS_SPACEBAR + {3, -1}, // FX_FOCUS_DELETE + {4, -1} // FX_FOCUS_RETURN }; - + private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() { public void onError(int error) { switch (error) { @@ -145,7 +154,7 @@ public class AudioService extends IAudioService.Stub { * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL}, * {@link AudioManager#RINGER_MODE_SILENT}, or * {@link AudioManager#RINGER_MODE_VIBRATE}. - */ + */ private int mRingerMode; /** @see System#MODE_RINGER_STREAMS_AFFECTED */ @@ -153,7 +162,7 @@ public class AudioService extends IAudioService.Stub { /** @see System#MUTE_STREAMS_AFFECTED */ private int mMuteAffectedStreams; - + /** * Has multiple bits per vibrate type to indicate the type's vibrate * setting. See {@link #setVibrateSetting(int, int)}. @@ -162,26 +171,24 @@ public class AudioService extends IAudioService.Stub { * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}. */ private int mVibrateSetting; - + /////////////////////////////////////////////////////////////////////////// // Construction /////////////////////////////////////////////////////////////////////////// - + /** @hide */ public AudioService(Context context) { mContext = context; mContentResolver = context.getContentResolver(); mVolumePanel = new VolumePanel(context, this); - + createAudioSystemThread(); createStreamStates(); readPersistedSettings(); readAudioSettings(); mMediaServerOk = true; - AudioSystem.setErrorCallback(mAudioSystemCallback); - if (Settings.System.getInt(mContentResolver, Settings.System.SOUND_EFFECTS_ENABLED, 0) == 1) { - loadSoundEffects(); - } + AudioSystem.setErrorCallback(mAudioSystemCallback); + loadSoundEffects(); } private void createAudioSystemThread() { @@ -189,8 +196,8 @@ public class AudioService extends IAudioService.Stub { mAudioSystemThread.start(); waitForAudioHandlerCreation(); } - - /** Waits for the volume handler to be created by the other thread. */ + + /** Waits for the volume handler to be created by the other thread. */ private void waitForAudioHandlerCreation() { synchronized(this) { while (mAudioHandler == null) { @@ -203,37 +210,51 @@ public class AudioService extends IAudioService.Stub { } } } - + private void createStreamStates() { - final int[] volumeLevelsPhone = createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_VOICE_CALL]); - final int[] volumeLevelsCoarse = createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_SYSTEM]); - final int[] volumeLevelsFine = createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_MUSIC]); - + final int[] volumeLevelsPhone = + createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_VOICE_CALL]); + final int[] volumeLevelsCoarse = + createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_SYSTEM]); + final int[] volumeLevelsFine = + createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_MUSIC]); + final int[] volumeLevelsBtPhone = + createVolumeLevels(0, + AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_BLUETOOTH_SCO]); + int numStreamTypes = AudioSystem.getNumStreamTypes(); VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes]; - + for (int i = 0; i < numStreamTypes; i++) { final int[] levels; - + switch (i) { - + case AudioSystem.STREAM_MUSIC: levels = volumeLevelsFine; break; - + case AudioSystem.STREAM_VOICE_CALL: levels = volumeLevelsPhone; break; - + + case AudioSystem.STREAM_BLUETOOTH_SCO: + levels = volumeLevelsBtPhone; + break; + default: levels = volumeLevelsCoarse; break; } - - streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[i], i, levels); + + if (i == AudioSystem.STREAM_BLUETOOTH_SCO) { + streams[i] = new VolumeStreamState(AudioManager.DEFAULT_STREAM_VOLUME[i], i,levels); + } else { + streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[i], i, levels); + } } } - + private static int[] createVolumeLevels(int offset, int numlevels) { double curve = 1.0f; // 1.4f int [] volumes = new int[numlevels + offset]; @@ -249,7 +270,7 @@ public class AudioService extends IAudioService.Stub { } return volumes; } - + private void readPersistedSettings() { final ContentResolver cr = mContentResolver; @@ -260,19 +281,19 @@ public class AudioService extends IAudioService.Stub { mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0); mMuteAffectedStreams = System.getInt(cr, - System.MUTE_STREAMS_AFFECTED, + System.MUTE_STREAMS_AFFECTED, ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM))); - + // Each stream will read its own persisted settings - + // Broadcast the sticky intent broadcastRingerMode(); - + // Broadcast vibrate settings broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER); broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION); } - + private void readAudioSettings() { synchronized (mSettingsLock) { mMicMute = AudioSystem.isMicrophoneMuted(); @@ -282,7 +303,7 @@ public class AudioService extends IAudioService.Stub { } } } - + private void applyAudioSettings() { synchronized (mSettingsLock) { AudioSystem.muteMicrophone(mMicMute); @@ -291,69 +312,69 @@ public class AudioService extends IAudioService.Stub { AudioSystem.setRouting(mode, mRoutes[mode], AudioSystem.ROUTE_ALL); } } - } - + } + /////////////////////////////////////////////////////////////////////////// // IPC methods /////////////////////////////////////////////////////////////////////////// - + /** @see AudioManager#adjustVolume(int, int) */ public void adjustVolume(int direction, int flags) { adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags); } - + /** @see AudioManager#adjustVolume(int, int, int) */ public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) { int streamType = getActiveStreamType(suggestedStreamType); - + // Don't play sound on other streams if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) { flags &= ~AudioManager.FLAG_PLAY_SOUND; } - + adjustStreamVolume(streamType, direction, flags); } - + /** @see AudioManager#adjustStreamVolume(int, int, int) */ public void adjustStreamVolume(int streamType, int direction, int flags) { ensureValidDirection(direction); ensureValidStreamType(streamType); - + boolean notificationsUseRingVolume = Settings.System.getInt(mContentResolver, Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1) == 1; if (notificationsUseRingVolume && streamType == AudioManager.STREAM_NOTIFICATION) { // Redirect the volume change to the ring stream streamType = AudioManager.STREAM_RING; } - + VolumeStreamState streamState = mStreamStates[streamType]; - final int oldIndex = streamState.mIndex; + final int oldIndex = streamState.mIndex; boolean adjustVolume = true; - + // If either the client forces allowing ringer modes for this adjustment, // or the stream type is one that is affected by ringer modes if ((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0 - || isStreamAffectedByRingerMode(streamType)) { + || streamType == AudioManager.STREAM_RING) { // Check if the ringer mode changes with this volume adjustment. If - // it does, it will handle adjusting the volome, so we won't below + // it does, it will handle adjusting the volume, so we won't below adjustVolume = checkForRingerModeChange(oldIndex, direction); } - + if (adjustVolume && streamState.adjustIndex(direction)) { - + boolean alsoUpdateNotificationVolume = notificationsUseRingVolume && streamType == AudioManager.STREAM_RING; if (alsoUpdateNotificationVolume) { mStreamStates[AudioManager.STREAM_NOTIFICATION].adjustIndex(direction); } - + // Post message to set system volume (it in turn will post a message // to persist). Do not change volume if stream is muted. if (streamState.muteCount() == 0) { sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0, streamState, 0); - + if (alsoUpdateNotificationVolume) { sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, AudioManager.STREAM_NOTIFICATION, SENDMSG_NOOP, 0, 0, mStreamStates[AudioManager.STREAM_NOTIFICATION], 0); @@ -363,12 +384,44 @@ public class AudioService extends IAudioService.Stub { // UI mVolumePanel.postVolumeChanged(streamType, flags); + // Broadcast Intent + sendVolumeUpdate(streamType); } /** @see AudioManager#setStreamVolume(int, int, int) */ public void setStreamVolume(int streamType, int index, int flags) { ensureValidStreamType(streamType); - + syncRingerAndNotificationStreamVolume(streamType, index, false); + + setStreamVolumeInt(streamType, index, false); + + // UI, etc. + mVolumePanel.postVolumeChanged(streamType, flags); + // Broadcast Intent + sendVolumeUpdate(streamType); + } + + private void sendVolumeUpdate(int streamType) { + Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION); + intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType); + intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, getStreamVolume(streamType)); + + // Currently, sending the intent only when the stream is BLUETOOTH_SCO + if (streamType == AudioManager.STREAM_BLUETOOTH_SCO) { + mContext.sendBroadcast(intent); + } + } + + /** + * Sync the STREAM_RING and STREAM_NOTIFICATION volumes if mandated by the + * value in Settings. + * + * @param streamType Type of the stream + * @param index Volume index for the stream + * @param force If true, set the volume even if the current and desired + * volume as same + */ + private void syncRingerAndNotificationStreamVolume(int streamType, int index, boolean force) { boolean notificationsUseRingVolume = Settings.System.getInt(mContentResolver, Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1) == 1; if (notificationsUseRingVolume) { @@ -378,23 +431,24 @@ public class AudioService extends IAudioService.Stub { } if (streamType == AudioManager.STREAM_RING) { // One-off to sync notification volume to ringer volume - setStreamVolumeInt(AudioManager.STREAM_NOTIFICATION, index); + setStreamVolumeInt(AudioManager.STREAM_NOTIFICATION, index, force); } } - - setStreamVolumeInt(streamType, index); - - // UI, etc. - mVolumePanel.postVolumeChanged(streamType, flags); } + /** * Sets the stream state's index, and posts a message to set system volume. * This will not call out to the UI. Assumes a valid stream type. + * + * @param streamType Type of the stream + * @param index Desired volume index of the stream + * @param force If true, set the volume even if the desired volume is same + * as the current volume. */ - private void setStreamVolumeInt(int streamType, int index) { + private void setStreamVolumeInt(int streamType, int index, boolean force) { VolumeStreamState streamState = mStreamStates[streamType]; - if (streamState.setIndex(index)) { + if (streamState.setIndex(index) || force) { // Post message to set system volume (it in turn will post a message // to persist). Do not change volume if stream is muted. if (streamState.muteCount() == 0) { @@ -403,7 +457,7 @@ public class AudioService extends IAudioService.Stub { } } } - + /** @see AudioManager#setStreamSolo(int, boolean) */ public void setStreamSolo(int streamType, boolean state, IBinder cb) { for (int stream = 0; stream < mStreamStates.length; stream++) { @@ -412,7 +466,7 @@ public class AudioService extends IAudioService.Stub { mStreamStates[stream].mute(cb, state); } } - + /** @see AudioManager#setStreamMute(int, boolean) */ public void setStreamMute(int streamType, boolean state, IBinder cb) { if (isStreamAffectedByMute(streamType)) { @@ -441,32 +495,33 @@ public class AudioService extends IAudioService.Stub { public void setRingerMode(int ringerMode) { if (ringerMode != mRingerMode) { mRingerMode = ringerMode; - + // Adjust volumes via posting message int numStreamTypes = AudioSystem.getNumStreamTypes(); if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) { for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (!isStreamAffectedByRingerMode(streamType)) continue; // Bring back last audible volume - setStreamVolumeInt(streamType, mStreamStates[streamType].mLastAudibleIndex); + setStreamVolumeInt(streamType, mStreamStates[streamType].mLastAudibleIndex, + false); } } else { for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (!isStreamAffectedByRingerMode(streamType)) continue; // Either silent or vibrate, either way volume is 0 - setStreamVolumeInt(streamType, 0); + setStreamVolumeInt(streamType, 0, false); } } - + // Send sticky broadcast broadcastRingerMode(); - + // Post a persist ringer mode msg sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG, SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY); } } - + /** @see AudioManager#shouldVibrate(int) */ public boolean shouldVibrate(int vibrateType) { @@ -474,21 +529,21 @@ public class AudioService extends IAudioService.Stub { case AudioManager.VIBRATE_SETTING_ON: return mRingerMode != AudioManager.RINGER_MODE_SILENT; - + case AudioManager.VIBRATE_SETTING_ONLY_SILENT: return mRingerMode == AudioManager.RINGER_MODE_VIBRATE; - + case AudioManager.VIBRATE_SETTING_OFF: - // Phone ringer should always vibrate in vibrate mode + // Phone ringer should always vibrate in vibrate mode if (vibrateType == AudioManager.VIBRATE_TYPE_RINGER) { return mRingerMode == AudioManager.RINGER_MODE_VIBRATE; } - + default: return false; } } - + /** @see AudioManager#getVibrateSetting(int) */ public int getVibrateSetting(int vibrateType) { return (mVibrateSetting >> (vibrateType * 2)) & 3; @@ -498,10 +553,10 @@ public class AudioService extends IAudioService.Stub { public void setVibrateSetting(int vibrateType, int vibrateSetting) { mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting); - + // Broadcast change broadcastVibrateSetting(vibrateType); - + // Post message to set ringer mode (it in turn will post a message // to persist) sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0, @@ -518,13 +573,13 @@ public class AudioService extends IAudioService.Stub { // First clear the existing setting. Each vibrate type has two bits in // the value. Note '3' is '11' in binary. existingValue &= ~(3 << (vibrateType * 2)); - + // Set into the old value existingValue |= (vibrateSetting & 3) << (vibrateType * 2); - + return existingValue; } - + /** @see AudioManager#setMicrophoneMute(boolean) */ public void setMicrophoneMute(boolean on) { if (!checkAudioSettingsPermission("setMicrophoneMute()")) { @@ -534,15 +589,15 @@ public class AudioService extends IAudioService.Stub { if (on != mMicMute) { AudioSystem.muteMicrophone(on); mMicMute = on; - } + } } } - + /** @see AudioManager#isMicrophoneMute() */ public boolean isMicrophoneMute() { return mMicMute; } - + /** @see AudioManager#setMode(int) */ public void setMode(int mode) { if (!checkAudioSettingsPermission("setMode()")) { @@ -552,15 +607,19 @@ public class AudioService extends IAudioService.Stub { if (mode != mMode) { AudioSystem.setMode(mode); mMode = mode; - } + } + int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); + int index = mStreamStates[streamType].mIndex; + syncRingerAndNotificationStreamVolume(streamType, index, true); + setStreamVolumeInt(streamType, index, true); } } - + /** @see AudioManager#getMode() */ public int getMode() { return mMode; } - + /** @see AudioManager#setRouting(int, int, int) */ public void setRouting(int mode, int routes, int mask) { if (!checkAudioSettingsPermission("setRouting()")) { @@ -570,10 +629,14 @@ public class AudioService extends IAudioService.Stub { if ((mRoutes[mode] & mask) != (routes & mask)) { AudioSystem.setRouting(mode, routes, mask); mRoutes[mode] = (mRoutes[mode] & ~mask) | (routes & mask); - } + } + int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); + int index = mStreamStates[streamType].mIndex; + syncRingerAndNotificationStreamVolume(streamType, index, true); + setStreamVolumeInt(streamType, index, true); } } - + /** @see AudioManager#getRouting(int) */ public int getRouting(int mode) { return mRoutes[mode]; @@ -583,7 +646,7 @@ public class AudioService extends IAudioService.Stub { public boolean isMusicActive() { return AudioSystem.isMusicActive(); } - + /** @see AudioManager#setParameter(String, String) */ public void setParameter(String key, String value) { AudioSystem.setParameter(key, value); @@ -591,13 +654,20 @@ public class AudioService extends IAudioService.Stub { /** @see AudioManager#playSoundEffect(int) */ public void playSoundEffect(int effectType) { - sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, effectType, 0, - null, 0); + sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, + effectType, SOUND_EFFECT_VOLUME, null, 0); + } + + /** @see AudioManager#playSoundEffect(int, float) */ + /* @hide FIXME: unhide before release */ + public void playSoundEffectVolume(int effectType, float volume) { + sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, + effectType, (int) (volume * 1000), null, 0); } /** - * Loads samples into the soundpool. - * This method must be called at when sound effects are enabled + * Loads samples into the soundpool. + * This method must be called at when sound effects are enabled */ public boolean loadSoundEffects() { synchronized (mSoundEffectsLock) { @@ -605,17 +675,17 @@ public class AudioService extends IAudioService.Stub { if (mSoundPool == null) { return false; } - /* - * poolId table: The value -1 in this table indicates that corresponding - * file (same index in SOUND_EFFECT_FILES[] has not been loaded. - * Once loaded, the value in poolId is the sample ID and the same + /* + * poolId table: The value -1 in this table indicates that corresponding + * file (same index in SOUND_EFFECT_FILES[] has not been loaded. + * Once loaded, the value in poolId is the sample ID and the same * sample can be reused for another effect using the same file. - */ + */ int[] poolId = new int[SOUND_EFFECT_FILES.length]; for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { poolId[fileIdx] = -1; } - /* + /* * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded. * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0: * this indicates we have a valid sample loaded for this effect. @@ -638,12 +708,12 @@ public class AudioService extends IAudioService.Stub { } } } - + return true; } /** - * Unloads samples from the sound pool. + * Unloads samples from the sound pool. * This method can be called to free some memory when * sound effects are disabled. */ @@ -665,12 +735,12 @@ public class AudioService extends IAudioService.Stub { mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]); SOUND_EFFECT_FILES_MAP[effect][1] = -1; poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1; - } + } } mSoundPool = null; } } - + /////////////////////////////////////////////////////////////////////////// // Internal methods /////////////////////////////////////////////////////////////////////////// @@ -683,7 +753,7 @@ public class AudioService extends IAudioService.Stub { private boolean checkForRingerModeChange(int oldIndex, int direction) { boolean adjustVolumeIndex = true; int newRingerMode = mRingerMode; - + if (mRingerMode == AudioManager.RINGER_MODE_NORMAL && oldIndex == 1 && direction == AudioManager.ADJUST_LOWER) { newRingerMode = AudioManager.RINGER_MODE_VIBRATE; @@ -697,7 +767,7 @@ public class AudioService extends IAudioService.Stub { && mRingerMode == AudioManager.RINGER_MODE_SILENT) { newRingerMode = AudioManager.RINGER_MODE_VIBRATE; } - + if (newRingerMode != mRingerMode) { setRingerMode(newRingerMode); @@ -708,18 +778,18 @@ public class AudioService extends IAudioService.Stub { */ adjustVolumeIndex = false; } - + return adjustVolumeIndex; } - + public boolean isStreamAffectedByRingerMode(int streamType) { - return (mRingerModeAffectedStreams & (1 << streamType)) != 0; + return (mRingerModeAffectedStreams & (1 << streamType)) != 0; } - + public boolean isStreamAffectedByMute(int streamType) { return (mMuteAffectedStreams & (1 << streamType)) != 0; } - + private void ensureValidDirection(int direction) { if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) { throw new IllegalArgumentException("Bad direction " + direction); @@ -736,13 +806,15 @@ public class AudioService extends IAudioService.Stub { boolean isOffhook = false; try { ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); - isOffhook = phone.isOffhook(); + if (phone != null) isOffhook = phone.isOffhook(); } catch (RemoteException e) { Log.w(TAG, "Couldn't connect to phone service", e); } - // TODO: applications can influence this - if (isOffhook) { + if ((getRouting(AudioSystem.MODE_IN_CALL) & AudioSystem.ROUTE_BLUETOOTH_SCO) != 0) { + // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO..."); + return AudioSystem.STREAM_BLUETOOTH_SCO; + } else if (isOffhook) { // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL..."); return AudioSystem.STREAM_VOICE_CALL; } else if (AudioSystem.isMusicActive()) { @@ -756,29 +828,33 @@ public class AudioService extends IAudioService.Stub { return suggestedStreamType; } } - + private void broadcastRingerMode() { // Send sticky broadcast - Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION); - broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode); - long origCallerIdentityToken = Binder.clearCallingIdentity(); - mContext.sendStickyBroadcast(broadcast); - Binder.restoreCallingIdentity(origCallerIdentityToken); + if (ActivityManagerNative.isSystemReady()) { + Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION); + broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode); + long origCallerIdentityToken = Binder.clearCallingIdentity(); + mContext.sendStickyBroadcast(broadcast); + Binder.restoreCallingIdentity(origCallerIdentityToken); + } } - + private void broadcastVibrateSetting(int vibrateType) { // Send broadcast - Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION); - broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType); - broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType)); - mContext.sendBroadcast(broadcast); + if (ActivityManagerNative.isSystemReady()) { + Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION); + broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType); + broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType)); + mContext.sendBroadcast(broadcast); + } } - + // Message helper methods private static int getMsg(int baseMsg, int streamType) { - return (baseMsg & 0xffff) | streamType << 16; + return (baseMsg & 0xffff) | streamType << 16; } - + private static int getMsgBase(int msg) { return msg & 0xffff; } @@ -792,11 +868,11 @@ public class AudioService extends IAudioService.Stub { } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) { return; } - + handler .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay); } - + boolean checkAudioSettingsPermission(String method) { if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS") == PackageManager.PERMISSION_GRANTED) { @@ -809,29 +885,29 @@ public class AudioService extends IAudioService.Stub { return false; } - + /////////////////////////////////////////////////////////////////////////// // Inner classes /////////////////////////////////////////////////////////////////////////// - + public class VolumeStreamState { private final String mVolumeIndexSettingName; - private final String mLastAudibleVolumeIndexSettingName; + private final String mLastAudibleVolumeIndexSettingName; private final int mStreamType; - + private final int[] mVolumes; private int mIndex; private int mLastAudibleIndex; private ArrayList mDeathHandlers; //handles mute/solo requests client death - + private VolumeStreamState(String settingName, int streamType, int[] volumes) { - + mVolumeIndexSettingName = settingName; mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE; - + mStreamType = streamType; mVolumes = volumes; - + final ContentResolver cr = mContentResolver; mIndex = getValidIndex(Settings.System.getInt(cr, mVolumeIndexSettingName, AudioManager.DEFAULT_STREAM_VOLUME[streamType])); mLastAudibleIndex = getValidIndex(Settings.System.getInt(cr, @@ -841,14 +917,31 @@ public class AudioService extends IAudioService.Stub { mDeathHandlers = new ArrayList(); } + /** + * Constructor to be used when there is no setting associated with the VolumeStreamState. + * + * @param defaultVolume Default volume of the stream to use. + * @param streamType Type of the stream. + * @param volumes Volumes levels associated with this stream. + */ + private VolumeStreamState(int defaultVolume, int streamType, int[] volumes) { + mVolumeIndexSettingName = null; + mLastAudibleVolumeIndexSettingName = null; + mIndex = mLastAudibleIndex = defaultVolume; + mStreamType = streamType; + mVolumes = volumes; + AudioSystem.setVolume(mStreamType, defaultVolume); + mDeathHandlers = new ArrayList(); + } + public boolean adjustIndex(int deltaIndex) { return setIndex(mIndex + deltaIndex); } - + public boolean setIndex(int index) { int oldIndex = mIndex; mIndex = getValidIndex(index); - + if (oldIndex != mIndex) { if (mIndex > 0) { mLastAudibleIndex = mIndex; @@ -858,11 +951,11 @@ public class AudioService extends IAudioService.Stub { return false; } } - + public int getMaxIndex() { return mVolumes.length - 1; } - + public void mute(IBinder cb, boolean state) { VolumeDeathHandler handler = getDeathHandler(cb, state); if (handler == null) { @@ -871,17 +964,17 @@ public class AudioService extends IAudioService.Stub { } handler.mute(state); } - + private int getValidIndex(int index) { if (index < 0) { return 0; } else if (index >= mVolumes.length) { return mVolumes.length - 1; } - + return index; } - + private class VolumeDeathHandler implements IBinder.DeathRecipient { private IBinder mICallback; // To be notified of client's death private int mMuteCount; // Number of active mutes for this client @@ -924,7 +1017,7 @@ public class AudioService extends IAudioService.Stub { mDeathHandlers.remove(this); mICallback.unlinkToDeath(this, 0); if (muteCount() == 0) { - // If the stream is not mut any more, restore it's volume if + // If the stream is not mut any more, restore it's volume if // ringer mode allows it if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) { setIndex(mLastAudibleIndex); @@ -980,68 +1073,68 @@ public class AudioService extends IAudioService.Stub { } } } - + /** Thread that handles native AudioSystem control. */ private class AudioSystemThread extends Thread { AudioSystemThread() { super("AudioService"); } - + @Override public void run() { // Set this thread up so the handler will work on it Looper.prepare(); - + synchronized(AudioService.this) { mAudioHandler = new AudioHandler(); // Notify that the handler has been created AudioService.this.notify(); } - + // Listen for volume change requests that are set by VolumePanel Looper.loop(); } } - + /** Handles internal volume messages in separate volume thread. */ private class AudioHandler extends Handler { - + private void setSystemVolume(VolumeStreamState streamState) { - + // Adjust volume AudioSystem .setVolume(streamState.mStreamType, streamState.mVolumes[streamState.mIndex]); - + // Post a persist volume msg sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType, SENDMSG_REPLACE, 0, 0, streamState, PERSIST_DELAY); } - + private void persistVolume(VolumeStreamState streamState) { System.putInt(mContentResolver, streamState.mVolumeIndexSettingName, streamState.mIndex); System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName, streamState.mLastAudibleIndex); } - + private void persistRingerMode() { System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode); } - + private void persistVibrateSetting() { System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting); } - - private void playSoundEffect(int effectType) { + + private void playSoundEffect(int effectType, int volume) { synchronized (mSoundEffectsLock) { if (mSoundPool == null) { return; } if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) { - mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], SOUND_EFFECT_VOLUME, SOUND_EFFECT_VOLUME, - 0, 0, 1.0f); + float v = (float) volume / 1000.0f; + mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], v, v, 0, 0, 1.0f); } else { MediaPlayer mediaPlayer = new MediaPlayer(); if (mediaPlayer != null) { @@ -1084,36 +1177,36 @@ public class AudioService extends IAudioService.Stub { } } } - + @Override public void handleMessage(Message msg) { int baseMsgWhat = getMsgBase(msg.what); - + switch (baseMsgWhat) { - + case MSG_SET_SYSTEM_VOLUME: setSystemVolume((VolumeStreamState) msg.obj); break; - + case MSG_PERSIST_VOLUME: persistVolume((VolumeStreamState) msg.obj); break; - + case MSG_PERSIST_RINGER_MODE: persistRingerMode(); break; - + case MSG_PERSIST_VIBRATE_SETTING: persistVibrateSetting(); break; - + case MSG_MEDIA_SERVER_DIED: Log.e(TAG, "Media server died."); - // Force creation of new IAudioflinger interface + // Force creation of new IAudioflinger interface mMediaServerOk = false; AudioSystem.getMode(); break; - + case MSG_MEDIA_SERVER_STARTED: Log.e(TAG, "Media server started."); // Restore audio routing and stream volumes @@ -1134,10 +1227,10 @@ public class AudioService extends IAudioService.Stub { break; case MSG_PLAY_SOUND_EFFECT: - playSoundEffect(msg.arg1); + playSoundEffect(msg.arg1, msg.arg2); break; } } } - + } diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java index 37100677329f8cbfe7bd00b33b9334accbcbad15..d0fa7953dd210add1ab1c62b5a597927db95bf34 100644 --- a/media/java/android/media/AudioSystem.java +++ b/media/java/android/media/AudioSystem.java @@ -43,15 +43,17 @@ public class AudioSystem public static final int STREAM_ALARM = 4; /* The audio stream for notifications */ public static final int STREAM_NOTIFICATION = 5; + /* @hide The audio stream for phone calls when connected on bluetooth */ + public static final int STREAM_BLUETOOTH_SCO = 6; /** * @deprecated Use {@link #numStreamTypes() instead} */ public static final int NUM_STREAMS = 5; // Expose only the getter method publicly so we can change it in the future - private static final int NUM_STREAM_TYPES = 6; + private static final int NUM_STREAM_TYPES = 7; public static final int getNumStreamTypes() { return NUM_STREAM_TYPES; } - + /* max and min volume levels */ /* Maximum volume setting, for use with setVolume(int,int) */ public static final int MAX_VOLUME = 100; @@ -78,7 +80,7 @@ public class AudioSystem /* * Sets the microphone mute on or off. * - * param on set true to mute the microphone; + * param on set true to mute the microphone; * false to turn mute off * return command completion status see AUDIO_STATUS_OK, see AUDIO_STATUS_ERROR */ @@ -116,18 +118,18 @@ public class AudioSystem public static final int MODE_RINGTONE = 1; public static final int MODE_IN_CALL = 2; public static final int NUM_MODES = 3; - + /* Routing bits for setRouting/getRouting API */ public static final int ROUTE_EARPIECE = (1 << 0); public static final int ROUTE_SPEAKER = (1 << 1); - - /** @deprecated use {@link #ROUTE_BLUETOOTH_SCO} */ + + /** @deprecated use {@link #ROUTE_BLUETOOTH_SCO} */ @Deprecated public static final int ROUTE_BLUETOOTH = (1 << 2); public static final int ROUTE_BLUETOOTH_SCO = (1 << 2); public static final int ROUTE_HEADSET = (1 << 3); public static final int ROUTE_BLUETOOTH_A2DP = (1 << 4); - public static final int ROUTE_ALL = 0xFFFFFFFF; + public static final int ROUTE_ALL = 0xFFFFFFFF; /* * Sets the audio routing for a specified mode @@ -185,7 +187,7 @@ public class AudioSystem public static final int AUDIO_STATUS_ERROR = 1; /* Media server died. see ErrorCallback */ public static final int AUDIO_STATUS_SERVER_DIED = 100; - + private static ErrorCallback mErrorCallback; /* @@ -211,7 +213,7 @@ public class AudioSystem { mErrorCallback = cb; } - + private static void errorCallbackFromNative(int error) { if (mErrorCallback != null) { diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java index 2b7656f1dd860dd1ab6e12129fe59b82a88675f5..316fa7a5f92eeda54117ae8694c33b39cd9b8568 100644 --- a/media/java/android/media/AudioTrack.java +++ b/media/java/android/media/AudioTrack.java @@ -30,12 +30,31 @@ import android.util.Log; /** * The AudioTrack class manages and plays a single audio resource for Java applications. * It allows to stream PCM audio buffers to the audio hardware for playback. This is - * be achieved by "pushing" the data to the AudioTrack object using the - * {@link #write(byte[], int, int)} or {@link #write(short[], int, int)} method. - * During construction, an AudioTrack object can be initialized with a given buffer. - * This size determines how long an AudioTrack can play before running out of data. - * - * {@hide Pending API council review} + * achieved by "pushing" the data to the AudioTrack object using one of the + * {@link #write(byte[], int, int)} and {@link #write(short[], int, int)} methods. + *

                An AudioTrack instance can operate under two modes: static of streaming.
                + * The Streaming mode consists in continuously writing data to the AudioTrack, using one + * of the write() methods. These are blocking and return when the data has been transferred + * from the Java layer to the native layer, and is queued for playback. The streaming mode + * is most useful when playing blocks of audio data that for instance are: + *

                  + *
                • too big to fit in memory because of the duration of the sound to play,
                • + *
                • too big to fit in memory because of the characteristics of the audio data + * (high sampling rate, bits per sample ...)
                • + *
                • chosen, received or generated as the audio keeps playing.
                • + *
                + * The static mode is to be chosen when dealing with short sounds that fit in memory and + * that need to be played with the smallest latency possible. Static mode AudioTrack instances can + * play the sound without the need to transfer the audio data from Java to the audio hardware + * each time the sound is to be played. The static mode will therefore be preferred for UI and + * game sounds that are played often, and with the smallest overhead possible. + *

                Upon creation, an AudioTrack object initializes its associated audio buffer. + * The size of this buffer, specified during the construction, determines how long an AudioTrack + * can play before running out of data.
                + * For an AudioTrack using the static mode, this size is the maximum size of the sound that can + * be played from it.
                + * For the streaming mode, data will be written to the hardware in chunks of + * sizes inferior to the total buffer size. */ public class AudioTrack { @@ -46,42 +65,41 @@ public class AudioTrack private static final float VOLUME_MIN = 0.0f; /** Maximum value for a channel volume */ private static final float VOLUME_MAX = 1.0f; - + /** state of an AudioTrack this is stopped */ public static final int PLAYSTATE_STOPPED = 1; // matches SL_PLAYSTATE_STOPPED /** state of an AudioTrack this is paused */ public static final int PLAYSTATE_PAUSED = 2; // matches SL_PLAYSTATE_PAUSED /** state of an AudioTrack this is playing */ public static final int PLAYSTATE_PLAYING = 3; // matches SL_PLAYSTATE_PLAYING - - /** - * Creation mode where audio data is transferred from Java to the native layer + + /** + * Creation mode where audio data is transferred from Java to the native layer * only once before the audio starts playing. */ public static final int MODE_STATIC = 0; - /** - * Creation mode where audio data is streamed from Java to the native layer + /** + * Creation mode where audio data is streamed from Java to the native layer * as the audio is playing. */ public static final int MODE_STREAM = 1; - - /** - * State of an AudioTrack that was not successfully initialized upon creation + + /** + * State of an AudioTrack that was not successfully initialized upon creation */ public static final int STATE_UNINITIALIZED = 0; - /** + /** * State of an AudioTrack that is ready to be used. */ public static final int STATE_INITIALIZED = 1; /** - * State of a successfully initialized AudioTrack that uses static data, + * State of a successfully initialized AudioTrack that uses static data, * but that hasn't received that data yet. */ public static final int STATE_NO_STATIC_DATA = 2; - - // to keep in sync with libs/android_runtime/android_media_AudioTrack.cpp - // error codes + // Error codes: + // to keep in sync with frameworks/base/core/jni/android_media_AudioTrack.cpp /** * Denotes a successful operation. */ @@ -90,139 +108,137 @@ public class AudioTrack * Denotes a generic operation failure. */ public static final int ERROR = -1; - private static final int ERROR_NATIVESETUP_AUDIOSYSTEM = -2; - private static final int ERROR_NATIVESETUP_INVALIDCHANNELCOUNT = -3; - private static final int ERROR_NATIVESETUP_INVALIDFORMAT = -4; - private static final int ERROR_NATIVESETUP_INVALIDSTREAMTYPE = -5; - private static final int ERROR_NATIVESETUP_NATIVEINITFAILED = -6; /** * Denotes a failure due to the use of an invalid value. */ - public static final int ERROR_BAD_VALUE = -7; + public static final int ERROR_BAD_VALUE = -2; /** * Denotes a failure due to the improper use of a method. */ - public static final int ERROR_INVALID_OPERATION = -8; - // events + public static final int ERROR_INVALID_OPERATION = -3; + + private static final int ERROR_NATIVESETUP_AUDIOSYSTEM = -16; + private static final int ERROR_NATIVESETUP_INVALIDCHANNELCOUNT = -17; + private static final int ERROR_NATIVESETUP_INVALIDFORMAT = -18; + private static final int ERROR_NATIVESETUP_INVALIDSTREAMTYPE = -19; + private static final int ERROR_NATIVESETUP_NATIVEINITFAILED = -20; + + // Events: + // to keep in sync with frameworks/base/include/media/AudioTrack.h /** * Event id for when the playback head has reached a previously set marker. */ - protected static final int NATIVE_EVENT_MARKER = 3; + private static final int NATIVE_EVENT_MARKER = 3; /** * Event id for when the previously set update period has passed during playback. */ - protected static final int NATIVE_EVENT_NEW_POS = 4; - + private static final int NATIVE_EVENT_NEW_POS = 4; + private final static String TAG = "AudioTrack-Java"; - + //-------------------------------------------------------------------------- // Member variables //-------------------- /** * Indicates the state of the AudioTrack instance */ - protected int mState = STATE_UNINITIALIZED; + private int mState = STATE_UNINITIALIZED; /** * Indicates the play state of the AudioTrack instance */ - protected int mPlayState = PLAYSTATE_STOPPED; + private int mPlayState = PLAYSTATE_STOPPED; /** * Lock to make sure mPlayState updates are reflecting the actual state of the object. */ - protected final Object mPlayStateLock = new Object(); - /** - * The listener the AudioTrack notifies previously set marker is reached. - * @see #setMarkerReachedListener(OnMarkerReachedListener) - */ - protected OnMarkerReachedListener mMarkerListener = null; + private final Object mPlayStateLock = new Object(); /** - * Lock to protect marker listener updates against event notifications + * The listener the AudioTrack notifies when the playback position reaches a marker + * or for periodic updates during the progression of the playback head. + * @see #setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener) */ - protected final Object mMarkerListenerLock = new Object(); + private OnPlaybackPositionUpdateListener mPositionListener = null; /** - * The listener the AudioTrack notifies periodically during playback. - * @see #setPeriodicNotificationListener(OnPeriodicNotificationListener) + * Lock to protect event listener updates against event notifications */ - protected OnPeriodicNotificationListener mPeriodicListener = null; - /** - * Lock to protect periodic listener updates against event notifications - */ - protected final Object mPeriodicListenerLock = new Object(); + private final Object mPositionListenerLock = new Object(); /** * Size of the native audio buffer. */ - protected int mNativeBufferSizeInBytes = 0; + private int mNativeBufferSizeInBytes = 0; /** - * Handler for events coming from the native code + * Handler for marker events coming from the native code */ - protected NativeEventHandler mNativeEventHandler = null; + private NativeEventHandlerDelegate mEventHandlerDelegate = null; /** * The audio data sampling rate in Hz. */ - protected int mSampleRate = 22050; + private int mSampleRate = 22050; /** * The number of input audio channels (1 is mono, 2 is stereo) */ - protected int mChannelCount = 1; + private int mChannelCount = 1; /** * The type of the audio stream to play. See - * {@link AudioManager.STREAM_VOICE_CALL}, {@link AudioManager.STREAM_SYSTEM}, - * {@link AudioManager.STREAM_RING}, {@link AudioManager.STREAM_MUSIC} and - * {@link AudioManager.STREAM_ALARM} + * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, + * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC} and + * {@link AudioManager#STREAM_ALARM} */ - protected int mStreamType = AudioManager.STREAM_MUSIC; + private int mStreamType = AudioManager.STREAM_MUSIC; /** * The way audio is consumed by the hardware, streaming or static. */ - protected int mDataLoadMode = MODE_STREAM; + private int mDataLoadMode = MODE_STREAM; /** * The current audio channel configuration */ - protected int mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; + private int mChannelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; /** * The encoding of the audio samples. - * @see #AudioFormat.ENCODING_PCM_8BIT - * @see #AudioFormat.ENCODING_PCM_16BIT + * @see AudioFormat#ENCODING_PCM_8BIT + * @see AudioFormat#ENCODING_PCM_16BIT */ - protected int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; + private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; //-------------------------------- // Used exclusively by native code //-------------------- - /** - * Accessed by native methods: provides access to C++ AudioTrack object + /** + * Accessed by native methods: provides access to C++ AudioTrack object */ @SuppressWarnings("unused") private int mNativeTrackInJavaObj; - /** + /** * Accessed by native methods: provides access to the JNI data (i.e. resources used by * the native AudioTrack object, but not stored in it). */ @SuppressWarnings("unused") private int mJniData; - - + + //-------------------------------------------------------------------------- // Constructor, Finalize //-------------------- /** * Class constructor. - * @param streamType the type of the audio stream. See - * {@link AudioSystem.STREAM_VOICE_CALL}, {@link AudioSystem.STREAM_SYSTEM}, - * {@link AudioSystem.STREAM_RING}, {@link AudioSystem.STREAM_MUSIC} and - * {@link AudioSystem.STREAM_ALARM} + * @param streamType the type of the audio stream. See + + * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, + * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC} and + * {@link AudioManager#STREAM_ALARM} * @param sampleRateInHz the sample rate expressed in Hertz. Examples of rates are (but * not limited to) 44100, 22050 and 11025. - * @param channelConfig describes the configuration of the audio channels. - * See {@link AudioFormat.CHANNEL_CONFIGURATION_MONO} and - * {@link AudioFormat.CHANNEL_CONFIGURATION_STEREO} - * @param audioFormat the format in which the audio data is represented. - * See {@link AudioFormat.ENCODING_PCM_16BIT} and - * {@link AudioFormat.ENCODING_PCM_8BIT} + * @param channelConfig describes the configuration of the audio channels. + + * See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} and + * {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO} + + * @param audioFormat the format in which the audio data is represented. + * See {@link AudioFormat#ENCODING_PCM_16BIT} and + * {@link AudioFormat#ENCODING_PCM_8BIT} * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is read - * from for playback. If using the AudioTrack in streaming mode, you can write data into + * from for playback. If using the AudioTrack in streaming mode, you can write data into * this buffer in smaller chunks than this size. If using the AudioTrack in static mode, * this is the maximum size of the sound that will be played for this instance. * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM} @@ -230,7 +246,7 @@ public class AudioTrack */ public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode) - throws IllegalArgumentException { + throws IllegalArgumentException { mState = STATE_UNINITIALIZED; audioParamCheck(streamType, sampleRateInHz, channelConfig, audioFormat, mode); @@ -238,8 +254,8 @@ public class AudioTrack audioBuffSizeCheck(bufferSizeInBytes); // native initialization - int initResult = native_setup(new WeakReference(this), - mStreamType, mSampleRate, mChannelCount, mAudioFormat, + int initResult = native_setup(new WeakReference(this), + mStreamType, mSampleRate, mChannelCount, mAudioFormat, mNativeBufferSizeInBytes, mDataLoadMode); if (initResult != SUCCESS) { loge("Error code "+initResult+" when initializing AudioTrack."); @@ -252,8 +268,8 @@ public class AudioTrack mState = STATE_INITIALIZED; } } - - + + // Convenience method for the constructor's parameter checks. // This is where constructor IllegalArgumentException-s are thrown // postconditions: @@ -262,25 +278,27 @@ public class AudioTrack // mAudioFormat is valid // mSampleRate is valid // mDataLoadMode is valid - private void audioParamCheck(int streamType, int sampleRateInHz, + private void audioParamCheck(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int mode) { - + //-------------- // stream type if( (streamType != AudioManager.STREAM_ALARM) && (streamType != AudioManager.STREAM_MUSIC) && (streamType != AudioManager.STREAM_RING) && (streamType != AudioManager.STREAM_SYSTEM) - && (streamType != AudioManager.STREAM_VOICE_CALL) && (streamType != AudioManager.STREAM_NOTIFICATION) ) { + && (streamType != AudioManager.STREAM_VOICE_CALL) + && (streamType != AudioManager.STREAM_NOTIFICATION) + && (streamType != AudioManager.STREAM_BLUETOOTH_SCO)) { throw (new IllegalArgumentException("Invalid stream type.")); } else { mStreamType = streamType; } - + //-------------- // sample rate if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) { throw (new IllegalArgumentException(sampleRateInHz + "Hz is not a supported sample rate.")); - } else { + } else { mSampleRate = sampleRateInHz; } @@ -314,10 +332,10 @@ public class AudioTrack break; default: mAudioFormat = AudioFormat.ENCODING_INVALID; - throw(new IllegalArgumentException("Unsupported sample encoding." + throw(new IllegalArgumentException("Unsupported sample encoding." + " Should be ENCODING_PCM_8BIT or ENCODING_PCM_16BIT.")); } - + //-------------- // audio load mode if ( (mode != MODE_STREAM) && (mode != MODE_STATIC) ) { @@ -326,8 +344,8 @@ public class AudioTrack mDataLoadMode = mode; } } - - + + // Convenience method for the contructor's audio buffer size check. // preconditions: // mChannelCount is valid @@ -335,41 +353,29 @@ public class AudioTrack // postcondition: // mNativeBufferSizeInBytes is valid (multiple of frame size, positive) private void audioBuffSizeCheck(int audioBufferSize) { - // NB: this section is only valid with PCM data. + // NB: this section is only valid with PCM data. // To update when supporting compressed formats - int frameSizeInBytes = mChannelCount + int frameSizeInBytes = mChannelCount * (mAudioFormat == AudioFormat.ENCODING_PCM_8BIT ? 1 : 2); if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) { throw (new IllegalArgumentException("Invalid audio buffer size.")); } - + mNativeBufferSizeInBytes = audioBufferSize; } - - - // Convenience method for the creation of the native event handler - // It is called only when a non-null event listener is set. - // precondition: - // mNativeEventHandler is null - private void createNativeEventHandler() { - Looper looper; - if ((looper = Looper.myLooper()) != null) { - mNativeEventHandler = new NativeEventHandler(this, looper); - } else if ((looper = Looper.getMainLooper()) != null) { - mNativeEventHandler = new NativeEventHandler(this, looper); - } else { - mNativeEventHandler = null; - } - } - - + + /** * Releases the native AudioTrack resources. */ public void release() { // even though native_release() stops the native AudioTrack, we need to stop // AudioTrack subclasses too. - stop(); + try { + stop(); + } catch(IllegalStateException ise) { + // don't raise an exception, we're releasing the resources. + } native_release(); mState = STATE_UNINITIALIZED; } @@ -377,7 +383,7 @@ public class AudioTrack @Override protected void finalize() { native_finalize(); - } + } //-------------------------------------------------------------------------- // Getters @@ -390,7 +396,7 @@ public class AudioTrack static public float getMinVolume() { return AudioTrack.VOLUME_MIN; } - + /** * Returns the maximum valid volume value. Volume values set above this one will * be clamped at this value. @@ -398,37 +404,47 @@ public class AudioTrack */ static public float getMaxVolume() { return AudioTrack.VOLUME_MAX; - } - + } + /** * Returns the configured audio data sample rate in Hz */ public int getSampleRate() { return mSampleRate; } + + /** + * @hide + * Returns the current playback rate in Hz. Note that this rate may differ from one set using + * {@link #setPlaybackRate(int)} as the value effectively set is implementation-dependent. + */ + public int getPlaybackRate() { + return native_get_playback_rate(); + } /** - * Returns the configured audio data format. See {@link #AudioFormat.ENCODING_PCM_16BIT} - * and {@link #AudioFormat.ENCODING_PCM_8BIT}. + * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT} + * and {@link AudioFormat#ENCODING_PCM_8BIT}. */ public int getAudioFormat() { return mAudioFormat; } - + /** * Returns the type of audio stream this AudioTrack is configured for. - * Compare the result against {@link AudioManager.STREAM_VOICE_CALL}, - * {@link AudioManager.STREAM_SYSTEM}, {@link AudioManager.STREAM_RING}, - * {@link AudioManager.STREAM_MUSIC} or {@link AudioManager.STREAM_ALARM} + * Compare the result against {@link AudioManager#STREAM_VOICE_CALL}, + * {@link AudioManager#STREAM_SYSTEM}, {@link AudioManager#STREAM_RING}, + * {@link AudioManager#STREAM_MUSIC} or {@link AudioManager#STREAM_ALARM} */ public int getStreamType() { return mStreamType; } /** - * Returns the configured channel configuration. - * See {@link #AudioFormat.CHANNEL_CONFIGURATION_MONO} - * and {@link #AudioFormat.CHANNEL_CONFIGURATION_STEREO}. + * Returns the configured channel configuration. + + * See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} + * and {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO}. */ public int getChannelConfiguration() { return mChannelConfiguration; @@ -443,19 +459,19 @@ public class AudioTrack /** * Returns the state of the AudioTrack instance. This is useful after the - * AudioTrack instance has been created to check if it was initialized + * AudioTrack instance has been created to check if it was initialized * properly. This ensures that the appropriate hardware resources have been * acquired. */ public int getState() { return mState; } - + /** * Returns the playback state of the AudioTrack instance. - * @see AudioTrack.PLAYSTATE_STOPPED - * @see AudioTrack.PLAYSTATE_PAUSED - * @see AudioTrack.PLAYSTATE_PLAYING + * @see #PLAYSTATE_STOPPED + * @see #PLAYSTATE_PAUSED + * @see #PLAYSTATE_PLAYING */ public int getPlayState() { return mPlayState; @@ -492,56 +508,100 @@ public class AudioTrack /** * Returns the hardware output sample rate */ - static public int getNativeOutputSampleRate() { - return native_get_output_sample_rate(); + static public int getNativeOutputSampleRate(int streamType) { + return native_get_output_sample_rate(streamType); } - - //-------------------------------------------------------------------------- - // Initialization / configuration - //-------------------- /** - * Sets the listener the AudioTrack notifies when a previously set marker is reached. - * @param listener + * {@hide} + * Returns the minimum buffer size required for the successful creation of an AudioTrack + * object to be created in the {@link #MODE_STREAM} mode. + * @param sampleRateInHz the sample rate expressed in Hertz. + * @param channelConfig describes the configuration of the audio channels. + * See {@link AudioFormat#CHANNEL_CONFIGURATION_MONO} and + * {@link AudioFormat#CHANNEL_CONFIGURATION_STEREO} + * @param audioFormat the format in which the audio data is represented. + * See {@link AudioFormat#ENCODING_PCM_16BIT} and + * {@link AudioFormat#ENCODING_PCM_8BIT} + * @return {@link #ERROR_BAD_VALUE} if an invalid parameter was passed, + * or {@link #ERROR} if the implementation was unable to query the hardware for its output + * properties, + * or the minimum buffer size expressed in number of bytes. */ - public void setMarkerReachedListener(OnMarkerReachedListener listener) { - synchronized (mMarkerListenerLock) { - mMarkerListener = listener; + static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) { + int channelCount = 0; + switch(channelConfig) { + case AudioFormat.CHANNEL_CONFIGURATION_MONO: + channelCount = 1; + break; + case AudioFormat.CHANNEL_CONFIGURATION_STEREO: + channelCount = 2; + break; + default: + loge("getMinBufferSize(): Invalid channel configuration."); + return AudioTrack.ERROR_BAD_VALUE; } - if ((listener != null) && (mNativeEventHandler == null)) { - createNativeEventHandler(); + + if ((audioFormat != AudioFormat.ENCODING_PCM_16BIT) + && (audioFormat != AudioFormat.ENCODING_PCM_8BIT)) { + loge("getMinBufferSize(): Invalid audio format."); + return AudioTrack.ERROR_BAD_VALUE; + } + + if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) { + loge("getMinBufferSize(): " + sampleRateInHz +"Hz is not a supported sample rate."); + return AudioTrack.ERROR_BAD_VALUE; + } + + int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat); + if ((size == -1) || (size == 0)) { + loge("getMinBufferSize(): error querying hardware"); + return AudioTrack.ERROR; + } + else { + return size; } } - - + + + //-------------------------------------------------------------------------- + // Initialization / configuration + //-------------------- /** - * Sets the listener the AudioTrack notifies periodically during playback. + * Sets the listener the AudioTrack notifies when a previously set marker is reached or + * for each periodic playback head position update. * @param listener */ - public void setPeriodicNotificationListener(OnPeriodicNotificationListener listener) { - synchronized (mPeriodicListenerLock) { - mPeriodicListener = listener; + public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener) { + setPlaybackPositionUpdateListener(listener, null); + } + + + public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener, + Handler handler) { + synchronized (mPositionListenerLock) { + mPositionListener = listener; } - if ((listener != null) && (mNativeEventHandler == null)) { - createNativeEventHandler(); + if (listener != null) { + mEventHandlerDelegate = new NativeEventHandlerDelegate(this, handler); } + } - - - /** - * Sets the specified left/right output volume values on the AudioTrack. Values are clamped + + + + /** + * Sets the specified left/right output volume values on the AudioTrack. Values are clamped * to the ({@link #getMinVolume()}, {@link #getMaxVolume()}) interval if outside this range. - * @param leftVolume output attenuation for the left channel. A value of 0.0f is silence, + * @param leftVolume output attenuation for the left channel. A value of 0.0f is silence, * a value of 1.0f is no attenuation. * @param rightVolume output attenuation for the right channel - * @return {@link #SUCCESS} - * @throws IllegalStateException + * @return error code or success, see {@link #SUCCESS}, + * {@link #ERROR_INVALID_OPERATION} */ - public int setStereoVolume(float leftVolume, float rightVolume) - throws IllegalStateException { + public int setStereoVolume(float leftVolume, float rightVolume) { if (mState != STATE_INITIALIZED) { - throw(new IllegalStateException("setStereoVolume() called on an "+ - "uninitialized AudioTrack.")); + return ERROR_INVALID_OPERATION; } // clamp the volumes @@ -559,84 +619,108 @@ public class AudioTrack } native_setVolume(leftVolume, rightVolume); - + return SUCCESS; } - - + + /** * Sets the playback sample rate for this track. This sets the sampling rate at which * the audio data will be consumed and played back, not the original sampling rate of the * content. Setting it to half the sample rate of the content will cause the playback to * last twice as long, but will also result result in a negative pitch shift. * The current implementation supports a maximum sample rate of twice the hardware output - * sample rate (see {@link #getNativeOutputSampleRate()}). Use {@link #getSampleRate()} to + * sample rate (see {@link #getNativeOutputSampleRate(int)}). Use {@link #getSampleRate()} to * check the rate actually used in hardware after potential clamping. * @param sampleRateInHz - * @return {@link #SUCCESS} + * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, + * {@link #ERROR_INVALID_OPERATION} */ public int setPlaybackRate(int sampleRateInHz) { + if (mState != STATE_INITIALIZED) { + return ERROR_INVALID_OPERATION; + } + if (sampleRateInHz <= 0) { + return ERROR_BAD_VALUE; + } native_set_playback_rate(sampleRateInHz); return SUCCESS; } - - + + /** - * + * * @param markerInFrames marker in frames * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, - * {@link #ERROR_INVALID_OPERATION} + * {@link #ERROR_INVALID_OPERATION} */ public int setNotificationMarkerPosition(int markerInFrames) { + if (mState != STATE_INITIALIZED) { + return ERROR_INVALID_OPERATION; + } return native_set_marker_pos(markerInFrames); } - - + + /** * @param periodInFrames update period in frames * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION} */ public int setPositionNotificationPeriod(int periodInFrames) { + if (mState != STATE_INITIALIZED) { + return ERROR_INVALID_OPERATION; + } return native_set_pos_update_period(periodInFrames); } - - + + /** * Sets the playback head position. The track must be stopped for the position to be changed. * @param positionInFrames playback head position in frames - * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE} - * @throws java.lang.IllegalStateException if the track is not in - * the {@link #PLAYSTATE_STOPPED} state. + * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, + * {@link #ERROR_INVALID_OPERATION} */ - public int setPlaybackHeadPosition(int positionInFrames) - throws IllegalStateException { + public int setPlaybackHeadPosition(int positionInFrames) { synchronized(mPlayStateLock) { - if(mPlayState == PLAYSTATE_STOPPED) { + if ((mPlayState == PLAYSTATE_STOPPED) || (mPlayState == PLAYSTATE_PAUSED)) { return native_set_position(positionInFrames); + } else { + return ERROR_INVALID_OPERATION; } } - throw(new IllegalStateException("setPlaybackHeadPosition() called on a track that is "+ - "not in the PLAYSTATE_STOPPED play state.")); } - + /** * Sets the loop points and the loop count. The loop can be infinite. * @param startInFrames loop start marker in frames * @param endInFrames loop end marker in frames - * @param loopCount the number of times the loop is looped. + * @param loopCount the number of times the loop is looped. * A value of -1 means infinite looping. - * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE} + * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, + * {@link #ERROR_INVALID_OPERATION} */ public int setLoopPoints(int startInFrames, int endInFrames, int loopCount) { + if (mDataLoadMode == MODE_STREAM) { + return ERROR_INVALID_OPERATION; + } return native_set_loop(startInFrames, endInFrames, loopCount); } + /** + * Sets the initialization state of the instance. To be used in an AudioTrack subclass + * constructor to set a subclass-specific post-initialization state. + * @param state the state of the AudioTrack instance + */ + protected void setState(int state) { + mState = state; + } + //--------------------------------------------------------- // Transport control methods //-------------------- /** - * Starts playing an AudioTrack. + * Starts playing an AudioTrack. * @throws IllegalStateException */ public void play() @@ -644,7 +728,7 @@ public class AudioTrack if (mState != STATE_INITIALIZED) { throw(new IllegalStateException("play() called on uninitialized AudioTrack.")); } - + synchronized(mPlayStateLock) { native_start(); mPlayState = PLAYSTATE_PLAYING; @@ -671,7 +755,7 @@ public class AudioTrack /** * Pauses the playback of the audio data. * @throws IllegalStateException - */ + */ public void pause() throws IllegalStateException { if (mState != STATE_INITIALIZED) { @@ -685,25 +769,21 @@ public class AudioTrack mPlayState = PLAYSTATE_PAUSED; } } - - + + //--------------------------------------------------------- // Audio data supply //-------------------- /** * Flushes the audio data currently queued for playback. - * @throws IllegalStateException - */ - public void flush() - throws IllegalStateException { - if (mState != STATE_INITIALIZED) { - throw(new IllegalStateException("flush() called on uninitialized AudioTrack.")); - } - //logd("flush()"); + */ - // flush the data in native layer - native_flush(); + public void flush() { + if (mState == STATE_INITIALIZED) { + // flush the data in native layer + native_flush(); + } } @@ -712,53 +792,61 @@ public class AudioTrack * @param audioData the array that holds the data to play. * @param offsetInBytes the offset in audioData where the data to play starts. * @param sizeInBytes the number of bytes to read in audioData after the offset. - * @return the number of bytes that were written. - * @throws IllegalStateException - */ - public int write(byte[] audioData,int offsetInBytes, int sizeInBytes) - throws IllegalStateException { - if ((mDataLoadMode == MODE_STATIC) + * @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION} + * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if + * the parameters don't resolve to valid data and indexes. + */ + + public int write(byte[] audioData,int offsetInBytes, int sizeInBytes) { + if ((mDataLoadMode == MODE_STATIC) && (mState == STATE_NO_STATIC_DATA) && (sizeInBytes > 0)) { mState = STATE_INITIALIZED; } - //TODO check if future writes should be forbidden for static tracks - // or: how to update data for static tracks? if (mState != STATE_INITIALIZED) { - throw(new IllegalStateException("write() called on uninitialized AudioTrack.")); + return ERROR_INVALID_OPERATION; } - return native_write_byte(audioData, offsetInBytes, sizeInBytes); + if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0) + || (offsetInBytes + sizeInBytes > audioData.length)) { + return ERROR_BAD_VALUE; + } + + return native_write_byte(audioData, offsetInBytes, sizeInBytes, mAudioFormat); } - - + + /** * Writes the audio data to the audio hardware for playback. * @param audioData the array that holds the data to play. * @param offsetInShorts the offset in audioData where the data to play starts. * @param sizeInShorts the number of bytes to read in audioData after the offset. - * @return the number of shorts that were written. - * @throws IllegalStateException - */ - public int write(short[] audioData, int offsetInShorts, int sizeInShorts) - throws IllegalStateException { - if ((mDataLoadMode == MODE_STATIC) + * @return the number of shorts that were written or {@link #ERROR_INVALID_OPERATION} + * if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if + * the parameters don't resolve to valid data and indexes. + */ + + public int write(short[] audioData, int offsetInShorts, int sizeInShorts) { + if ((mDataLoadMode == MODE_STATIC) && (mState == STATE_NO_STATIC_DATA) && (sizeInShorts > 0)) { mState = STATE_INITIALIZED; } - //TODO check if future writes should be forbidden for static tracks - // or: how to update data for static tracks? - + if (mState != STATE_INITIALIZED) { - throw(new IllegalStateException("write() called on uninitialized AudioTrack.")); + return ERROR_INVALID_OPERATION; + } + + if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0) + || (offsetInShorts + sizeInShorts > audioData.length)) { + return ERROR_BAD_VALUE; } - return native_write_short(audioData, offsetInShorts, sizeInShorts); + return native_write_short(audioData, offsetInShorts, sizeInShorts, mAudioFormat); } - - + + /** * Notifies the native resource to reuse the audio data already loaded in the native * layer. This call is only valid with AudioTrack instances that don't use the streaming @@ -778,23 +866,16 @@ public class AudioTrack // Interface definitions //-------------------- /** - * Interface definition for a callback to be invoked when an AudioTrack has - * reached a notification marker set by setNotificationMarkerPosition(). + * Interface definition for a callback to be invoked when the playback head position of + * an AudioTrack has reached a notification marker or has increased by a certain period. */ - public interface OnMarkerReachedListener { + public interface OnPlaybackPositionUpdateListener { /** * Called on the listener to notify it that the previously set marker has been reached * by the playback head. */ void onMarkerReached(AudioTrack track); - } - - - /** - * Interface definition for a callback to be invoked for each periodic AudioTrack - * update during playback. The update interval is set by setPositionNotificationPeriod(). - */ - public interface OnPeriodicNotificationListener { + /** * Called on the listener to periodically notify it that the playback head has reached * a multiple of the notification period. @@ -807,42 +888,63 @@ public class AudioTrack // Inner classes //-------------------- /** - * Helper class to handle the forwarding of native events to the appropriate listeners - */ - private class NativeEventHandler extends Handler - { - private AudioTrack mAudioTrack; - - public NativeEventHandler(AudioTrack mp, Looper looper) { - super(looper); - mAudioTrack = mp; - } - - @Override - public void handleMessage(Message msg) { - if (mAudioTrack == null) { - return; - } - switch(msg.what) { - case NATIVE_EVENT_MARKER: - synchronized (mMarkerListenerLock) { - if (mAudioTrack.mMarkerListener != null) { - mAudioTrack.mMarkerListener.onMarkerReached(mAudioTrack); - } - } - break; - case NATIVE_EVENT_NEW_POS: - synchronized (mPeriodicListenerLock) { - if (mAudioTrack.mPeriodicListener != null) { - mAudioTrack.mPeriodicListener.onPeriodicNotification(mAudioTrack); - } + * Helper class to handle the forwarding of native events to the appropriate listener + * (potentially) handled in a different thread + */ + private class NativeEventHandlerDelegate { + private final AudioTrack mAudioTrack; + private final Handler mHandler; + + NativeEventHandlerDelegate(AudioTrack track, Handler handler) { + mAudioTrack = track; + // find the looper for our new event handler + Looper looper; + if (handler != null) { + looper = handler.getLooper(); + } else { + // no given handler, look for main looper + if ((looper = Looper.myLooper()) == null) { + looper = Looper.getMainLooper(); } - break; - default: - Log.e(TAG, "[ android.media.AudioTrack.NativeEventHandler ] " + - "Unknown event type: " + msg.what); - break; } + // construct the event handler with this looper + if (looper != null) { + // implement the event handler delegate + mHandler = new Handler(looper) { + @Override + public void handleMessage(Message msg) { + if (mAudioTrack == null) { + return; + } + OnPlaybackPositionUpdateListener listener = null; + synchronized (mPositionListenerLock) { + listener = mAudioTrack.mPositionListener; + } + switch(msg.what) { + case NATIVE_EVENT_MARKER: + if (listener != null) { + listener.onMarkerReached(mAudioTrack); + } + break; + case NATIVE_EVENT_NEW_POS: + if (listener != null) { + listener.onPeriodicNotification(mAudioTrack); + } + break; + default: + Log.e(TAG, "[ android.media.AudioTrack.NativeEventHandler ] " + + "Unknown event type: " + msg.what); + break; + } + } + }; + } else { + mHandler = null; + } + } + + Handler getHandler() { + return mHandler; } } @@ -858,28 +960,29 @@ public class AudioTrack if (track == null) { return; } - - if (track.mNativeEventHandler != null) { - Message m = track.mNativeEventHandler.obtainMessage(what, arg1, arg2, obj); - track.mNativeEventHandler.sendMessage(m); + + if (track.mEventHandlerDelegate != null) { + Message m = + track.mEventHandlerDelegate.getHandler().obtainMessage(what, arg1, arg2, obj); + track.mEventHandlerDelegate.getHandler().sendMessage(m); } } - - + + //--------------------------------------------------------- // Native methods called from the Java side //-------------------- - private native final int native_setup(Object audiotrack_this, - int streamType, int sampleRate, int nbChannels, int audioFormat, + private native final int native_setup(Object audiotrack_this, + int streamType, int sampleRate, int nbChannels, int audioFormat, int buffSizeInBytes, int mode); private native final void native_finalize(); - + private native final void native_release(); - private native final void native_start(); + private native final void native_start(); private native final void native_stop(); @@ -887,34 +990,36 @@ public class AudioTrack private native final void native_flush(); - private native final int native_write_byte(byte[] audioData, - int offsetInBytes, int sizeInBytes); - - private native final int native_write_short(short[] audioData, - int offsetInShorts, int sizeInShorts); - + private native final int native_write_byte(byte[] audioData, + int offsetInBytes, int sizeInBytes, int format); + + private native final int native_write_short(short[] audioData, + int offsetInShorts, int sizeInShorts, int format); + private native final int native_reload_static(); private native final int native_get_native_frame_count(); private native final void native_setVolume(float leftVolume, float rightVolume); - + private native final void native_set_playback_rate(int sampleRateInHz); private native final int native_get_playback_rate(); - + private native final int native_set_marker_pos(int marker); private native final int native_get_marker_pos(); - + private native final int native_set_pos_update_period(int updatePeriod); private native final int native_get_pos_update_period(); - + private native final int native_set_position(int position); private native final int native_get_position(); - + private native final int native_set_loop(int start, int end, int loopCount); - - static private native final int native_get_output_sample_rate(); - + + static private native final int native_get_output_sample_rate(int streamType); + static private native final int native_get_min_buff_size( + int sampleRateInHz, int channelConfig, int audioFormat); + //--------------------------------------------------------- // Utility methods @@ -929,6 +1034,3 @@ public class AudioTrack } } - - - diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl index 3e33d98ec82dbbfc0957b96f255e591e9f367607..f5e242d11d10c16f190f925ceeb98e7c7191f680 100644 --- a/media/java/android/media/IAudioService.aidl +++ b/media/java/android/media/IAudioService.aidl @@ -65,6 +65,8 @@ interface IAudioService { oneway void playSoundEffect(int effectType); + oneway void playSoundEffectVolume(int effectType, float volume); + boolean loadSoundEffects(); oneway void unloadSoundEffects(); diff --git a/media/java/android/media/JetPlayer.java b/media/java/android/media/JetPlayer.java index b9268d5970a0539af928c91d03c40a921ad8ddef..9de0eec463c613c33faaf31c35ad3734af5218ea 100644 --- a/media/java/android/media/JetPlayer.java +++ b/media/java/android/media/JetPlayer.java @@ -17,21 +17,22 @@ package android.media; +import java.io.FileDescriptor; import java.lang.ref.WeakReference; import java.lang.CloneNotSupportedException; +import android.content.res.AssetFileDescriptor; import android.os.Looper; import android.os.Handler; import android.os.Message; +import android.util.AndroidRuntimeException; import android.util.Log; /** * JetPlayer provides access to JET content playback and control. *

                * Use JetPlayer.getJetPlayer() to get an instance of this class. - * There can only be one instance of this class at any one time. * - * @hide */ public class JetPlayer { @@ -39,15 +40,29 @@ public class JetPlayer // Constants //------------------------ /** - * The maximum number of simultaneous tracks. Use {@link #getMaxTracks()} to + * The maximum number of simultaneous tracks. Use __link #getMaxTracks()} to * access this value. */ - protected static int MAXTRACKS = 32; + private static int MAXTRACKS = 32; - // These constants are to be kept in sync with the ones in include/media/JetPlayer.h - protected static final int JET_USERID_UPDATE = 1; - protected static final int JET_NUMQUEUEDSEGMENT_UPDATE = 2; - protected static final int JET_PAUSE_UPDATE = 3; + // to keep in sync with the JetPlayer class constants + // defined in frameworks/base/include/media/JetPlayer.h + private static final int JET_EVENT = 1; + private static final int JET_USERID_UPDATE = 2; + private static final int JET_NUMQUEUEDSEGMENT_UPDATE = 3; + private static final int JET_PAUSE_UPDATE = 4; + + // to keep in sync with external/sonivox/arm-wt-22k/lib_src/jet_data.h + // Encoding of event information on 32 bits + private static final int JET_EVENT_VAL_MASK = 0x0000007f; // mask for value + private static final int JET_EVENT_CTRL_MASK = 0x00003f80; // mask for controller + private static final int JET_EVENT_CHAN_MASK = 0x0003c000; // mask for channel + private static final int JET_EVENT_TRACK_MASK = 0x00fc0000; // mask for track number + private static final int JET_EVENT_SEG_MASK = 0xff000000; // mask for segment ID + private static final int JET_EVENT_CTRL_SHIFT = 7; // shift to get controller number to bit 0 + private static final int JET_EVENT_CHAN_SHIFT = 14; // shift to get MIDI channel to bit 0 + private static final int JET_EVENT_TRACK_SHIFT = 18; // shift to get track ID to bit 0 + private static final int JET_EVENT_SEG_SHIFT = 24; // shift to get segment ID to bit 0 //-------------------------------------------- @@ -56,13 +71,20 @@ public class JetPlayer private EventHandler mNativeEventHandler = null; /** - * Lock to protect event listener updates against event notifications + * Lock to protect status listener updates against status change notifications */ - protected final Object mStatusListenerLock = new Object(); + private final Object mStatusListenerLock = new Object(); - protected JetStatusUpdateListener mJetStatusUpdateListener = null; + /** + * Lock to protect the event listener updates against event notifications + */ + private final Object mEventListenerLock = new Object(); + + private JetStatusUpdateListener mJetStatusUpdateListener = null; - protected static JetPlayer singletonRef; + private JetEventListener mJetEventListener = null; + + private static JetPlayer singletonRef; //-------------------------------- @@ -136,8 +158,18 @@ public class JetPlayer //-------------------------------------------- // Jet functionality //------------------------ - public boolean openJetFile(String path) { - return native_openJetFile(path); + public boolean loadJetFile(String path) { + return native_loadJetFromFile(path); + } + + + public boolean loadJetFile(AssetFileDescriptor afd) { + long len = afd.getLength(); + if (len < 0) { + throw new AndroidRuntimeException("no length for fd"); + } + return native_loadJetFromFileD( + afd.getFileDescriptor(), afd.getStartOffset(), len); } @@ -195,6 +227,10 @@ public class JetPlayer } + public boolean clearQueue() { + return native_clearQueue(); + } + //--------------------------------------------------------- // Internal class to handle events posted from native code @@ -211,28 +247,44 @@ public class JetPlayer @Override public void handleMessage(Message msg) { switch(msg.what) { + case JET_EVENT: + synchronized (mEventListenerLock) { + if (mJetEventListener != null) { + // call the appropriate listener after decoding the event parameters + // encoded in msg.arg1 + mJetEventListener.onJetEvent( + mJet, + (short)((msg.arg1 & JET_EVENT_SEG_MASK) >> JET_EVENT_SEG_SHIFT), + (byte) ((msg.arg1 & JET_EVENT_TRACK_MASK) >> JET_EVENT_TRACK_SHIFT), + // JETCreator channel numbers start at 1, but the index starts at 0 + // in the .jet files + (byte)(((msg.arg1 & JET_EVENT_CHAN_MASK) >> JET_EVENT_CHAN_SHIFT) + 1), + (byte) ((msg.arg1 & JET_EVENT_CTRL_MASK) >> JET_EVENT_CTRL_SHIFT), + (byte) (msg.arg1 & JET_EVENT_VAL_MASK) ); + } + } + return; case JET_USERID_UPDATE: synchronized (mStatusListenerLock) { if (mJetStatusUpdateListener != null) { - mJetStatusUpdateListener.onJetUserIdUpdate(msg.arg1, msg.arg2); + mJetStatusUpdateListener.onJetUserIdUpdate(mJet, msg.arg1, msg.arg2); } } return; case JET_NUMQUEUEDSEGMENT_UPDATE: synchronized (mStatusListenerLock) { if (mJetStatusUpdateListener != null) { - mJetStatusUpdateListener.onJetNumQueuedSegmentUpdate(msg.arg1); + mJetStatusUpdateListener.onJetNumQueuedSegmentUpdate(mJet, msg.arg1); } } return; case JET_PAUSE_UPDATE: synchronized (mStatusListenerLock) { if (mJetStatusUpdateListener != null) - mJetStatusUpdateListener.onJetPauseUpdate(msg.arg1); + mJetStatusUpdateListener.onJetPauseUpdate(mJet, msg.arg1); } return; - default: loge("Unknown message type " + msg.what); return; @@ -242,7 +294,7 @@ public class JetPlayer //-------------------------------------------- - // Jet event listener + // Jet status update listener //------------------------ public void setStatusUpdateListener(JetStatusUpdateListener listener) { synchronized(mStatusListenerLock) { @@ -255,31 +307,66 @@ public class JetPlayer } /** - * Handles the notification when the JET segment userID is updated. + * Handles the notification when the JET status is updated. */ public interface JetStatusUpdateListener { /** * Callback for when JET's currently playing segment userID is updated. * + * @param player the JET player the status update is coming from * @param userId the ID of the currently playing segment * @param repeatCount the repetition count for the segment (0 means it plays once) */ - void onJetUserIdUpdate(int userId, int repeatCount); + void onJetUserIdUpdate(JetPlayer player, int userId, int repeatCount); /** * Callback for when JET's number of queued segments is updated. * + * @param player the JET player the status update is coming from * @param nbSegments the number of segments in the JET queue */ - void onJetNumQueuedSegmentUpdate(int nbSegments); + void onJetNumQueuedSegmentUpdate(JetPlayer player, int nbSegments); /** * Callback for when JET pause state is updated. * + * @param player the JET player the status update is coming from * @param paused indicates whether JET is paused or not */ - void onJetPauseUpdate(int paused); - }; + void onJetPauseUpdate(JetPlayer player, int paused); + } + + + //-------------------------------------------- + // Jet event listener + //------------------------ + public void setEventListener(JetEventListener listener) { + synchronized(mEventListenerLock) { + mJetEventListener = listener; + } + + if ((listener != null) && (mNativeEventHandler == null)) { + createNativeEventHandler(); + } + } + + /** + * Handles the notification when the JET engine generates an event. + */ + public interface JetEventListener { + /** + * Callback for when the JET engine generates a new event. + * + * @param player the JET player the event is coming from + * @param segment 8 bit unsigned value + * @param track 6 bit unsigned value + * @param channel 4 bit unsigned value + * @param controller 7 bit unsigned value + * @param value 7 bit unsigned value + */ + void onJetEvent(JetPlayer player, + short segment, byte track, byte channel, byte controller, byte value); + } //-------------------------------------------- @@ -289,7 +376,8 @@ public class JetPlayer int maxTracks, int trackBufferSize); private native final void native_finalize(); private native final void native_release(); - private native final boolean native_openJetFile(String pathToJetFile); + private native final boolean native_loadJetFromFile(String pathToJetFile); + private native final boolean native_loadJetFromFileD(FileDescriptor fd, long offset, long len); private native final boolean native_closeJetFile(); private native final boolean native_playJet(); private native final boolean native_pauseJet(); @@ -300,7 +388,8 @@ public class JetPlayer private native final boolean native_setMuteFlags(int muteFlags, boolean sync); private native final boolean native_setMuteArray(boolean[]muteArray, boolean sync); private native final boolean native_setMuteFlag(int trackId, boolean muteFlag, boolean sync); - private native final boolean native_triggerClip(int clipId); + private native final boolean native_triggerClip(int clipId); + private native final boolean native_clearQueue(); //--------------------------------------------------------- // Called exclusively by native code diff --git a/media/java/android/media/MediaFile.java b/media/java/android/media/MediaFile.java index 22361aade44ab52cc3f66570bbabf511b3900124..f05842d6ce02bac3547c05cc025cb60bbfc6c1d1 100644 --- a/media/java/android/media/MediaFile.java +++ b/media/java/android/media/MediaFile.java @@ -102,13 +102,17 @@ public class MediaFile { addFileType("AMR", FILE_TYPE_AMR, "audio/amr"); addFileType("AWB", FILE_TYPE_AWB, "audio/amr-wb"); addFileType("WMA", FILE_TYPE_WMA, "audio/x-ms-wma"); - addFileType("OGG", FILE_TYPE_OGG, "application/ogg"); + addFileType("OGG", FILE_TYPE_OGG, "application/ogg"); + addFileType("OGA", FILE_TYPE_OGG, "application/ogg"); addFileType("MID", FILE_TYPE_MID, "audio/midi"); + addFileType("MIDI", FILE_TYPE_MID, "audio/midi"); addFileType("XMF", FILE_TYPE_MID, "audio/midi"); addFileType("RTTTL", FILE_TYPE_MID, "audio/midi"); addFileType("SMF", FILE_TYPE_SMF, "audio/sp-midi"); addFileType("IMY", FILE_TYPE_IMY, "audio/imelody"); + addFileType("RTX", FILE_TYPE_MID, "audio/midi"); + addFileType("OTA", FILE_TYPE_MID, "audio/midi"); addFileType("MP4", FILE_TYPE_MP4, "video/mp4"); addFileType("M4V", FILE_TYPE_M4V, "video/mp4"); diff --git a/media/java/android/media/MediaMetadataRetriever.java b/media/java/android/media/MediaMetadataRetriever.java index c1a0c211d31c54c8fd402a1736dbdd6fa305ec84..3a49a5f36e64b610268ef9bfbfab376d06528eb5 100644 --- a/media/java/android/media/MediaMetadataRetriever.java +++ b/media/java/android/media/MediaMetadataRetriever.java @@ -18,6 +18,7 @@ package android.media; import android.content.ContentResolver; import android.content.Context; +import android.content.res.AssetFileDescriptor; import android.graphics.Bitmap; import android.net.Uri; import android.os.ParcelFileDescriptor; @@ -137,11 +138,11 @@ public class MediaMetadataRetriever return; } - ParcelFileDescriptor fd = null; + AssetFileDescriptor fd = null; try { ContentResolver resolver = context.getContentResolver(); try { - fd = resolver.openFileDescriptor(uri, "r"); + fd = resolver.openAssetFileDescriptor(uri, "r"); } catch(FileNotFoundException e) { throw new IllegalArgumentException(); } @@ -152,7 +153,14 @@ public class MediaMetadataRetriever if (!descriptor.valid()) { throw new IllegalArgumentException(); } - setDataSource(descriptor); + // Note: using getDeclaredLength so that our behavior is the same + // as previous versions when the content provider is returning + // a full file. + if (fd.getDeclaredLength() < 0) { + setDataSource(descriptor); + } else { + setDataSource(descriptor, fd.getStartOffset(), fd.getDeclaredLength()); + } return; } catch (SecurityException ex) { } finally { diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java index 1a82654ca2c331592f0be09d7b616d77f99b0be5..202d0ae931fe64b47485f0a8e8a5a6895e36f0e4 100644 --- a/media/java/android/media/MediaPlayer.java +++ b/media/java/android/media/MediaPlayer.java @@ -39,11 +39,11 @@ import java.lang.ref.WeakReference; /** * MediaPlayer class can be used to control playback * of audio/video files and streams. An example on how to use the methods in - * this class can be found in VideoView. - * Please see Android Media APIs + * this class can be found in {@link android.widget.VideoView}. + * Please see Audio and Video * for additional help using MediaPlayer. * - *

                Topics covered are: + *

                Topics covered here are: *

                  *
                1. State Diagram *
                2. Valid and Invalid States @@ -584,14 +584,21 @@ public class MediaPlayer return; } - ParcelFileDescriptor fd = null; + AssetFileDescriptor fd = null; try { ContentResolver resolver = context.getContentResolver(); - fd = resolver.openFileDescriptor(uri, "r"); + fd = resolver.openAssetFileDescriptor(uri, "r"); if (fd == null) { return; } - setDataSource(fd.getFileDescriptor()); + // Note: using getDeclaredLength so that our behavior is the same + // as previous versions when the content provider is returning + // a full file. + if (fd.getDeclaredLength() < 0) { + setDataSource(fd.getFileDescriptor()); + } else { + setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength()); + } return; } catch (SecurityException ex) { } catch (IOException ex) { @@ -825,13 +832,14 @@ public class MediaPlayer * done using the MediaPlayer. */ public void release() { - if (mWakeLock != null) mWakeLock.release(); + stayAwake(false); updateSurfaceScreenOn(); mOnPreparedListener = null; mOnBufferingUpdateListener = null; mOnCompletionListener = null; mOnSeekCompleteListener = null; mOnErrorListener = null; + mOnInfoListener = null; mOnVideoSizeChangedListener = null; _release(); } @@ -844,6 +852,7 @@ public class MediaPlayer * data source and calling prepare(). */ public void reset() { + stayAwake(false); _reset(); // make sure none of the listeners get called anymore mEventHandler.removeCallbacksAndMessages(null); @@ -910,18 +919,7 @@ public class MediaPlayer private static final int MEDIA_SEEK_COMPLETE = 4; private static final int MEDIA_SET_VIDEO_SIZE = 5; private static final int MEDIA_ERROR = 100; - - // error codes from framework that indicate content issues - // contained in arg1 of error message - - // Seek not supported - live stream - private static final int ERROR_SEEK_NOT_SUPPORTED = 42; - - // A/V interleave exceeds the progressive streaming buffer - private static final int ERROR_CONTENT_IS_POORLY_INTERLEAVED = 43; - - // video decoder is falling behind - content is too complex - private static final int ERROR_VIDEO_TRACK_IS_FALLING_BEHIND = 44; + private static final int MEDIA_INFO = 200; private class EventHandler extends Handler { @@ -966,6 +964,8 @@ public class MediaPlayer return; case MEDIA_ERROR: + // For PV specific error values (msg.arg2) look in + // opencore/pvmi/pvmf/include/pvmf_return_codes.h Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")"); boolean error_was_handled = false; if (mOnErrorListener != null) { @@ -976,6 +976,17 @@ public class MediaPlayer } stayAwake(false); return; + + case MEDIA_INFO: + // For PV specific code values (msg.arg2) look in + // opencore/pvmi/pvmf/include/pvmf_return_codes.h + Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")"); + if (mOnInfoListener != null) { + mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2); + } + // No real default action so far. + return; + case MEDIA_NOP: // interface test message - ignore break; @@ -1157,12 +1168,19 @@ public class MediaPlayer * @see android.media.MediaPlayer.OnErrorListener */ public static final int MEDIA_ERROR_UNKNOWN = 1; + /** Media server died. In this case, the application must release the * MediaPlayer object and instantiate a new one. * @see android.media.MediaPlayer.OnErrorListener */ public static final int MEDIA_ERROR_SERVER_DIED = 100; + /** The video is streamed and its container is not valid for progressive + * playback i.e the video's index (e.g moov atom) is not at the start of the + * file. + * @hide pending API council approval. Replace with @see tag after. + */ + public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200; /** * Interface definition of a callback to be invoked when there @@ -1180,7 +1198,8 @@ public class MediaPlayer *
                3. {@link #MEDIA_ERROR_UNKNOWN} *
                4. {@link #MEDIA_ERROR_SERVER_DIED} *
              - * @param extra an extra code, specific to the error type + * @param extra an extra code, specific to the error. Typically + * implementation dependant. * @return True if the method handled the error, false if it didn't. * Returning false, or not having an OnErrorListener at all, will * cause the OnCompletionListener to be called. @@ -1192,12 +1211,83 @@ public class MediaPlayer * Register a callback to be invoked when an error has happened * during an asynchronous operation. * - * @param l the callback that will be run + * @param listener the callback that will be run */ - public void setOnErrorListener(OnErrorListener l) + public void setOnErrorListener(OnErrorListener listener) { - mOnErrorListener = l; + mOnErrorListener = listener; } private OnErrorListener mOnErrorListener; + + + /* Do not change these values without updating their counterparts + * in include/media/mediaplayer.h! + */ + /** Unspecified media player info. + * @see android.media.MediaPlayer.OnInfoListener + * @hide pending API council approval. + */ + public static final int MEDIA_INFO_UNKNOWN = 1; + + /** The video is too complex for the decoder: it can't decode frames fast + * enough. Possibly only the audio plays fine at this stage. + * @see android.media.MediaPlayer.OnInfoListener + * @hide pending API council approval. + */ + public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; + + /** Bad interleaving means that a media has been improperly interleaved or + * not interleaved at all, e.g has all the video samples first then all the + * audio ones. Video is playing but a lot of disk seeks may be happening. + * @see android.media.MediaPlayer.OnInfoListener + * @hide pending API council approval. + */ + public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; + + /** The media cannot be seeked (e.g live stream) + * @see android.media.MediaPlayer.OnInfoListener + * @hide pending API council approval. + */ + public static final int MEDIA_INFO_NOT_SEEKABLE = 801; + + /** + * Interface definition of a callback to be invoked to communicate some + * info and/or warning about the media or its playback. + * @hide pending API council approval. + */ + public interface OnInfoListener + { + /** + * Called to indicate an info or a warning. + * + * @param mp the MediaPlayer the info pertains to. + * @param what the type of info or warning. + *
                + *
              • {@link #MEDIA_INFO_UNKNOWN} + *
              • {@link #MEDIA_INFO_VIDEO_TRACK_LAGGING} + *
              • {@link #MEDIA_INFO_BAD_INTERLEAVING} + *
              • {@link #MEDIA_INFO_NOT_SEEKABLE} + *
              + * @param extra an extra code, specific to the info. Typically + * implementation dependant. + * @return True if the method handled the info, false if it didn't. + * Returning false, or not having an OnErrorListener at all, will + * cause the info to be discarded. + */ + boolean onInfo(MediaPlayer mp, int what, int extra); + } + + /** + * Register a callback to be invoked when an info/warning is available. + * + * @param listener the callback that will be run + * @hide pending API council approval. + */ + public void setOnInfoListener(OnInfoListener listener) + { + mOnInfoListener = listener; + } + + private OnInfoListener mOnInfoListener; } diff --git a/media/java/android/media/MediaRecorder.java b/media/java/android/media/MediaRecorder.java index 651cc41439a50b968825bb22110a927a12ddae5b..1c08cba5d4491263fdfd4b07697ffe74cf03a920 100644 --- a/media/java/android/media/MediaRecorder.java +++ b/media/java/android/media/MediaRecorder.java @@ -16,19 +16,27 @@ package android.media; -import android.view.Surface; import android.hardware.Camera; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.util.Log; +import android.view.Surface; import java.io.IOException; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileDescriptor; +import java.lang.ref.WeakReference; /** * Used to record audio and video. The recording control is based on a - * simple state machine (see below). - * - *

              + * simple state machine (see below). + * + *

              *

              - * + * *

              A common case of using MediaRecorder to record audio works as follows: - * + * *

              MediaRecorder recorder = new MediaRecorder();
                * recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
              @@ -41,38 +49,56 @@ import java.io.IOException;
                * recorder.reset();   // You can reuse the object by going back to setAudioSource() step
                * recorder.release(); // Now the object cannot be reused
                * 
              - * - *

              See the Android Media APIs - * page for additional help with using MediaRecorder. + * + *

              See the Audio and Video + * documentation for additional help with using MediaRecorder. */ public class MediaRecorder -{ +{ static { System.loadLibrary("media_jni"); } - + private final static String TAG = "MediaRecorder"; + // The two fields below are accessed by native methods @SuppressWarnings("unused") private int mNativeContext; - + @SuppressWarnings("unused") private Surface mSurface; - + + private String mPath; + private FileDescriptor mFd; + private EventHandler mEventHandler; + private OnErrorListener mOnErrorListener; + private OnInfoListener mOnInfoListener; + /** * Default constructor. */ public MediaRecorder() { - native_setup(); + + Looper looper; + if ((looper = Looper.myLooper()) != null) { + mEventHandler = new EventHandler(this, looper); + } else if ((looper = Looper.getMainLooper()) != null) { + mEventHandler = new EventHandler(this, looper); + } else { + mEventHandler = null; + } + + /* Native setup requires a weak reference to our object. + * It's easier to create it here than in C++. + */ + native_setup(new WeakReference(this)); } - + /** * Sets a Camera to use for recording. Use this function to switch * quickly between preview and capture mode without a teardown of * the camera object. Must call before prepare(). - * + * * @param c the Camera to use for recording - * FIXME: Temporarily hidden until API approval - * @hide */ public native void setCamera(Camera c); @@ -80,15 +106,15 @@ public class MediaRecorder * Sets a Surface to show a preview of recorded media (video). Calls this * before prepare() to make sure that the desirable preview display is * set. - * + * * @param sv the Surface to use for the preview */ public void setPreviewDisplay(Surface sv) { mSurface = sv; } - + /** - * Defines the audio source. These constants are used with + * Defines the audio source. These constants are used with * {@link MediaRecorder#setAudioSource(int)}. */ public final class AudioSource { @@ -102,9 +128,8 @@ public class MediaRecorder } /** - * Defines the video source. These constants are used with + * Defines the video source. These constants are used with * {@link MediaRecorder#setVideoSource(int)}. - * @hide */ public final class VideoSource { /* Do not change these values without updating their counterparts @@ -117,7 +142,7 @@ public class MediaRecorder } /** - * Defines the output format. These constants are used with + * Defines the output format. These constants are used with * {@link MediaRecorder#setOutputFormat(int)}. */ public final class OutputFormat { @@ -135,7 +160,7 @@ public class MediaRecorder }; /** - * Defines the audio encoding. These constants are used with + * Defines the audio encoding. These constants are used with * {@link MediaRecorder#setAudioEncoder(int)}. */ public final class AudioEncoder { @@ -150,9 +175,8 @@ public class MediaRecorder } /** - * Defines the video encoding. These constants are used with + * Defines the video encoding. These constants are used with * {@link MediaRecorder#setVideoEncoder(int)}. - * @hide */ public final class VideoEncoder { /* Do not change these values without updating their counterparts @@ -168,53 +192,51 @@ public class MediaRecorder /** * Sets the audio source to be used for recording. If this method is not * called, the output file will not contain an audio track. The source needs - * to be specified before setting recording-parameters or encoders. Call + * to be specified before setting recording-parameters or encoders. Call * this only before setOutputFormat(). - * + * * @param audio_source the audio source to use * @throws IllegalStateException if it is called after setOutputFormat() * @see android.media.MediaRecorder.AudioSource - */ + */ public native void setAudioSource(int audio_source) throws IllegalStateException; /** * Sets the video source to be used for recording. If this method is not * called, the output file will not contain an video track. The source needs - * to be specified before setting recording-parameters or encoders. Call + * to be specified before setting recording-parameters or encoders. Call * this only before setOutputFormat(). - * + * * @param video_source the video source to use * @throws IllegalStateException if it is called after setOutputFormat() * @see android.media.MediaRecorder.VideoSource - * @hide - */ + */ public native void setVideoSource(int video_source) throws IllegalStateException; /** * Sets the format of the output file produced during recording. Call this * after setAudioSource()/setVideoSource() but before prepare(). - * - * @param output_format the output format to use. The output format + * + * @param output_format the output format to use. The output format * needs to be specified before setting recording-parameters or encoders. * @throws IllegalStateException if it is called after prepare() or before * setAudioSource()/setVideoSource(). * @see android.media.MediaRecorder.OutputFormat - */ + */ public native void setOutputFormat(int output_format) throws IllegalStateException; - + /** * Sets the width and height of the video to be captured. Must be called * after setVideoSource(). Call this after setOutFormat() but before * prepare(). - * + * * @param width the width of the video to be captured * @param height the height of the video to be captured - * @throws IllegalStateException if it is called after + * @throws IllegalStateException if it is called after * prepare() or before setOutputFormat() - * @hide */ public native void setVideoSize(int width, int height) throws IllegalStateException; @@ -225,22 +247,34 @@ public class MediaRecorder * prepare(). * * @param rate the number of frames per second of video to capture - * @throws IllegalStateException if it is called after + * @throws IllegalStateException if it is called after * prepare() or before setOutputFormat(). - * @hide + * + * NOTE: On some devices that have auto-frame rate, this sets the + * maximum frame rate, not a constant frame rate. Actual frame rate + * will vary according to lighting conditions. */ public native void setVideoFrameRate(int rate) throws IllegalStateException; + /** + * Sets the maximum duration (in ms) of the recording session. + * Call this after setOutFormat() but before prepare(). + * + * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit) + * + */ + public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException; + /** * Sets the audio encoder to be used for recording. If this method is not * called, the output file will not contain an audio track. Call this after * setOutputFormat() but before prepare(). - * + * * @param audio_encoder the audio encoder to use. * @throws IllegalStateException if it is called before * setOutputFormat() or after prepare(). * @see android.media.MediaRecorder.AudioEncoder - */ + */ public native void setAudioEncoder(int audio_encoder) throws IllegalStateException; @@ -248,41 +282,78 @@ public class MediaRecorder * Sets the video encoder to be used for recording. If this method is not * called, the output file will not contain an video track. Call this after * setOutputFormat() and before prepare(). - * + * * @param video_encoder the video encoder to use. * @throws IllegalStateException if it is called before * setOutputFormat() or after prepare() * @see android.media.MediaRecorder.VideoEncoder - * @hide - */ + */ public native void setVideoEncoder(int video_encoder) throws IllegalStateException; + /** + * Pass in the file descriptor of the file to be written. Call this after + * setOutputFormat() but before prepare(). + * + * @param fd an open file descriptor to be written into. + * @throws IllegalStateException if it is called before + * setOutputFormat() or after prepare() + */ + public void setOutputFile(FileDescriptor fd) throws IllegalStateException + { + mPath = null; + mFd = fd; + } + /** * Sets the path of the output file to be produced. Call this after * setOutputFormat() but before prepare(). - * - * @param path The pathname to use() + * + * @param path The pathname to use. * @throws IllegalStateException if it is called before * setOutputFormat() or after prepare() - */ - public native void setOutputFile(String path) throws IllegalStateException; - + */ + public void setOutputFile(String path) throws IllegalStateException + { + mFd = null; + mPath = path; + } + + // native implementation + private native void _setOutputFile(FileDescriptor fd, long offset, long length) + throws IllegalStateException, IOException; + private native void _prepare() throws IllegalStateException, IOException; + /** * Prepares the recorder to begin capturing and encoding data. This method * must be called after setting up the desired audio and video sources, * encoders, file format, etc., but before start(). - * + * * @throws IllegalStateException if it is called after * start() or before setOutputFormat(). * @throws IOException if prepare fails otherwise. */ - public native void prepare() throws IllegalStateException, IOException; + public void prepare() throws IllegalStateException, IOException + { + if (mPath != null) { + FileOutputStream fos = new FileOutputStream(mPath); + try { + _setOutputFile(fos.getFD(), 0, 0); + } finally { + fos.close(); + } + } else if (mFd != null) { + _setOutputFile(mFd, 0, 0); + } else { + throw new IOException("No valid output file"); + } + _prepare(); + } /** - * Begins capturing and encoding data to the file specified with + * Begins capturing and encoding data to the file specified with * setOutputFile(). Call this after prepare(). - * + * * @throws IllegalStateException if it is called before * prepare(). */ @@ -291,7 +362,7 @@ public class MediaRecorder /** * Stops recording. Call this after start(). Once recording is stopped, * you will have to configure it again as if it has just been constructed. - * + * * @throws IllegalStateException if it is called before start() */ public native void stop() throws IllegalStateException; @@ -301,19 +372,167 @@ public class MediaRecorder * this method, you will have to configure it again as if it had just been * constructed. */ - public native void reset(); - + public void reset() { + native_reset(); + + // make sure none of the listeners get called anymore + mEventHandler.removeCallbacksAndMessages(null); + } + + private native void native_reset(); + /** - * Returns the maximum absolute amplitude that was sampled since the last + * Returns the maximum absolute amplitude that was sampled since the last * call to this method. Call this only after the setAudioSource(). - * - * @return the maximum absolute amplitude measured since the last call, or + * + * @return the maximum absolute amplitude measured since the last call, or * 0 when called for the first time * @throws IllegalStateException if it is called before * the audio source has been set. */ public native int getMaxAmplitude() throws IllegalStateException; - + + /* Do not change this value without updating its counterpart + * in include/media/mediarecorder.h! + */ + /** Unspecified media recorder error. + * @see android.media.MediaRecorder.OnErrorListener + */ + public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1; + + /** + * Interface definition for a callback to be invoked when an error + * occurs while recording. + */ + public interface OnErrorListener + { + /** + * Called when an error occurs while recording. + * + * @param mr the MediaRecorder that encountered the error + * @param what the type of error that has occurred: + *

                + *
              • {@link #MEDIA_RECORDER_ERROR_UNKNOWN} + *
              + * @param extra an extra code, specific to the error type + */ + void onError(MediaRecorder mr, int what, int extra); + } + + /** + * Register a callback to be invoked when an error occurs while + * recording. + * + * @param l the callback that will be run + */ + public void setOnErrorListener(OnErrorListener l) + { + mOnErrorListener = l; + } + + /* Do not change these values without updating their counterparts + * in include/media/mediarecorder.h! + */ + /** Unspecified media recorder error. + * @see android.media.MediaRecorder.OnInfoListener + */ + public static final int MEDIA_RECORDER_INFO_UNKNOWN = 1; + /** A maximum duration had been setup and has now been reached. + * @see android.media.MediaRecorder.OnInfoListener + */ + public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800; + + /** + * Interface definition for a callback to be invoked when an error + * occurs while recording. + */ + public interface OnInfoListener + { + /** + * Called when an error occurs while recording. + * + * @param mr the MediaRecorder that encountered the error + * @param what the type of error that has occurred: + *
                + *
              • {@link #MEDIA_RECORDER_INFO_UNKNOWN} + *
              + * @param extra an extra code, specific to the error type + */ + void onInfo(MediaRecorder mr, int what, int extra); + } + + /** + * Register a callback to be invoked when an informational event occurs while + * recording. + * + * @param listener the callback that will be run + */ + public void setOnInfoListener(OnInfoListener listener) + { + mOnInfoListener = listener; + } + + private class EventHandler extends Handler + { + private MediaRecorder mMediaRecorder; + + public EventHandler(MediaRecorder mr, Looper looper) { + super(looper); + mMediaRecorder = mr; + } + + /* Do not change these values without updating their counterparts + * in include/media/mediarecorder.h! + */ + private static final int MEDIA_RECORDER_EVENT_ERROR = 1; + private static final int MEDIA_RECORDER_EVENT_INFO = 2; + + @Override + public void handleMessage(Message msg) { + if (mMediaRecorder.mNativeContext == 0) { + Log.w(TAG, "mediarecorder went away with unhandled events"); + return; + } + switch(msg.what) { + case MEDIA_RECORDER_EVENT_ERROR: + if (mOnErrorListener != null) + mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2); + + return; + + case MEDIA_RECORDER_EVENT_INFO: + if (mOnInfoListener != null) + mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2); + + return; + + default: + Log.e(TAG, "Unknown message type " + msg.what); + return; + } + } + } + + /** + * Called from native code when an interesting event happens. This method + * just uses the EventHandler system to post the event back to the main app thread. + * We use a weak reference to the original MediaRecorder object so that the native + * code is safe from the object disappearing from underneath it. (This is + * the cookie passed to native_setup().) + */ + private static void postEventFromNative(Object mediarecorder_ref, + int what, int arg1, int arg2, Object obj) + { + MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get(); + if (mr == null) { + return; + } + + if (mr.mEventHandler != null) { + Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj); + mr.mEventHandler.sendMessage(m); + } + } /** * Releases resources associated with this MediaRecorder object. @@ -322,10 +541,10 @@ public class MediaRecorder */ public native void release(); - private native final void native_setup() throws IllegalStateException; - + private native final void native_setup(Object mediarecorder_this) throws IllegalStateException; + private native final void native_finalize(); - + @Override protected void finalize() { native_finalize(); } } diff --git a/media/java/android/media/MediaScanner.java b/media/java/android/media/MediaScanner.java index 38203b6b8c88d80bb25466edd429f822e278d0d3..fc8476d4ae83f0b67d702e346119ca76c8e24eb8 100644 --- a/media/java/android/media/MediaScanner.java +++ b/media/java/android/media/MediaScanner.java @@ -118,6 +118,7 @@ public class MediaScanner private static final String NOTIFICATIONS_DIR = "/notifications/"; private static final String ALARMS_DIR = "/alarms/"; private static final String MUSIC_DIR = "/music/"; + private static final String PODCAST_DIR = "/podcasts/"; private static final String[] ID3_GENRES = { // ID3v1 Genres @@ -455,8 +456,9 @@ public class MediaScanner boolean ringtones = (path.indexOf(RINGTONES_DIR) > 0); boolean notifications = (path.indexOf(NOTIFICATIONS_DIR) > 0); boolean alarms = (path.indexOf(ALARMS_DIR) > 0); + boolean podcasts = (path.indexOf(PODCAST_DIR) > 0); boolean music = (path.indexOf(MUSIC_DIR) > 0) || - (!ringtones && !notifications && !alarms); + (!ringtones && !notifications && !alarms && !podcasts); if (mFileType == MediaFile.FILE_TYPE_MP3 || mFileType == MediaFile.FILE_TYPE_MP4 || @@ -473,7 +475,7 @@ public class MediaScanner // we used to compute the width and height but it's not worth it } - result = endFile(entry, ringtones, notifications, alarms, music); + result = endFile(entry, ringtones, notifications, alarms, music, podcasts); } } catch (RemoteException e) { Log.e(TAG, "RemoteException in MediaScanner.scanFile()", e); @@ -586,7 +588,8 @@ public class MediaScanner return map; } - public Uri endFile(FileCacheEntry entry, boolean ringtones, boolean notifications, boolean alarms, boolean music) + private Uri endFile(FileCacheEntry entry, boolean ringtones, boolean notifications, + boolean alarms, boolean music, boolean podcasts) throws RemoteException { // update database Uri tableUri; @@ -634,6 +637,7 @@ public class MediaScanner values.put(Audio.Media.IS_NOTIFICATION, notifications); values.put(Audio.Media.IS_ALARM, alarms); values.put(Audio.Media.IS_MUSIC, music); + values.put(Audio.Media.IS_PODCAST, podcasts); } else if (isImage) { // nothing right now } diff --git a/media/java/android/media/Ringtone.java b/media/java/android/media/Ringtone.java index cfcb5eb13329c660fffc0435ba36fc410050cb06..e80d8aaf984a28c06067c0be976599b5860ee6f7 100644 --- a/media/java/android/media/Ringtone.java +++ b/media/java/android/media/Ringtone.java @@ -164,9 +164,16 @@ public class Ringtone { } else if (mFileDescriptor != null) { mAudio.setDataSource(mFileDescriptor); } else if (mAssetFileDescriptor != null) { - mAudio.setDataSource(mAssetFileDescriptor.getFileDescriptor(), - mAssetFileDescriptor.getStartOffset(), - mAssetFileDescriptor.getLength()); + // Note: using getDeclaredLength so that our behavior is the same + // as previous versions when the content provider is returning + // a full file. + if (mAssetFileDescriptor.getDeclaredLength() < 0) { + mAudio.setDataSource(mAssetFileDescriptor.getFileDescriptor()); + } else { + mAudio.setDataSource(mAssetFileDescriptor.getFileDescriptor(), + mAssetFileDescriptor.getStartOffset(), + mAssetFileDescriptor.getDeclaredLength()); + } } else { throw new IOException("No data source set."); } diff --git a/media/java/android/media/SoundPool.java b/media/java/android/media/SoundPool.java index 427f173ba09fc4738ecaafa0d3d7ca32e242da0b..000430f96b632695ce293216b3b174a135239c1f 100644 --- a/media/java/android/media/SoundPool.java +++ b/media/java/android/media/SoundPool.java @@ -16,6 +16,7 @@ package android.media; +import android.util.AndroidRuntimeException; import android.util.Log; import java.io.File; import java.io.FileDescriptor; @@ -79,7 +80,11 @@ public class SoundPool public int load(AssetFileDescriptor afd, int priority) { if (afd != null) { - return _load(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength(), priority); + long len = afd.getLength(); + if (len < 0) { + throw new AndroidRuntimeException("no length for fd"); + } + return _load(afd.getFileDescriptor(), afd.getStartOffset(), len, priority); } else { return 0; } diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp index 5562254616bb6c7711eeb01e21a62f0be77c7b99..707db02fd94889538597992c3e86c92428badd39 100644 --- a/media/jni/android_media_MediaPlayer.cpp +++ b/media/jni/android_media_MediaPlayer.cpp @@ -29,6 +29,7 @@ #include "jni.h" #include "JNIHelp.h" #include "android_runtime/AndroidRuntime.h" +#include "utils/Errors.h" // for status_t // ---------------------------------------------------------------------------- @@ -171,6 +172,7 @@ android_media_MediaPlayer_setDataSource(JNIEnv *env, jobject thiz, jstring path) jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); return; } + LOGV("setDataSource: path %s", pathStr); status_t opStatus = mp->setDataSource(pathStr); // Make sure that local ref is released before a potential exception @@ -192,6 +194,7 @@ android_media_MediaPlayer_setDataSourceFD(JNIEnv *env, jobject thiz, jobject fil return; } int fd = getParcelFileDescriptorFD(env, fileDescriptor); + LOGV("setDataSourceFD: fd %d", fd); process_media_player_call( env, thiz, mp->setDataSource(fd, offset, length), "java/io/IOException", "setDataSourceFD failed." ); } @@ -207,8 +210,8 @@ android_media_MediaPlayer_prepare(JNIEnv *env, jobject thiz) jobject surface = env->GetObjectField(thiz, fields.surface); if (surface != NULL) { const sp& native_surface = get_surface(env, surface); - //LOGI("prepare: surface=%p (id=%d)", - // native_surface.get(), native_surface->ID()); + LOGV("prepare: surface=%p (id=%d)", + native_surface.get(), native_surface->ID()); mp->setVideoSurface(native_surface); } process_media_player_call( env, thiz, mp->prepare(), "java/io/IOException", "Prepare failed." ); @@ -225,8 +228,8 @@ android_media_MediaPlayer_prepareAsync(JNIEnv *env, jobject thiz) jobject surface = env->GetObjectField(thiz, fields.surface); if (surface != NULL) { const sp& native_surface = get_surface(env, surface); - LOGI("prepareAsync: surface=%p (id=%d)", - native_surface.get(), native_surface->ID()); + LOGV("prepareAsync: surface=%p (id=%d)", + native_surface.get(), native_surface->ID()); mp->setVideoSurface(native_surface); } process_media_player_call( env, thiz, mp->prepareAsync(), "java/io/IOException", "Prepare Async failed." ); @@ -235,6 +238,7 @@ android_media_MediaPlayer_prepareAsync(JNIEnv *env, jobject thiz) static void android_media_MediaPlayer_start(JNIEnv *env, jobject thiz) { + LOGV("start"); sp mp = getMediaPlayer(env, thiz); if (mp == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", NULL); @@ -246,6 +250,7 @@ android_media_MediaPlayer_start(JNIEnv *env, jobject thiz) static void android_media_MediaPlayer_stop(JNIEnv *env, jobject thiz) { + LOGV("stop"); sp mp = getMediaPlayer(env, thiz); if (mp == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", NULL); @@ -257,6 +262,7 @@ android_media_MediaPlayer_stop(JNIEnv *env, jobject thiz) static void android_media_MediaPlayer_pause(JNIEnv *env, jobject thiz) { + LOGV("pause"); sp mp = getMediaPlayer(env, thiz); if (mp == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", NULL); @@ -273,7 +279,10 @@ android_media_MediaPlayer_isPlaying(JNIEnv *env, jobject thiz) jniThrowException(env, "java/lang/IllegalStateException", NULL); return false; } - return mp->isPlaying(); + const jboolean is_playing = mp->isPlaying(); + + LOGV("isPlaying: %d", is_playing); + return is_playing; } static void @@ -284,6 +293,7 @@ android_media_MediaPlayer_seekTo(JNIEnv *env, jobject thiz, int msec) jniThrowException(env, "java/lang/IllegalStateException", NULL); return; } + LOGV("seekTo: %d(msec)", msec); process_media_player_call( env, thiz, mp->seekTo(msec), NULL, NULL ); } @@ -296,9 +306,12 @@ android_media_MediaPlayer_getVideoWidth(JNIEnv *env, jobject thiz) return 0; } int w; - if (0 == mp->getVideoWidth(&w)) - return w; - return 0; + if (0 != mp->getVideoWidth(&w)) { + LOGE("getVideoWidth failed"); + w = 0; + } + LOGV("getVideoWidth: %d", w); + return w; } static int @@ -310,9 +323,12 @@ android_media_MediaPlayer_getVideoHeight(JNIEnv *env, jobject thiz) return 0; } int h; - if (0 == mp->getVideoHeight(&h)) - return h; - return 0; + if (0 != mp->getVideoHeight(&h)) { + LOGE("getVideoHeight failed"); + h = 0; + } + LOGV("getVideoHeight: %d", h); + return h; } @@ -326,6 +342,7 @@ android_media_MediaPlayer_getCurrentPosition(JNIEnv *env, jobject thiz) } int msec; process_media_player_call( env, thiz, mp->getCurrentPosition(&msec), NULL, NULL ); + LOGV("getCurrentPosition: %d (msec)", msec); return msec; } @@ -339,12 +356,14 @@ android_media_MediaPlayer_getDuration(JNIEnv *env, jobject thiz) } int msec; process_media_player_call( env, thiz, mp->getDuration(&msec), NULL, NULL ); + LOGV("getDuration: %d (msec)", msec); return msec; } static void android_media_MediaPlayer_reset(JNIEnv *env, jobject thiz) { + LOGV("reset"); sp mp = getMediaPlayer(env, thiz); if (mp == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", NULL); @@ -356,6 +375,7 @@ android_media_MediaPlayer_reset(JNIEnv *env, jobject thiz) static void android_media_MediaPlayer_setAudioStreamType(JNIEnv *env, jobject thiz, int streamtype) { + LOGV("setAudioStreamType: %d", streamtype); sp mp = getMediaPlayer(env, thiz); if (mp == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", NULL); @@ -367,6 +387,7 @@ android_media_MediaPlayer_setAudioStreamType(JNIEnv *env, jobject thiz, int stre static void android_media_MediaPlayer_setLooping(JNIEnv *env, jobject thiz, jboolean looping) { + LOGV("setLooping: %d", looping); sp mp = getMediaPlayer(env, thiz); if (mp == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", NULL); @@ -378,6 +399,7 @@ android_media_MediaPlayer_setLooping(JNIEnv *env, jobject thiz, jboolean looping static jboolean android_media_MediaPlayer_isLooping(JNIEnv *env, jobject thiz) { + LOGV("isLooping"); sp mp = getMediaPlayer(env, thiz); if (mp == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", NULL); @@ -389,6 +411,7 @@ android_media_MediaPlayer_isLooping(JNIEnv *env, jobject thiz) static void android_media_MediaPlayer_setVolume(JNIEnv *env, jobject thiz, float leftVolume, float rightVolume) { + LOGV("setVolume: left %f right %f", leftVolume, rightVolume); sp mp = getMediaPlayer(env, thiz); if (mp == NULL ) { jniThrowException(env, "java/lang/IllegalStateException", NULL); @@ -570,4 +593,3 @@ bail: } // KTHXBYE - diff --git a/media/jni/android_media_MediaRecorder.cpp b/media/jni/android_media_MediaRecorder.cpp index 2810a9cc9ad5552f5a32f89b103632c40a3d64ab..1e508d29e27a35bab0309e44582d42c239c291bb 100644 --- a/media/jni/android_media_MediaRecorder.cpp +++ b/media/jni/android_media_MediaRecorder.cpp @@ -41,16 +41,68 @@ using namespace android; // ---------------------------------------------------------------------------- // helper function to extract a native Camera object from a Camera Java object -extern sp get_native_camera(JNIEnv *env, jobject thiz); +extern sp get_native_camera(JNIEnv *env, jobject thiz, struct camera_context_t** context); struct fields_t { jfieldID context; jfieldID surface; /* actually in android.view.Surface XXX */ jfieldID surface_native; + + jmethodID post_event; }; static fields_t fields; +static Mutex sLock; + +// ---------------------------------------------------------------------------- +// ref-counted object for callbacks +class JNIMediaRecorderListener: public MediaRecorderListener +{ +public: + JNIMediaRecorderListener(JNIEnv* env, jobject thiz, jobject weak_thiz); + ~JNIMediaRecorderListener(); + void notify(int msg, int ext1, int ext2); +private: + JNIMediaRecorderListener(); + jclass mClass; // Reference to MediaRecorder class + jobject mObject; // Weak ref to MediaRecorder Java object to call on +}; + +JNIMediaRecorderListener::JNIMediaRecorderListener(JNIEnv* env, jobject thiz, jobject weak_thiz) +{ + + // Hold onto the MediaRecorder class for use in calling the static method + // that posts events to the application thread. + jclass clazz = env->GetObjectClass(thiz); + if (clazz == NULL) { + LOGE("Can't find android/media/MediaRecorder"); + jniThrowException(env, "java/lang/Exception", NULL); + return; + } + mClass = (jclass)env->NewGlobalRef(clazz); + + // We use a weak reference so the MediaRecorder object can be garbage collected. + // The reference is only used as a proxy for callbacks. + mObject = env->NewGlobalRef(weak_thiz); +} + +JNIMediaRecorderListener::~JNIMediaRecorderListener() +{ + // remove global references + JNIEnv *env = AndroidRuntime::getJNIEnv(); + env->DeleteGlobalRef(mObject); + env->DeleteGlobalRef(mClass); +} + +void JNIMediaRecorderListener::notify(int msg, int ext1, int ext2) +{ + LOGV("JNIMediaRecorderListener::notify"); + + JNIEnv *env = AndroidRuntime::getJNIEnv(); + env->CallStaticVoidMethod(mClass, fields.post_event, mObject, msg, ext1, ext2, 0); +} + // ---------------------------------------------------------------------------- static sp get_surface(JNIEnv* env, jobject clazz) @@ -60,21 +112,46 @@ static sp get_surface(JNIEnv* env, jobject clazz) return sp(p); } -static void process_media_recorder_call(JNIEnv *env, status_t opStatus, const char* exception, const char* message) +// Returns true if it throws an exception. +static bool process_media_recorder_call(JNIEnv *env, status_t opStatus, const char* exception, const char* message) { LOGV("process_media_recorder_call"); if (opStatus == (status_t)INVALID_OPERATION) { jniThrowException(env, "java/lang/IllegalStateException", NULL); + return true; } else if (opStatus != (status_t)OK) { jniThrowException(env, exception, message); + return true; + } + return false; +} + +static sp getMediaRecorder(JNIEnv* env, jobject thiz) +{ + Mutex::Autolock l(sLock); + MediaRecorder* const p = (MediaRecorder*)env->GetIntField(thiz, fields.context); + return sp(p); +} + +static sp setMediaRecorder(JNIEnv* env, jobject thiz, const sp& recorder) +{ + Mutex::Autolock l(sLock); + sp old = (MediaRecorder*)env->GetIntField(thiz, fields.context); + if (recorder.get()) { + recorder->incStrong(thiz); + } + if (old != 0) { + old->decStrong(thiz); } - return; + env->SetIntField(thiz, fields.context, (int)recorder.get()); + return old; } + static void android_media_MediaRecorder_setCamera(JNIEnv* env, jobject thiz, jobject camera) { - sp c = get_native_camera(env, camera); - MediaRecorder *mr = (MediaRecorder*)env->GetIntField(thiz, fields.context); + sp c = get_native_camera(env, camera, NULL); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->setCamera(c->remote()), "java/lang/RuntimeException", "setCamera failed."); } @@ -87,7 +164,7 @@ android_media_MediaRecorder_setVideoSource(JNIEnv *env, jobject thiz, jint vs) jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid video source"); return; } - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->setVideoSource(vs), "java/lang/RuntimeException", "setVideoSource failed."); } @@ -99,7 +176,7 @@ android_media_MediaRecorder_setAudioSource(JNIEnv *env, jobject thiz, jint as) jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid audio source"); return; } - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->setAudioSource(as), "java/lang/RuntimeException", "setAudioSource failed."); } @@ -111,7 +188,7 @@ android_media_MediaRecorder_setOutputFormat(JNIEnv *env, jobject thiz, jint of) jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid output format"); return; } - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->setOutputFormat(of), "java/lang/RuntimeException", "setOutputFormat failed."); } @@ -123,7 +200,7 @@ android_media_MediaRecorder_setVideoEncoder(JNIEnv *env, jobject thiz, jint ve) jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid video encoder"); return; } - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->setVideoEncoder(ve), "java/lang/RuntimeException", "setVideoEncoder failed."); } @@ -135,37 +212,29 @@ android_media_MediaRecorder_setAudioEncoder(JNIEnv *env, jobject thiz, jint ae) jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid audio encoder"); return; } - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->setAudioEncoder(ae), "java/lang/RuntimeException", "setAudioEncoder failed."); } static void -android_media_MediaRecorder_setOutputFile(JNIEnv *env, jobject thiz, jstring path) +android_media_MediaRecorder_setOutputFileFD(JNIEnv *env, jobject thiz, jobject fileDescriptor, jlong offset, jlong length) { LOGV("setOutputFile"); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); - - if (path == NULL) { - jniThrowException(env, "java/lang/IllegalArgumentException", "Path is a NULL pointer"); + if (fileDescriptor == NULL) { + jniThrowException(env, "java/lang/IllegalArgumentException", NULL); return; } - const char *pathStr = env->GetStringUTFChars(path, NULL); - if (pathStr == NULL) { // Out of memory - jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); - return; - } - status_t opStatus = mr->setOutputFile(pathStr); - - // Make sure that local ref is released before a potential exception - env->ReleaseStringUTFChars(path, pathStr); - process_media_recorder_call(env, opStatus, "java/lang/RuntimeException", "setOutputFile failed."); + int fd = getParcelFileDescriptorFD(env, fileDescriptor); + sp mr = getMediaRecorder(env, thiz); + status_t opStatus = mr->setOutputFile(fd, offset, length); + process_media_recorder_call(env, opStatus, "java/io/IOException", "setOutputFile failed."); } static void android_media_MediaRecorder_setVideoSize(JNIEnv *env, jobject thiz, jint width, jint height) { LOGV("setVideoSize(%d, %d)", width, height); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); if (width <= 0 || height <= 0) { jniThrowException(env, "java/lang/IllegalArgumentException", "invalid video size"); @@ -182,21 +251,35 @@ android_media_MediaRecorder_setVideoFrameRate(JNIEnv *env, jobject thiz, jint ra jniThrowException(env, "java/lang/IllegalArgumentException", "invalid frame rate"); return; } - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->setVideoFrameRate(rate), "java/lang/RuntimeException", "setVideoFrameRate failed."); } +static void +android_media_MediaRecorder_setMaxDuration(JNIEnv *env, jobject thiz, jint max_duration_ms) +{ + LOGV("setMaxDuration(%d)", max_duration_ms); + sp mr = getMediaRecorder(env, thiz); + + char params[64]; + sprintf(params, "max-duration=%d", max_duration_ms); + + process_media_recorder_call(env, mr->setParameters(String8(params)), "java/lang/RuntimeException", "setMaxDuration failed."); +} + static void android_media_MediaRecorder_prepare(JNIEnv *env, jobject thiz) { LOGV("prepare"); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); jobject surface = env->GetObjectField(thiz, fields.surface); if (surface != NULL) { const sp& native_surface = get_surface(env, surface); LOGI("prepare: surface=%p (id=%d)", native_surface.get(), native_surface->ID()); - process_media_recorder_call(env, mr->setPreviewSurface(native_surface), "java/lang/RuntimeException", "setPreviewSurface failed."); + if (process_media_recorder_call(env, mr->setPreviewSurface(native_surface), "java/lang/RuntimeException", "setPreviewSurface failed.")) { + return; + } } process_media_recorder_call(env, mr->prepare(), "java/io/IOException", "prepare failed."); } @@ -205,7 +288,7 @@ static int android_media_MediaRecorder_native_getMaxAmplitude(JNIEnv *env, jobject thiz) { LOGV("getMaxAmplitude"); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); int result = 0; process_media_recorder_call(env, mr->getMaxAmplitude(&result), "java/lang/RuntimeException", "getMaxAmplitude failed."); return result; @@ -215,7 +298,7 @@ static void android_media_MediaRecorder_start(JNIEnv *env, jobject thiz) { LOGV("start"); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->start(), "java/lang/RuntimeException", "start failed."); } @@ -223,68 +306,78 @@ static void android_media_MediaRecorder_stop(JNIEnv *env, jobject thiz) { LOGV("stop"); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); + sp mr = getMediaRecorder(env, thiz); process_media_recorder_call(env, mr->stop(), "java/lang/RuntimeException", "stop failed."); } static void -android_media_MediaRecorder_reset(JNIEnv *env, jobject thiz) +android_media_MediaRecorder_native_reset(JNIEnv *env, jobject thiz) { - LOGV("reset"); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); - process_media_recorder_call(env, mr->reset(), "java/lang/RuntimeException", "reset failed."); + LOGV("native_reset"); + sp mr = getMediaRecorder(env, thiz); + process_media_recorder_call(env, mr->reset(), "java/lang/RuntimeException", "native_reset failed."); } static void android_media_MediaRecorder_release(JNIEnv *env, jobject thiz) { LOGV("release"); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); - env->SetIntField(thiz, fields.context, 0); - delete mr; + sp mr = setMediaRecorder(env, thiz, 0); + if (mr != NULL) { + mr->setListener(NULL); + mr->release(); + } } static void -android_media_MediaRecorder_native_setup(JNIEnv *env, jobject thiz) +android_media_MediaRecorder_native_setup(JNIEnv *env, jobject thiz, jobject weak_this) { LOGV("setup"); - MediaRecorder *mr = new MediaRecorder(); - if (mr->initCheck() == NO_ERROR) { - env->SetIntField(thiz, fields.context, (int)mr); - } else { - delete mr; + sp mr = new MediaRecorder(); + if (mr == NULL) { + jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); + return; + } + if (mr->initCheck() != NO_ERROR) { jniThrowException(env, "java/lang/IOException", "Unable to initialize camera"); + return; } + + // create new listener and give it to MediaRecorder + sp listener = new JNIMediaRecorderListener(env, thiz, weak_this); + mr->setListener(listener); + + setMediaRecorder(env, thiz, mr); } static void android_media_MediaRecorder_native_finalize(JNIEnv *env, jobject thiz) { LOGV("finalize"); - MediaRecorder *mr = (MediaRecorder *)env->GetIntField(thiz, fields.context); - delete mr; + android_media_MediaRecorder_release(env, thiz); } // ---------------------------------------------------------------------------- static JNINativeMethod gMethods[] = { - {"setCamera", "(Landroid/hardware/Camera;)V",(void *)android_media_MediaRecorder_setCamera}, - {"setVideoSource", "(I)V", (void *)android_media_MediaRecorder_setVideoSource}, - {"setAudioSource", "(I)V", (void *)android_media_MediaRecorder_setAudioSource}, - {"setOutputFormat", "(I)V", (void *)android_media_MediaRecorder_setOutputFormat}, - {"setVideoEncoder", "(I)V", (void *)android_media_MediaRecorder_setVideoEncoder}, - {"setAudioEncoder", "(I)V", (void *)android_media_MediaRecorder_setAudioEncoder}, - {"setOutputFile", "(Ljava/lang/String;)V", (void *)android_media_MediaRecorder_setOutputFile}, - {"setVideoSize", "(II)V", (void *)android_media_MediaRecorder_setVideoSize}, - {"setVideoFrameRate", "(I)V", (void *)android_media_MediaRecorder_setVideoFrameRate}, - {"prepare", "()V", (void *)android_media_MediaRecorder_prepare}, - {"getMaxAmplitude", "()I", (void *)android_media_MediaRecorder_native_getMaxAmplitude}, - {"start", "()V", (void *)android_media_MediaRecorder_start}, - {"stop", "()V", (void *)android_media_MediaRecorder_stop}, - {"reset", "()V", (void *)android_media_MediaRecorder_reset}, - {"release", "()V", (void *)android_media_MediaRecorder_release}, - {"native_setup", "()V", (void *)android_media_MediaRecorder_native_setup}, - {"native_finalize", "()V", (void *)android_media_MediaRecorder_native_finalize}, + {"setCamera", "(Landroid/hardware/Camera;)V", (void *)android_media_MediaRecorder_setCamera}, + {"setVideoSource", "(I)V", (void *)android_media_MediaRecorder_setVideoSource}, + {"setAudioSource", "(I)V", (void *)android_media_MediaRecorder_setAudioSource}, + {"setOutputFormat", "(I)V", (void *)android_media_MediaRecorder_setOutputFormat}, + {"setVideoEncoder", "(I)V", (void *)android_media_MediaRecorder_setVideoEncoder}, + {"setAudioEncoder", "(I)V", (void *)android_media_MediaRecorder_setAudioEncoder}, + {"_setOutputFile", "(Ljava/io/FileDescriptor;JJ)V", (void *)android_media_MediaRecorder_setOutputFileFD}, + {"setVideoSize", "(II)V", (void *)android_media_MediaRecorder_setVideoSize}, + {"setVideoFrameRate", "(I)V", (void *)android_media_MediaRecorder_setVideoFrameRate}, + {"setMaxDuration", "(I)V", (void *)android_media_MediaRecorder_setMaxDuration}, + {"_prepare", "()V", (void *)android_media_MediaRecorder_prepare}, + {"getMaxAmplitude", "()I", (void *)android_media_MediaRecorder_native_getMaxAmplitude}, + {"start", "()V", (void *)android_media_MediaRecorder_start}, + {"stop", "()V", (void *)android_media_MediaRecorder_stop}, + {"native_reset", "()V", (void *)android_media_MediaRecorder_native_reset}, + {"release", "()V", (void *)android_media_MediaRecorder_release}, + {"native_setup", "(Ljava/lang/Object;)V", (void *)android_media_MediaRecorder_native_setup}, + {"native_finalize", "()V", (void *)android_media_MediaRecorder_native_finalize}, }; static const char* const kClassPathName = "android/media/MediaRecorder"; @@ -323,6 +416,13 @@ int register_android_media_MediaRecorder(JNIEnv *env) return -1; } + fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative", + "(Ljava/lang/Object;IIILjava/lang/Object;)V"); + if (fields.post_event == NULL) { + LOGE("Can't find MediaRecorder.postEventFromNative"); + return -1; + } + return AndroidRuntime::registerNativeMethods(env, "android/media/MediaRecorder", gMethods, NELEM(gMethods)); } diff --git a/media/jni/soundpool/SoundPool.cpp b/media/jni/soundpool/SoundPool.cpp index 7872a8df7d5c5304af7493b69144d64686586c26..02731825e08794a17132caed973b6f46486e632a 100644 --- a/media/jni/soundpool/SoundPool.cpp +++ b/media/jni/soundpool/SoundPool.cpp @@ -64,13 +64,6 @@ SoundPool::SoundPool(jobject soundPoolRef, int maxChannels, int streamType, int mChannels.push_back(&mChannelPool[i]); } - if (AudioSystem::getOutputFrameCount(&mFrameCount) != NO_ERROR) { - mFrameCount = kDefaultFrameCount; - } - if (AudioSystem::getOutputSamplingRate(&mSampleRate) != NO_ERROR) { - mSampleRate = kDefaultSampleRate; - } - // start decode thread startThreads(); } @@ -481,8 +474,8 @@ void SoundChannel::play(const sp& sample, int nextChannelID, float leftV { AudioTrack* oldTrack; - LOGV("play: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f", - sample->sampleID(), nextChannelID, leftVolume, rightVolume, priority, loop, rate); + LOGV("play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f", + this, sample->sampleID(), nextChannelID, leftVolume, rightVolume, priority, loop, rate); // if not idle, this voice is being stolen if (mState != IDLE) { @@ -496,9 +489,18 @@ void SoundChannel::play(const sp& sample, int nextChannelID, float leftV } // initialize track + int afFrameCount; + int afSampleRate; + int streamType = mSoundPool->streamType(); + if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) { + afFrameCount = kDefaultFrameCount; + } + if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) { + afSampleRate = kDefaultSampleRate; + } int numChannels = sample->numChannels(); uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5); - uint32_t bufferFrames = (mSoundPool->mFrameCount * sampleRate) / mSoundPool->mSampleRate; + uint32_t bufferFrames = (afFrameCount * sampleRate) / afSampleRate; uint32_t frameCount = 0; if (loop) { @@ -511,12 +513,21 @@ void SoundChannel::play(const sp& sample, int nextChannelID, float leftV } AudioTrack* newTrack; + + // mToggle toggles each time a track is started on a given channel. + // The toggle is concatenated with the SoundChannel address and passed to AudioTrack + // as callback user data. This enables the detection of callbacks received from the old + // audio track while the new one is being started and avoids processing them with + // wrong audio audio buffer size (mAudioBufferSize) + unsigned long toggle = mToggle ^ 1; + void *userData = (void *)((unsigned long)this | toggle); + #ifdef USE_SHARED_MEM_BUFFER - newTrack = new AudioTrack(mSoundPool->streamType(), sampleRate, sample->format(), - numChannels, sample->getIMemory(), 0, callback, this); + newTrack = new AudioTrack(streamType, sampleRate, sample->format(), + numChannels, sample->getIMemory(), 0, callback, userData); #else - newTrack = new AudioTrack(mSoundPool->streamType(), sampleRate, sample->format(), - numChannels, frameCount, 0, callback, this, bufferFrames); + newTrack = new AudioTrack(streamType, sampleRate, sample->format(), + numChannels, frameCount, 0, callback, userData, bufferFrames); #endif if (newTrack->initCheck() != NO_ERROR) { LOGE("Error creating AudioTrack"); @@ -529,6 +540,8 @@ void SoundChannel::play(const sp& sample, int nextChannelID, float leftV { Mutex::Autolock lock(&mLock); + // From now on, AudioTrack callbacks recevieved with previous toggle value will be ignored. + mToggle = toggle; oldTrack = mAudioTrack; mAudioTrack = newTrack; mPos = 0; @@ -583,7 +596,13 @@ void SoundChannel::nextEvent() void SoundChannel::callback(int event, void* user, void *info) { - SoundChannel* channel = static_cast(user); + unsigned long toggle = (unsigned long)user & 1; + SoundChannel* channel = static_cast((void *)((unsigned long)user & ~1)); + + if (channel->mToggle != toggle) { + LOGV("callback with wrong toggle"); + return; + } channel->process(event, info); } @@ -592,7 +611,7 @@ void SoundChannel::process(int event, void *info) //LOGV("process(%d)", mChannelID); sp sample = mSample; - LOGV("SoundChannel::process event %d", event); +// LOGV("SoundChannel::process event %d", event); if (event == AudioTrack::EVENT_MORE_DATA) { AudioTrack::Buffer* b = static_cast(info); diff --git a/media/jni/soundpool/SoundPool.h b/media/jni/soundpool/SoundPool.h index d02ae8b5a4e7579f5516496c6ea43d84e1cb177a..78027812fb95649ee23c37fbbd4f26c6e3ca9649 100644 --- a/media/jni/soundpool/SoundPool.h +++ b/media/jni/soundpool/SoundPool.h @@ -118,7 +118,7 @@ protected: class SoundChannel : public SoundEvent { public: enum state { IDLE, RESUMING, STOPPING, PAUSED, PLAYING }; - SoundChannel() : mAudioTrack(0), mState(IDLE), mNumChannels(1), mPos(0) {} + SoundChannel() : mAudioTrack(0), mState(IDLE), mNumChannels(1), mPos(0), mToggle(0) {} ~SoundChannel(); void init(SoundPool* soundPool); void play(const sp& sample, int channelID, float leftVolume, float rightVolume, @@ -151,6 +151,7 @@ private: int mNumChannels; int mPos; int mAudioBufferSize; + unsigned long mToggle; }; // application object for managing a pool of sounds @@ -215,8 +216,6 @@ private: int mAllocated; int mNextSampleID; int mNextChannelID; - int mFrameCount; - int mSampleRate; bool mQuit; }; diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk index 2a697b95232f10f1b54de4a753809472360112a3..8020da2b61005764c23a83465e4598535ee636b5 100644 --- a/media/libmedia/Android.mk +++ b/media/libmedia/Android.mk @@ -4,6 +4,7 @@ include $(CLEAR_VARS) LOCAL_SRC_FILES:= \ AudioTrack.cpp \ IAudioFlinger.cpp \ + IAudioFlingerClient.cpp \ IAudioTrack.cpp \ IAudioRecord.cpp \ AudioRecord.cpp \ diff --git a/media/libmedia/AudioRecord.cpp b/media/libmedia/AudioRecord.cpp index e833c85a7890ca511b42c299512cde03e6d5fff5..7594ff0ca0668ca798479f11c2ae795a0fd170fd 100644 --- a/media/libmedia/AudioRecord.cpp +++ b/media/libmedia/AudioRecord.cpp @@ -128,8 +128,23 @@ status_t AudioRecord::set( return BAD_VALUE; } - // TODO: Get input frame count from hardware. - int minFrameCount = 1024*2; + // validate framecount + size_t inputBuffSizeInBytes = -1; + if (AudioSystem::getInputBufferSize(sampleRate, format, channelCount, &inputBuffSizeInBytes) + != NO_ERROR) { + LOGE("AudioSystem could not query the input buffer size."); + return NO_INIT; + } + if (inputBuffSizeInBytes == 0) { + LOGE("Recording parameters are not supported: sampleRate %d, channelCount %d, format %d", + sampleRate, channelCount, format); + return BAD_VALUE; + } + int frameSizeInBytes = channelCount * (format == AudioSystem::PCM_16_BIT ? 2 : 1); + + // We use 2* size of input buffer for ping pong use of record buffer. + int minFrameCount = 2 * inputBuffSizeInBytes / frameSizeInBytes; + LOGV("AudioRecord::set() minFrameCount = %d", minFrameCount); if (frameCount == 0) { frameCount = minFrameCount; @@ -144,7 +159,11 @@ status_t AudioRecord::set( // open record channel status_t status; sp record = audioFlinger->openRecord(getpid(), streamType, - sampleRate, format, channelCount, frameCount, flags, &status); + sampleRate, format, + channelCount, + frameCount, + ((uint16_t)flags) << 16, + &status); if (record == 0) { LOGE("AudioFlinger could not create record track, status: %d", status); return status; diff --git a/media/libmedia/AudioSystem.cpp b/media/libmedia/AudioSystem.cpp index a375b55a63690c39cc02b37e926b4a939544f52a..63dfc3b368b341576a17791993570d3672416b1f 100644 --- a/media/libmedia/AudioSystem.cpp +++ b/media/libmedia/AudioSystem.cpp @@ -15,10 +15,11 @@ */ #define LOG_TAG "AudioSystem" +//#define LOG_NDEBUG 0 + #include #include #include -#include #include namespace android { @@ -26,12 +27,18 @@ namespace android { // client singleton for AudioFlinger binder interface Mutex AudioSystem::gLock; sp AudioSystem::gAudioFlinger; -sp AudioSystem::gDeathNotifier; +sp AudioSystem::gAudioFlingerClient; audio_error_callback AudioSystem::gAudioErrorCallback = NULL; // Cached values -int AudioSystem::gOutSamplingRate = 0; -int AudioSystem::gOutFrameCount = 0; -uint32_t AudioSystem::gOutLatency = 0; +int AudioSystem::gOutSamplingRate[NUM_AUDIO_OUTPUT_TYPES]; +int AudioSystem::gOutFrameCount[NUM_AUDIO_OUTPUT_TYPES]; +uint32_t AudioSystem::gOutLatency[NUM_AUDIO_OUTPUT_TYPES]; +bool AudioSystem::gA2dpEnabled; +// Cached values for recording queries +uint32_t AudioSystem::gPrevInSamplingRate = 16000; +int AudioSystem::gPrevInFormat = AudioSystem::PCM_16_BIT; +int AudioSystem::gPrevInChannelCount = 1; +size_t AudioSystem::gInBuffSize = 0; // establish binder interface to AudioFlinger service @@ -48,19 +55,23 @@ const sp& AudioSystem::get_audio_flinger() LOGW("AudioFlinger not published, waiting..."); usleep(500000); // 0.5 s } while(true); - if (gDeathNotifier == NULL) { - gDeathNotifier = new DeathNotifier(); + if (gAudioFlingerClient == NULL) { + gAudioFlingerClient = new AudioFlingerClient(); } else { if (gAudioErrorCallback) { gAudioErrorCallback(NO_ERROR); } } - binder->linkToDeath(gDeathNotifier); + binder->linkToDeath(gAudioFlingerClient); gAudioFlinger = interface_cast(binder); + gAudioFlinger->registerClient(gAudioFlingerClient); // Cache frequently accessed parameters - gOutFrameCount = (int)gAudioFlinger->frameCount(); - gOutSamplingRate = (int)gAudioFlinger->sampleRate(); - gOutLatency = gAudioFlinger->latency(); + for (int output = 0; output < NUM_AUDIO_OUTPUT_TYPES; output++) { + gOutFrameCount[output] = (int)gAudioFlinger->frameCount(output); + gOutSamplingRate[output] = (int)gAudioFlinger->sampleRate(output); + gOutLatency[output] = gAudioFlinger->latency(output); + } + gA2dpEnabled = gAudioFlinger->isA2dpEnabled(); } LOGE_IF(gAudioFlinger==0, "no AudioFlinger!?"); return gAudioFlinger; @@ -139,7 +150,7 @@ status_t AudioSystem::getMasterMute(bool* mute) status_t AudioSystem::setStreamVolume(int stream, float value) { - if (uint32_t(stream) >= AudioTrack::NUM_STREAM_TYPES) return BAD_VALUE; + if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE; const sp& af = AudioSystem::get_audio_flinger(); if (af == 0) return PERMISSION_DENIED; af->setStreamVolume(stream, value); @@ -148,7 +159,7 @@ status_t AudioSystem::setStreamVolume(int stream, float value) status_t AudioSystem::setStreamMute(int stream, bool mute) { - if (uint32_t(stream) >= AudioTrack::NUM_STREAM_TYPES) return BAD_VALUE; + if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE; const sp& af = AudioSystem::get_audio_flinger(); if (af == 0) return PERMISSION_DENIED; af->setStreamMute(stream, mute); @@ -157,7 +168,7 @@ status_t AudioSystem::setStreamMute(int stream, bool mute) status_t AudioSystem::getStreamVolume(int stream, float* volume) { - if (uint32_t(stream) >= AudioTrack::NUM_STREAM_TYPES) return BAD_VALUE; + if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE; const sp& af = AudioSystem::get_audio_flinger(); if (af == 0) return PERMISSION_DENIED; *volume = af->streamVolume(stream); @@ -166,7 +177,7 @@ status_t AudioSystem::getStreamVolume(int stream, float* volume) status_t AudioSystem::getStreamMute(int stream, bool* mute) { - if (uint32_t(stream) >= AudioTrack::NUM_STREAM_TYPES) return BAD_VALUE; + if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE; const sp& af = AudioSystem::get_audio_flinger(); if (af == 0) return PERMISSION_DENIED; *mute = af->streamMute(stream); @@ -244,60 +255,129 @@ int AudioSystem::logToLinear(float volume) return volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0; } -status_t AudioSystem::getOutputSamplingRate(int* samplingRate) +status_t AudioSystem::getOutputSamplingRate(int* samplingRate, int streamType) { - if (gOutSamplingRate == 0) { + int output = getOutput(streamType); + + if (gOutSamplingRate[output] == 0) { const sp& af = AudioSystem::get_audio_flinger(); if (af == 0) return PERMISSION_DENIED; // gOutSamplingRate is updated by get_audio_flinger() - } - *samplingRate = gOutSamplingRate; + } + LOGV("getOutputSamplingRate() streamType %d, output %d, sampling rate %d", streamType, output, gOutSamplingRate[output]); + *samplingRate = gOutSamplingRate[output]; return NO_ERROR; } -status_t AudioSystem::getOutputFrameCount(int* frameCount) +status_t AudioSystem::getOutputFrameCount(int* frameCount, int streamType) { - if (gOutFrameCount == 0) { + int output = getOutput(streamType); + + if (gOutFrameCount[output] == 0) { const sp& af = AudioSystem::get_audio_flinger(); if (af == 0) return PERMISSION_DENIED; - // gOutSamplingRate is updated by get_audio_flinger() + // gOutFrameCount is updated by get_audio_flinger() } - *frameCount = gOutFrameCount; + LOGV("getOutputFrameCount() streamType %d, output %d, frame count %d", streamType, output, gOutFrameCount[output]); + + *frameCount = gOutFrameCount[output]; return NO_ERROR; } -status_t AudioSystem::getOutputLatency(uint32_t* latency) +status_t AudioSystem::getOutputLatency(uint32_t* latency, int streamType) { - if (gOutLatency == 0) { + int output = getOutput(streamType); + + if (gOutLatency[output] == 0) { const sp& af = AudioSystem::get_audio_flinger(); if (af == 0) return PERMISSION_DENIED; // gOutLatency is updated by get_audio_flinger() - } - *latency = gOutLatency; + } + LOGV("getOutputLatency() streamType %d, output %d, latency %d", streamType, output, gOutLatency[output]); + + *latency = gOutLatency[output]; + + return NO_ERROR; +} + +status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, int format, int channelCount, + size_t* buffSize) +{ + // Do we have a stale gInBufferSize or are we requesting the input buffer size for new values + if ((gInBuffSize == 0) || (sampleRate != gPrevInSamplingRate) || (format != gPrevInFormat) + || (channelCount != gPrevInChannelCount)) { + // save the request params + gPrevInSamplingRate = sampleRate; + gPrevInFormat = format; + gPrevInChannelCount = channelCount; + + gInBuffSize = 0; + const sp& af = AudioSystem::get_audio_flinger(); + if (af == 0) { + return PERMISSION_DENIED; + } + gInBuffSize = af->getInputBufferSize(sampleRate, format, channelCount); + } + *buffSize = gInBuffSize; return NO_ERROR; } // --------------------------------------------------------------------------- -void AudioSystem::DeathNotifier::binderDied(const wp& who) { +void AudioSystem::AudioFlingerClient::binderDied(const wp& who) { Mutex::Autolock _l(AudioSystem::gLock); AudioSystem::gAudioFlinger.clear(); - AudioSystem::gOutSamplingRate = 0; - AudioSystem::gOutFrameCount = 0; - AudioSystem::gOutLatency = 0; - + + for (int output = 0; output < NUM_AUDIO_OUTPUT_TYPES; output++) { + gOutFrameCount[output] = 0; + gOutSamplingRate[output] = 0; + gOutLatency[output] = 0; + } + AudioSystem::gInBuffSize = 0; + if (gAudioErrorCallback) { gAudioErrorCallback(DEAD_OBJECT); } LOGW("AudioFlinger server died!"); } +void AudioSystem::AudioFlingerClient::a2dpEnabledChanged(bool enabled) { + gA2dpEnabled = enabled; + LOGV("AudioFlinger A2DP enabled status changed! %d", enabled); +} + void AudioSystem::setErrorCallback(audio_error_callback cb) { Mutex::Autolock _l(AudioSystem::gLock); gAudioErrorCallback = cb; } +int AudioSystem::getOutput(int streamType) +{ + if (streamType == DEFAULT) { + streamType = MUSIC; + } + if (gA2dpEnabled && routedToA2dpOutput(streamType)) { + return AUDIO_OUTPUT_A2DP; + } else { + return AUDIO_OUTPUT_HARDWARE; + } +} + +bool AudioSystem::routedToA2dpOutput(int streamType) { + switch(streamType) { + case MUSIC: + case VOICE_CALL: + case BLUETOOTH_SCO: + case SYSTEM: + return true; + default: + return false; + } +} + + + }; // namespace android diff --git a/media/libmedia/AudioTrack.cpp b/media/libmedia/AudioTrack.cpp index f9f8568c969a5513d343628b21d62885de52cb4a..d26b0c578052afa9643c6fa8185e5ca9e7ebc35b 100644 --- a/media/libmedia/AudioTrack.cpp +++ b/media/libmedia/AudioTrack.cpp @@ -128,22 +128,21 @@ status_t AudioTrack::set( return NO_INIT; } int afSampleRate; - if (AudioSystem::getOutputSamplingRate(&afSampleRate) != NO_ERROR) { + if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) { return NO_INIT; } int afFrameCount; - if (AudioSystem::getOutputFrameCount(&afFrameCount) != NO_ERROR) { + if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) { return NO_INIT; } uint32_t afLatency; - if (AudioSystem::getOutputLatency(&afLatency) != NO_ERROR) { + if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) { return NO_INIT; } - // handle default values first. - if (streamType == DEFAULT) { - streamType = MUSIC; + if (streamType == AudioSystem::DEFAULT) { + streamType = AudioSystem::MUSIC; } if (sampleRate == 0) { sampleRate = afSampleRate; @@ -157,7 +156,7 @@ status_t AudioTrack::set( } // validate parameters - if (((format != AudioSystem::PCM_8_BIT) || mSharedBuffer != 0) && + if (((format != AudioSystem::PCM_8_BIT) || sharedBuffer != 0) && (format != AudioSystem::PCM_16_BIT)) { LOGE("Invalid format"); return BAD_VALUE; @@ -169,6 +168,8 @@ status_t AudioTrack::set( // Ensure that buffer depth covers at least audio hardware latency uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate); + if (minBufCount < 2) minBufCount = 2; + // When playing from shared buffer, playback will start even if last audioflinger // block is partly filled. if (sharedBuffer != 0 && minBufCount > 1) { @@ -260,7 +261,7 @@ status_t AudioTrack::set( mMarkerPosition = 0; mNewPosition = 0; mUpdatePeriod = 0; - + return NO_ERROR; } @@ -317,7 +318,7 @@ void AudioTrack::start() { sp t = mAudioTrackThread; - LOGV("start"); + LOGV("start %p", this); if (t != 0) { if (t->exitPending()) { if (t->requestExitAndWait() == WOULD_BLOCK) { @@ -349,7 +350,7 @@ void AudioTrack::stop() { sp t = mAudioTrackThread; - LOGV("stop"); + LOGV("stop %p", this); if (t != 0) { t->mLock.lock(); } @@ -434,12 +435,12 @@ void AudioTrack::setSampleRate(int rate) { int afSamplingRate; - if (AudioSystem::getOutputSamplingRate(&afSamplingRate) != NO_ERROR) { + if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) { return; } // Resampler implementation limits input sampling rate to 2 x output sampling rate. + if (rate <= 0) rate = 1; if (rate > afSamplingRate*2) rate = afSamplingRate*2; - if (rate > MAX_SAMPLE_RATE) rate = MAX_SAMPLE_RATE; mCblk->sampleRate = rate; @@ -467,10 +468,15 @@ status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount if (loopStart >= loopEnd || loopEnd - loopStart > mFrameCount) { - LOGW("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user); + LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user); return BAD_VALUE; } - // TODO handle shared buffer here: limit loop end to framecount + + if ((mSharedBuffer != 0) && (loopEnd > mFrameCount)) { + LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d", + loopStart, loopEnd, mFrameCount); + return BAD_VALUE; + } cblk->loopStart = loopStart; cblk->loopEnd = loopEnd; @@ -603,13 +609,20 @@ status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount) if (__builtin_expect(result!=NO_ERROR, false)) { cblk->waitTimeMs += WAIT_PERIOD_MS; if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) { - LOGW( "obtainBuffer timed out (is the CPU pegged?) " - "user=%08x, server=%08x", cblk->user, cblk->server); - mAudioTrack->start(); // FIXME: Wake up audioflinger - timeout = 1; + // timing out when a loop has been set and we have already written upto loop end + // is a normal condition: no need to wake AudioFlinger up. + if (cblk->user < cblk->loopEnd) { + LOGW( "obtainBuffer timed out (is the CPU pegged?) %p " + "user=%08x, server=%08x", this, cblk->user, cblk->server); + //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140) + cblk->lock.unlock(); + mAudioTrack->start(); + cblk->lock.lock(); + timeout = 1; + } cblk->waitTimeMs = 0; } - ; + if (--waitCount == 0) { return TIMED_OUT; } @@ -668,7 +681,7 @@ ssize_t AudioTrack::write(const void* buffer, size_t userSize) return BAD_VALUE; } - LOGV("write %d bytes, mActive=%d", userSize, mActive); + LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive); ssize_t written = 0; const int8_t *src = (const int8_t *)buffer; @@ -795,7 +808,14 @@ bool AudioTrack::processAudioBuffer(const sp& thread) writtenSize = audioBuffer.size; // Sanity check on returned size - if (ssize_t(writtenSize) <= 0) break; + if (ssize_t(writtenSize) <= 0) { + // The callback is done filling buffers + // Keep this thread going to handle timed events and + // still try to get more data in intervals of WAIT_PERIOD_MS + // but don't just loop and block the CPU, so wait + usleep(WAIT_PERIOD_MS*1000); + break; + } if (writtenSize > reqSize) writtenSize = reqSize; if (mFormat == AudioSystem::PCM_8_BIT) { diff --git a/media/libmedia/IAudioFlinger.cpp b/media/libmedia/IAudioFlinger.cpp index 018ea6c3469b1bb6986c0a56ce1c48e1c695f439..5cbb25ca1fc95358a15bb901f4114fb130c00774 100644 --- a/media/libmedia/IAudioFlinger.cpp +++ b/media/libmedia/IAudioFlinger.cpp @@ -51,6 +51,10 @@ enum { GET_MIC_MUTE, IS_MUSIC_ACTIVE, SET_PARAMETER, + REGISTER_CLIENT, + GET_INPUTBUFFERSIZE, + WAKE_UP, + IS_A2DP_ENABLED }; class BpAudioFlinger : public BpInterface @@ -120,42 +124,47 @@ public: return interface_cast(reply.readStrongBinder()); } - virtual uint32_t sampleRate() const + virtual uint32_t sampleRate(int output) const { Parcel data, reply; data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + data.writeInt32(output); remote()->transact(SAMPLE_RATE, data, &reply); return reply.readInt32(); } - virtual int channelCount() const + virtual int channelCount(int output) const { Parcel data, reply; data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + data.writeInt32(output); remote()->transact(CHANNEL_COUNT, data, &reply); return reply.readInt32(); } - virtual int format() const + virtual int format(int output) const { Parcel data, reply; data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + data.writeInt32(output); remote()->transact(FORMAT, data, &reply); return reply.readInt32(); } - virtual size_t frameCount() const + virtual size_t frameCount(int output) const { Parcel data, reply; data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + data.writeInt32(output); remote()->transact(FRAME_COUNT, data, &reply); return reply.readInt32(); } - virtual uint32_t latency() const + virtual uint32_t latency(int output) const { Parcel data, reply; data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + data.writeInt32(output); remote()->transact(LATENCY, data, &reply); return reply.readInt32(); } @@ -303,6 +312,41 @@ public: remote()->transact(SET_PARAMETER, data, &reply); return reply.readInt32(); } + + virtual void registerClient(const sp& client) + { + Parcel data, reply; + data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + data.writeStrongBinder(client->asBinder()); + remote()->transact(REGISTER_CLIENT, data, &reply); + } + + virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount) + { + Parcel data, reply; + data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + data.writeInt32(sampleRate); + data.writeInt32(format); + data.writeInt32(channelCount); + remote()->transact(GET_INPUTBUFFERSIZE, data, &reply); + return reply.readInt32(); + } + + virtual void wakeUp() + { + Parcel data, reply; + data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + remote()->transact(WAKE_UP, data, &reply); + return; + } + + virtual bool isA2dpEnabled() const + { + Parcel data, reply; + data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); + remote()->transact(IS_A2DP_ENABLED, data, &reply); + return (bool)reply.readInt32(); + } }; IMPLEMENT_META_INTERFACE(AudioFlinger, "android.media.IAudioFlinger"); @@ -355,27 +399,32 @@ status_t BnAudioFlinger::onTransact( } break; case SAMPLE_RATE: { CHECK_INTERFACE(IAudioFlinger, data, reply); - reply->writeInt32( sampleRate() ); + int output = data.readInt32(); + reply->writeInt32( sampleRate(output) ); return NO_ERROR; } break; case CHANNEL_COUNT: { CHECK_INTERFACE(IAudioFlinger, data, reply); - reply->writeInt32( channelCount() ); + int output = data.readInt32(); + reply->writeInt32( channelCount(output) ); return NO_ERROR; } break; case FORMAT: { CHECK_INTERFACE(IAudioFlinger, data, reply); - reply->writeInt32( format() ); + int output = data.readInt32(); + reply->writeInt32( format(output) ); return NO_ERROR; } break; case FRAME_COUNT: { CHECK_INTERFACE(IAudioFlinger, data, reply); - reply->writeInt32( frameCount() ); + int output = data.readInt32(); + reply->writeInt32( frameCount(output) ); return NO_ERROR; } break; case LATENCY: { CHECK_INTERFACE(IAudioFlinger, data, reply); - reply->writeInt32( latency() ); + int output = data.readInt32(); + reply->writeInt32( latency(output) ); return NO_ERROR; } break; case SET_MASTER_VOLUME: { @@ -470,6 +519,30 @@ status_t BnAudioFlinger::onTransact( reply->writeInt32( setParameter(key, value) ); return NO_ERROR; } break; + case REGISTER_CLIENT: { + CHECK_INTERFACE(IAudioFlinger, data, reply); + sp client = interface_cast(data.readStrongBinder()); + registerClient(client); + return NO_ERROR; + } break; + case GET_INPUTBUFFERSIZE: { + CHECK_INTERFACE(IAudioFlinger, data, reply); + uint32_t sampleRate = data.readInt32(); + int format = data.readInt32(); + int channelCount = data.readInt32(); + reply->writeInt32( getInputBufferSize(sampleRate, format, channelCount) ); + return NO_ERROR; + } break; + case WAKE_UP: { + CHECK_INTERFACE(IAudioFlinger, data, reply); + wakeUp(); + return NO_ERROR; + } break; + case IS_A2DP_ENABLED: { + CHECK_INTERFACE(IAudioFlinger, data, reply); + reply->writeInt32( (int)isA2dpEnabled() ); + return NO_ERROR; + } break; default: return BBinder::onTransact(code, data, reply, flags); } diff --git a/media/libmedia/IAudioFlingerClient.cpp b/media/libmedia/IAudioFlingerClient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5feb11fb10bbe33ff610f40128c516b2a1973aab --- /dev/null +++ b/media/libmedia/IAudioFlingerClient.cpp @@ -0,0 +1,77 @@ +/* + * 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. + */ + +#define LOG_TAG "IAudioFlingerClient" +#include + +#include +#include + +#include + +#include + +namespace android { + +enum { + AUDIO_OUTPUT_CHANGED = IBinder::FIRST_CALL_TRANSACTION +}; + +class BpAudioFlingerClient : public BpInterface +{ +public: + BpAudioFlingerClient(const sp& impl) + : BpInterface(impl) + { + } + + void a2dpEnabledChanged(bool enabled) + { + Parcel data, reply; + data.writeInterfaceToken(IAudioFlingerClient::getInterfaceDescriptor()); + data.writeInt32((int)enabled); + remote()->transact(AUDIO_OUTPUT_CHANGED, data, &reply); + } +}; + +IMPLEMENT_META_INTERFACE(AudioFlingerClient, "android.media.IAudioFlingerClient"); + +// ---------------------------------------------------------------------- + +#define CHECK_INTERFACE(interface, data, reply) \ + do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \ + LOGW("Call incorrectly routed to " #interface); \ + return PERMISSION_DENIED; \ + } } while (0) + +status_t BnAudioFlingerClient::onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) +{ + switch(code) { + case AUDIO_OUTPUT_CHANGED: { + CHECK_INTERFACE(IAudioFlingerClient, data, reply); + bool enabled = (bool)data.readInt32(); + a2dpEnabledChanged(enabled); + return NO_ERROR; + } break; + default: + return BBinder::onTransact(code, data, reply, flags); + } +} + +// ---------------------------------------------------------------------------- + +}; // namespace android diff --git a/media/libmedia/IMediaRecorder.cpp b/media/libmedia/IMediaRecorder.cpp index 1f6d59990abf031aa890b668d37c818ad2481adc..84d08c40ac67ea1ebea696826da1e9abf25d73ac 100644 --- a/media/libmedia/IMediaRecorder.cpp +++ b/media/libmedia/IMediaRecorder.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include namespace android { @@ -39,11 +40,14 @@ enum { SET_OUTPUT_FORMAT, SET_VIDEO_ENCODER, SET_AUDIO_ENCODER, - SET_OUTPUT_FILE, + SET_OUTPUT_FILE_PATH, + SET_OUTPUT_FILE_FD, SET_VIDEO_SIZE, SET_VIDEO_FRAMERATE, + SET_PARAMETERS, SET_PREVIEW_SURFACE, - SET_CAMERA + SET_CAMERA, + SET_LISTENER }; class BpMediaRecorder: public BpInterface @@ -139,7 +143,18 @@ public: Parcel data, reply; data.writeInterfaceToken(IMediaRecorder::getInterfaceDescriptor()); data.writeCString(path); - remote()->transact(SET_OUTPUT_FILE, data, &reply); + remote()->transact(SET_OUTPUT_FILE_PATH, data, &reply); + return reply.readInt32(); + } + + status_t setOutputFile(int fd, int64_t offset, int64_t length) { + LOGV("setOutputFile(%d, %lld, %lld)", fd, offset, length); + Parcel data, reply; + data.writeInterfaceToken(IMediaRecorder::getInterfaceDescriptor()); + data.writeFileDescriptor(fd); + data.writeInt64(offset); + data.writeInt64(length); + remote()->transact(SET_OUTPUT_FILE_FD, data, &reply); return reply.readInt32(); } @@ -164,6 +179,26 @@ public: return reply.readInt32(); } + status_t setParameters(const String8& params) + { + LOGV("setParameter(%s)", params.string()); + Parcel data, reply; + data.writeInterfaceToken(IMediaRecorder::getInterfaceDescriptor()); + data.writeString8(params); + remote()->transact(SET_PARAMETERS, data, &reply); + return reply.readInt32(); + } + + status_t setListener(const sp& listener) + { + LOGV("setListener(%p)", listener.get()); + Parcel data, reply; + data.writeInterfaceToken(IMediaRecorder::getInterfaceDescriptor()); + data.writeStrongBinder(listener->asBinder()); + remote()->transact(SET_LISTENER, data, &reply); + return reply.readInt32(); + } + status_t prepare() { LOGV("prepare"); @@ -330,13 +365,22 @@ status_t BnMediaRecorder::onTransact( return NO_ERROR; } break; - case SET_OUTPUT_FILE: { - LOGV("SET_OUTPUT_FILE"); + case SET_OUTPUT_FILE_PATH: { + LOGV("SET_OUTPUT_FILE_PATH"); CHECK_INTERFACE(IMediaRecorder, data, reply); const char* path = data.readCString(); reply->writeInt32(setOutputFile(path)); return NO_ERROR; } break; + case SET_OUTPUT_FILE_FD: { + LOGV("SET_OUTPUT_FILE_FD"); + CHECK_INTERFACE(IMediaRecorder, data, reply); + int fd = dup(data.readFileDescriptor()); + int64_t offset = data.readInt64(); + int64_t length = data.readInt64(); + reply->writeInt32(setOutputFile(fd, offset, length)); + return NO_ERROR; + } break; case SET_VIDEO_SIZE: { LOGV("SET_VIDEO_SIZE"); CHECK_INTERFACE(IMediaRecorder, data, reply); @@ -352,6 +396,20 @@ status_t BnMediaRecorder::onTransact( reply->writeInt32(setVideoFrameRate(frames_per_second)); return NO_ERROR; } break; + case SET_PARAMETERS: { + LOGV("SET_PARAMETER"); + CHECK_INTERFACE(IMediaRecorder, data, reply); + reply->writeInt32(setParameters(data.readString8())); + return NO_ERROR; + } break; + case SET_LISTENER: { + LOGV("SET_LISTENER"); + CHECK_INTERFACE(IMediaRecorder, data, reply); + sp listener = + interface_cast(data.readStrongBinder()); + reply->writeInt32(setListener(listener)); + return NO_ERROR; + } break; case SET_PREVIEW_SURFACE: { LOGV("SET_PREVIEW_SURFACE"); CHECK_INTERFACE(IMediaRecorder, data, reply); diff --git a/media/libmedia/JetPlayer.cpp b/media/libmedia/JetPlayer.cpp index f0edf887d64334a7e9bff55e121f02990700a405..2c6210471d3a2c2d296914f2d6109dd6edf3f20a 100644 --- a/media/libmedia/JetPlayer.cpp +++ b/media/libmedia/JetPlayer.cpp @@ -86,8 +86,8 @@ int JetPlayer::init() mState = EAS_STATE_ERROR; return result; } - // init the JET library - result = JET_Init(mEasData, NULL, 0); + // init the JET library with the default app event controller range + result = JET_Init(mEasData, NULL, sizeof(S_JET_CONFIG)); if( result != EAS_SUCCESS) { LOGE("JetPlayer::init(): Error initializing JET library, aborting."); mState = EAS_STATE_ERROR; @@ -96,7 +96,7 @@ int JetPlayer::init() // create the output AudioTrack mAudioTrack = new AudioTrack(); - mAudioTrack->set(AudioTrack::MUSIC, //TODO parametrize this + mAudioTrack->set(AudioSystem::MUSIC, //TODO parametrize this pLibConfig->sampleRate, 1, // format = PCM 16bits per sample, pLibConfig->numChannels, @@ -200,6 +200,11 @@ int JetPlayer::render() { while (!mRender) { LOGV("JetPlayer::render(): signal wait"); + if (audioStarted) { + mAudioTrack->pause(); + // we have to restart the playback once we start rendering again + audioStarted = false; + } mCondition.wait(mMutex); LOGV("JetPlayer::render(): signal rx'd"); } @@ -214,12 +219,15 @@ int JetPlayer::render() { } p += count * pLibConfig->numChannels; num_output += count * pLibConfig->numChannels * sizeof(EAS_PCM); + + // send events that were generated (if any) to the event callback + fireEventsFromJetQueue(); } // update playback state //LOGV("JetPlayer::render(): updating state"); JET_Status(mEasData, &mJetStatus); - fireEventOnStatusChange(); + fireUpdateOnStatusChange(); mPaused = mJetStatus.paused; mMutex.unlock(); // UNLOCK ]]]]]]]] ----------------------------------- @@ -261,9 +269,9 @@ threadExit: //------------------------------------------------------------------------------------------------- -// fire up an event if any of the status fields has changed +// fire up an update if any of the status fields has changed // precondition: mMutex locked -void JetPlayer::fireEventOnStatusChange() +void JetPlayer::fireUpdateOnStatusChange() { if( (mJetStatus.currentUserID != mPreviousJetStatus.currentUserID) ||(mJetStatus.segmentRepeatCount != mPreviousJetStatus.segmentRepeatCount) ) { @@ -303,9 +311,31 @@ void JetPlayer::fireEventOnStatusChange() //------------------------------------------------------------------------------------------------- -int JetPlayer::openFile(const char* path) +// fire up all the JET events in the JET engine queue (until the queue is empty) +// precondition: mMutex locked +void JetPlayer::fireEventsFromJetQueue() +{ + if(!mEventCallback) { + // no callback, just empty the event queue + while (JET_GetEvent(mEasData, NULL, NULL)) { } + return; + } + + EAS_U32 rawEvent; + while (JET_GetEvent(mEasData, &rawEvent, NULL)) { + mEventCallback( + JetPlayer::JET_EVENT, + rawEvent, + -1, + mJavaJetPlayerRef); + } +} + + +//------------------------------------------------------------------------------------------------- +int JetPlayer::loadFromFile(const char* path) { - LOGV("JetPlayer::openFile(): path=%s", path); + LOGV("JetPlayer::loadFromFile(): path=%s", path); Mutex::Autolock lock(mMutex); @@ -326,6 +356,29 @@ int JetPlayer::openFile(const char* path) return( result ); } + +//------------------------------------------------------------------------------------------------- +int JetPlayer::loadFromFD(const int fd, const long long offset, const long long length) +{ + LOGV("JetPlayer::loadFromFD(): fd=%d offset=%lld length=%lld", fd, offset, length); + + Mutex::Autolock lock(mMutex); + + mEasJetFileLoc = (EAS_FILE_LOCATOR) malloc(sizeof(EAS_FILE)); + mEasJetFileLoc->fd = fd; + mEasJetFileLoc->offset = offset; + mEasJetFileLoc->length = length; + mEasJetFileLoc->path = NULL; + + EAS_RESULT result = JET_OpenFile(mEasData, mEasJetFileLoc); + if(result != EAS_SUCCESS) + mState = EAS_STATE_ERROR; + else + mState = EAS_STATE_OPEN; + return( result ); +} + + //------------------------------------------------------------------------------------------------- int JetPlayer::closeFile() { @@ -348,7 +401,7 @@ int JetPlayer::play() JET_Status(mEasData, &mJetStatus); this->dumpJetStatus(&mJetStatus); - fireEventOnStatusChange(); + fireUpdateOnStatusChange(); // wake up render thread LOGV("JetPlayer::play(): wakeup render thread"); @@ -368,7 +421,7 @@ int JetPlayer::pause() JET_Status(mEasData, &mJetStatus); this->dumpJetStatus(&mJetStatus); - fireEventOnStatusChange(); + fireUpdateOnStatusChange(); return result; @@ -407,6 +460,14 @@ int JetPlayer::triggerClip(int clipId) return JET_TriggerClip(mEasData, clipId); } +//------------------------------------------------------------------------------------------------- +int JetPlayer::clearQueue() +{ + LOGV("JetPlayer::clearQueue"); + Mutex::Autolock lock(mMutex); + return JET_Clear_Queue(mEasData); +} + //------------------------------------------------------------------------------------------------- void JetPlayer::dump() { diff --git a/media/libmedia/ToneGenerator.cpp b/media/libmedia/ToneGenerator.cpp index 584d1350545e45badbb7a0152d08d84c53df3ee0..856059328e4b5f6b1271ba18358a6c4b725ebe10 100644 --- a/media/libmedia/ToneGenerator.cpp +++ b/media/libmedia/ToneGenerator.cpp @@ -93,11 +93,7 @@ ToneGenerator::ToneGenerator(int streamType, float volume) { mState = TONE_IDLE; - if (AudioSystem::getOutputSamplingRate(&mSamplingRate) != NO_ERROR) { - LOGE("Unable to marshal AudioFlinger"); - return; - } - if (AudioSystem::getOutputFrameCount(&mBufferSize) != NO_ERROR) { + if (AudioSystem::getOutputSamplingRate(&mSamplingRate, streamType) != NO_ERROR) { LOGE("Unable to marshal AudioFlinger"); return; } @@ -179,38 +175,42 @@ bool ToneGenerator::startTone(int toneType) { if (mState == TONE_INIT) { if (prepareWave()) { LOGV("Immediate start, time %d\n", (unsigned int)(systemTime()/1000000)); - + lResult = true; mState = TONE_STARTING; mLock.unlock(); mpAudioTrack->start(); mLock.lock(); if (mState == TONE_STARTING) { - if (mWaitCbkCond.waitRelative(mLock, seconds(1)) != NO_ERROR) { - LOGE("--- timed out"); + LOGV("Wait for start callback"); + status_t lStatus = mWaitCbkCond.waitRelative(mLock, seconds(1)); + if (lStatus != NO_ERROR) { + LOGE("--- Immediate start timed out, status %d", lStatus); mState = TONE_IDLE; + lResult = false; } } - - if (mState == TONE_PLAYING) - lResult = true; + } else { + mState == TONE_IDLE; } } else { LOGV("Delayed start\n"); mState = TONE_RESTARTING; - if (mWaitCbkCond.waitRelative(mLock, seconds(1)) == NO_ERROR) { - if (mState != TONE_INIT) { + status_t lStatus = mWaitCbkCond.waitRelative(mLock, seconds(1)); + if (lStatus == NO_ERROR) { + if (mState != TONE_IDLE) { lResult = true; } LOGV("cond received"); } else { - LOGE("--- timed out"); + LOGE("--- Delayed start timed out, status %d", lStatus); mState = TONE_IDLE; } } mLock.unlock(); - LOGV("Tone started, time %d\n", (unsigned int)(systemTime()/1000000)); + LOGV_IF(lResult, "Tone started, time %d\n", (unsigned int)(systemTime()/1000000)); + LOGW_IF(!lResult, "Tone start failed!!!, time %d\n", (unsigned int)(systemTime()/1000000)); return lResult; } @@ -239,7 +239,7 @@ void ToneGenerator::stopTone() { if (lStatus == NO_ERROR) { LOGV("track stop complete, time %d", (unsigned int)(systemTime()/1000000)); } else { - LOGE("--- timed out"); + LOGE("--- Stop timed out"); mState = TONE_IDLE; mpAudioTrack->stop(); } @@ -275,9 +275,9 @@ bool ToneGenerator::initAudioTrack() { mpAudioTrack = 0; } - // Open audio track in mono, PCM 16bit, default sampling rate, 2 buffers of + // Open audio track in mono, PCM 16bit, default sampling rate, default buffer size mpAudioTrack - = new AudioTrack(mStreamType, 0, AudioSystem::PCM_16_BIT, 1, NUM_PCM_BUFFERS*mBufferSize, 0, audioCallback, this, mBufferSize); + = new AudioTrack(mStreamType, 0, AudioSystem::PCM_16_BIT, 1, 0, 0, audioCallback, this, 0); if (mpAudioTrack == 0) { LOGE("AudioTrack allocation failed"); @@ -370,6 +370,8 @@ void ToneGenerator::audioCallback(int event, void* user, void *info) { break; default: LOGV("Extra Cbk"); + // Force loop exit + lNumSmp = 0; goto audioCallback_EndLoop; } @@ -461,8 +463,11 @@ audioCallback_EndLoop: if (lpToneGen->prepareWave()) { lpToneGen->mState = TONE_STARTING; } else { - lpToneGen->mState = TONE_INIT; + LOGW("Cbk restarting prepareWave() failed\n"); + lpToneGen->mState = TONE_IDLE; lpToneGen->mpAudioTrack->stop(); + // Force loop exit + lNumSmp = 0; } lSignal = true; break; diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp index ebdbda89379de44033c69cd4151b5936e2f2ea98..6b404124476594b11f0aafc97251b7f90fbef934 100644 --- a/media/libmedia/mediaplayer.cpp +++ b/media/libmedia/mediaplayer.cpp @@ -82,7 +82,7 @@ MediaPlayer::MediaPlayer() mListener = NULL; mCookie = NULL; mDuration = -1; - mStreamType = AudioTrack::MUSIC; + mStreamType = AudioSystem::MUSIC; mCurrentPosition = -1; mSeekPosition = -1; mCurrentState = MEDIA_PLAYER_IDLE; @@ -172,7 +172,7 @@ status_t MediaPlayer::setDataSource(const sp& player) status_t MediaPlayer::setDataSource(const char *url) { LOGV("setDataSource(%s)", url); - status_t err = UNKNOWN_ERROR; + status_t err = BAD_VALUE; if (url != NULL) { const sp& service(getMediaPlayerService()); if (service != 0) { @@ -199,7 +199,7 @@ status_t MediaPlayer::setVideoSurface(const sp& surface) { LOGV("setVideoSurface"); Mutex::Autolock _l(mLock); - if (mPlayer == 0) return UNKNOWN_ERROR; + if (mPlayer == 0) return NO_INIT; return mPlayer->setVideoSurface(surface->getISurface()); } @@ -215,11 +215,15 @@ status_t MediaPlayer::prepareAsync_l() return INVALID_OPERATION; } +// TODO: In case of error, prepareAsync provides the caller with 2 error codes, +// one defined in the Android framework and one provided by the implementation +// that generated the error. The sync version of prepare returns only 1 error +// code. status_t MediaPlayer::prepare() { LOGV("prepare"); Mutex::Autolock _l(mLock); - if (mPrepareSync) return UNKNOWN_ERROR; + if (mPrepareSync) return -EALREADY; mPrepareSync = true; status_t ret = prepareAsync_l(); if (ret != NO_ERROR) return ret; @@ -253,7 +257,6 @@ status_t MediaPlayer::start() status_t ret = mPlayer->start(); if (ret != NO_ERROR) { mCurrentState = MEDIA_PLAYER_STATE_ERROR; - ret = UNKNOWN_ERROR; } else { if (mCurrentState == MEDIA_PLAYER_PLAYBACK_COMPLETE) { LOGV("playback completed immediately following start()"); @@ -275,7 +278,6 @@ status_t MediaPlayer::stop() status_t ret = mPlayer->stop(); if (ret != NO_ERROR) { mCurrentState = MEDIA_PLAYER_STATE_ERROR; - ret = UNKNOWN_ERROR; } else { mCurrentState = MEDIA_PLAYER_STOPPED; } @@ -295,7 +297,6 @@ status_t MediaPlayer::pause() status_t ret = mPlayer->pause(); if (ret != NO_ERROR) { mCurrentState = MEDIA_PLAYER_STATE_ERROR; - ret = UNKNOWN_ERROR; } else { mCurrentState = MEDIA_PLAYER_PAUSED; } @@ -422,7 +423,6 @@ status_t MediaPlayer::reset() if (ret != NO_ERROR) { LOGE("reset() failed with return code (%d)", ret); mCurrentState = MEDIA_PLAYER_STATE_ERROR; - ret = UNKNOWN_ERROR; } else { mCurrentState = MEDIA_PLAYER_IDLE; } @@ -516,7 +516,9 @@ void MediaPlayer::notify(int msg, int ext1, int ext2) } break; case MEDIA_ERROR: - // Always log errors + // Always log errors. + // ext1: Media framework error code. + // ext2: Implementation dependant error code. LOGE("error (%d, %d)", ext1, ext2); mCurrentState = MEDIA_PLAYER_STATE_ERROR; if (mPrepareSync) @@ -528,6 +530,11 @@ void MediaPlayer::notify(int msg, int ext1, int ext2) send = false; } break; + case MEDIA_INFO: + // ext1: Media framework error code. + // ext2: Implementation dependant error code. + LOGW("info/warning (%d, %d)", ext1, ext2); + break; case MEDIA_SEEK_COMPLETE: LOGV("Received seek complete"); if (mSeekPosition != mCurrentPosition) { diff --git a/media/libmedia/mediarecorder.cpp b/media/libmedia/mediarecorder.cpp index 6ee4c0d45ef2040b3122eb9dbe354dbf6367227e..23b3b9d2d29b0c3db32f905f2dbe6c7467b42617 100644 --- a/media/libmedia/mediarecorder.cpp +++ b/media/libmedia/mediarecorder.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -42,7 +43,7 @@ status_t MediaRecorder::setCamera(const sp& camera) if (OK != ret) { LOGV("setCamera failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } return ret; } @@ -58,12 +59,16 @@ status_t MediaRecorder::setPreviewSurface(const sp& surface) LOGE("setPreviewSurface called in an invalid state(%d)", mCurrentState); return INVALID_OPERATION; } + if (!mIsVideoSourceSet) { + LOGE("try to set preview surface without setting the video source first"); + return INVALID_OPERATION; + } status_t ret = mMediaRecorder->setPreviewSurface(surface->getISurface()); if (OK != ret) { LOGV("setPreviewSurface failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } return ret; } @@ -84,8 +89,16 @@ status_t MediaRecorder::init() if (OK != ret) { LOGV("init failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } + + ret = mMediaRecorder->setListener(this); + if (OK != ret) { + LOGV("setListener failed: %d", ret); + mCurrentState = MEDIA_RECORDER_ERROR; + return ret; + } + mCurrentState = MEDIA_RECORDER_INITIALIZED; return ret; } @@ -117,7 +130,7 @@ status_t MediaRecorder::setVideoSource(int vs) if (OK != ret) { LOGV("setVideoSource failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } mIsVideoSourceSet = true; return ret; @@ -150,7 +163,7 @@ status_t MediaRecorder::setAudioSource(int as) if (OK != ret) { LOGV("setAudioSource failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } mIsAudioSourceSet = true; return ret; @@ -167,12 +180,16 @@ status_t MediaRecorder::setOutputFormat(int of) LOGE("setOutputFormat called in an invalid state: %d", mCurrentState); return INVALID_OPERATION; } + if (mIsVideoSourceSet && of >= OUTPUT_FORMAT_RAW_AMR) { + LOGE("output format (%d) is meant for audio recording only and incompatible with video recording", of); + return INVALID_OPERATION; + } status_t ret = mMediaRecorder->setOutputFormat(of); if (OK != ret) { LOGE("setOutputFormat failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } mCurrentState = MEDIA_RECORDER_DATASOURCE_CONFIGURED; return ret; @@ -185,6 +202,10 @@ status_t MediaRecorder::setVideoEncoder(int ve) LOGE("media recorder is not initialized yet"); return INVALID_OPERATION; } + if (!mIsVideoSourceSet) { + LOGE("try to set the video encoder without setting the video source first"); + return INVALID_OPERATION; + } if (mIsVideoEncoderSet) { LOGE("video encoder has already been set"); return INVALID_OPERATION; @@ -198,7 +219,7 @@ status_t MediaRecorder::setVideoEncoder(int ve) if (OK != ret) { LOGV("setVideoEncoder failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } mIsVideoEncoderSet = true; return ret; @@ -211,6 +232,10 @@ status_t MediaRecorder::setAudioEncoder(int ae) LOGE("media recorder is not initialized yet"); return INVALID_OPERATION; } + if (!mIsAudioSourceSet) { + LOGE("try to set the audio encoder without setting the audio source first"); + return INVALID_OPERATION; + } if (mIsAudioEncoderSet) { LOGE("audio encoder has already been set"); return INVALID_OPERATION; @@ -224,7 +249,7 @@ status_t MediaRecorder::setAudioEncoder(int ae) if (OK != ret) { LOGV("setAudioEncoder failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } mIsAudioEncoderSet = true; return ret; @@ -248,9 +273,35 @@ status_t MediaRecorder::setOutputFile(const char* path) status_t ret = mMediaRecorder->setOutputFile(path); if (OK != ret) { - LOGV("setAudioEncoder failed: %d", ret); + LOGV("setOutputFile failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; + } + mIsOutputFileSet = true; + return ret; +} + +status_t MediaRecorder::setOutputFile(int fd, int64_t offset, int64_t length) +{ + LOGV("setOutputFile(%d, %lld, %lld)", fd, offset, length); + if(mMediaRecorder == NULL) { + LOGE("media recorder is not initialized yet"); + return INVALID_OPERATION; + } + if (mIsOutputFileSet) { + LOGE("output file has already been set"); + return INVALID_OPERATION; + } + if (!(mCurrentState & MEDIA_RECORDER_DATASOURCE_CONFIGURED)) { + LOGE("setOutputFile called in an invalid state(%d)", mCurrentState); + return INVALID_OPERATION; + } + + status_t ret = mMediaRecorder->setOutputFile(fd, offset, length); + if (OK != ret) { + LOGV("setOutputFile failed: %d", ret); + mCurrentState = MEDIA_RECORDER_ERROR; + return ret; } mIsOutputFileSet = true; return ret; @@ -267,12 +318,16 @@ status_t MediaRecorder::setVideoSize(int width, int height) LOGE("setVideoSize called in an invalid state: %d", mCurrentState); return INVALID_OPERATION; } + if (!mIsVideoSourceSet) { + LOGE("try to set video size without setting video source first"); + return INVALID_OPERATION; + } status_t ret = mMediaRecorder->setVideoSize(width, height); if (OK != ret) { LOGE("setVideoSize failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } return ret; } @@ -288,16 +343,37 @@ status_t MediaRecorder::setVideoFrameRate(int frames_per_second) LOGE("setVideoFrameRate called in an invalid state: %d", mCurrentState); return INVALID_OPERATION; } + if (!mIsVideoSourceSet) { + LOGE("try to set video frame rate without setting video source first"); + return INVALID_OPERATION; + } status_t ret = mMediaRecorder->setVideoFrameRate(frames_per_second); if (OK != ret) { LOGE("setVideoFrameRate failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } return ret; } +status_t MediaRecorder::setParameters(const String8& params) { + LOGV("setParameters(%s)", params.string()); + if(mMediaRecorder == NULL) { + LOGE("media recorder is not initialized yet"); + return INVALID_OPERATION; + } + + status_t ret = mMediaRecorder->setParameters(params); + if (OK != ret) { + LOGE("setParameters(%s) failed: %d", params.string(), ret); + mCurrentState = MEDIA_RECORDER_ERROR; + return ret; + } + + return ret; +} + status_t MediaRecorder::prepare() { LOGV("prepare"); @@ -306,7 +382,24 @@ status_t MediaRecorder::prepare() return INVALID_OPERATION; } if (!(mCurrentState & MEDIA_RECORDER_DATASOURCE_CONFIGURED)) { - LOGE("setVideoFrameRate called in an invalid state: %d", mCurrentState); + LOGE("prepare called in an invalid state: %d", mCurrentState); + return INVALID_OPERATION; + } + if (mIsAudioSourceSet != mIsAudioEncoderSet) { + if (mIsAudioSourceSet) { + LOGE("audio source is set, but audio encoder is not set"); + } else { // must not happen, since setAudioEncoder checks this already + LOGE("audio encoder is set, but audio source is not set"); + } + return INVALID_OPERATION; + } + + if (mIsVideoSourceSet != mIsVideoEncoderSet) { + if (mIsVideoSourceSet) { + LOGE("video source is set, but video encoder is not set"); + } else { // must not happen, since setVideoEncoder checks this already + LOGE("video encoder is set, but video source is not set"); + } return INVALID_OPERATION; } @@ -314,7 +407,7 @@ status_t MediaRecorder::prepare() if (OK != ret) { LOGE("prepare failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } mCurrentState = MEDIA_RECORDER_PREPARED; return ret; @@ -328,7 +421,7 @@ status_t MediaRecorder::getMaxAmplitude(int* max) return INVALID_OPERATION; } if (mCurrentState & MEDIA_RECORDER_ERROR) { - LOGE("setVideoFrameRate called in an invalid state: %d", mCurrentState); + LOGE("getMaxAmplitude called in an invalid state: %d", mCurrentState); return INVALID_OPERATION; } @@ -336,7 +429,7 @@ status_t MediaRecorder::getMaxAmplitude(int* max) if (OK != ret) { LOGE("getMaxAmplitude failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } return ret; } @@ -357,7 +450,7 @@ status_t MediaRecorder::start() if (OK != ret) { LOGE("start failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } mCurrentState = MEDIA_RECORDER_RECORDING; return ret; @@ -379,8 +472,13 @@ status_t MediaRecorder::stop() if (OK != ret) { LOGE("stop failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } + + // FIXME: + // stop and reset are semantically different. + // We treat them the same for now, and will change this in the future. + doCleanUp(); mCurrentState = MEDIA_RECORDER_IDLE; return ret; } @@ -447,7 +545,7 @@ status_t MediaRecorder::doReset() if (OK != ret) { LOGE("doReset failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; - return UNKNOWN_ERROR; + return ret; } else { mCurrentState = MEDIA_RECORDER_INITIALIZED; } @@ -512,5 +610,31 @@ MediaRecorder::~MediaRecorder() } } +status_t MediaRecorder::setListener(const sp& listener) +{ + LOGV("setListener"); + Mutex::Autolock _l(mLock); + mListener = listener; + + return NO_ERROR; +} + +void MediaRecorder::notify(int msg, int ext1, int ext2) +{ + LOGV("message received msg=%d, ext1=%d, ext2=%d", msg, ext1, ext2); + + sp listener; + mLock.lock(); + listener = mListener; + mLock.unlock(); + + if (listener != NULL) { + Mutex::Autolock _l(mNotifyLock); + LOGV("callback application"); + listener->notify(msg, ext1, ext2); + LOGV("back from callback"); + } +} + }; // namespace android diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp index 53831717ec8a68efe7843cfe0678088539cdfcbd..40705c6ebcea12b873c3fa491d80f28c354b0bd0 100644 --- a/media/libmediaplayerservice/MediaPlayerService.cpp +++ b/media/libmediaplayerservice/MediaPlayerService.cpp @@ -61,113 +61,32 @@ pid_t gettid() { return syscall(__NR_gettid);} #undef __KERNEL__ #endif -/* - When USE_SIGBUS_HANDLER is set to 1, a handler for SIGBUS will be - installed, which allows us to recover when there is a read error - when accessing an mmap'ed file. However, since the kernel folks - don't seem to like it when non kernel folks install signal handlers - in their own process, this is currently disabled. - Without the handler, the process hosting this service will die and - then be restarted. This is mostly OK right now because the process is - not being shared with any other services, and clients of the service - will be notified of its death in their MediaPlayer.onErrorListener - callback, assuming they have installed one, and can then attempt to - do their own recovery. - It does open us up to a DOS attack against the media server, where - a malicious application can trivially force the media server to - restart continuously. -*/ -#define USE_SIGBUS_HANDLER 0 + +namespace android { // TODO: Temp hack until we can register players -static const char* MIDI_FILE_EXTS[] = -{ - ".mid", - ".smf", - ".xmf", - ".imy", - ".rtttl", - ".rtx", - ".ota" +typedef struct { + const char *extension; + const player_type playertype; +} extmap; +extmap FILE_EXTS [] = { + {".mid", SONIVOX_PLAYER}, + {".midi", SONIVOX_PLAYER}, + {".smf", SONIVOX_PLAYER}, + {".xmf", SONIVOX_PLAYER}, + {".imy", SONIVOX_PLAYER}, + {".rtttl", SONIVOX_PLAYER}, + {".rtx", SONIVOX_PLAYER}, + {".ota", SONIVOX_PLAYER}, + {".ogg", VORBIS_PLAYER}, + {".oga", VORBIS_PLAYER}, }; -namespace android { - // TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround /* static */ const uint32_t MediaPlayerService::AudioOutput::kAudioVideoDelayMs = 96; /* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4; /* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false; -static struct sigaction oldact; -static pthread_key_t sigbuskey; - -static void sigbushandler(int signal, siginfo_t *info, void *context) -{ - char *faultaddr = (char*) info->si_addr; - LOGE("SIGBUS at %p\n", faultaddr); - - struct mediasigbushandler* h = (struct mediasigbushandler*) pthread_getspecific(sigbuskey); - - if (h) { - if (h->len) { - if (faultaddr < h->base || faultaddr >= h->base + h->len) { - // outside specified range, call old handler - if (oldact.sa_flags & SA_SIGINFO) { - oldact.sa_sigaction(signal, info, context); - } else { - oldact.sa_handler(signal); - } - return; - } - } - - // no range specified or address was in range - - if (h->handlesigbus) { - if (h->handlesigbus(info, h)) { - // thread's handler didn't handle the signal - if (oldact.sa_flags & SA_SIGINFO) { - oldact.sa_sigaction(signal, info, context); - } else { - oldact.sa_handler(signal); - } - } - return; - } - - if (h->sigbusvar) { - // map in a zeroed out page so the operation can succeed - long pagesize = sysconf(_SC_PAGE_SIZE); - long pagemask = ~(pagesize - 1); - void * pageaddr = (void*) (((long)(faultaddr)) & pagemask); - - void * bar = mmap( pageaddr, pagesize, PROT_READ, MAP_ANONYMOUS|MAP_PRIVATE|MAP_FIXED, -1, 0); - if (bar == MAP_FAILED) { - LOGE("couldn't map zero page at %p: %s", pageaddr, strerror(errno)); - if (oldact.sa_flags & SA_SIGINFO) { - oldact.sa_sigaction(signal, info, context); - } else { - oldact.sa_handler(signal); - } - return; - } - - LOGE("setting sigbusvar at %p", h->sigbusvar); - *(h->sigbusvar) = 1; - return; - } - } - - LOGE("SIGBUS: no handler, or improperly configured handler (%p)", h); - - if (oldact.sa_flags & SA_SIGINFO) { - oldact.sa_sigaction(signal, info, context); - } else { - oldact.sa_handler(signal); - } - return; -} - void MediaPlayerService::instantiate() { defaultServiceManager()->addService( String16("media.player"), new MediaPlayerService()); @@ -177,25 +96,10 @@ MediaPlayerService::MediaPlayerService() { LOGV("MediaPlayerService created"); mNextConnId = 1; - - pthread_key_create(&sigbuskey, NULL); - - -#if USE_SIGBUS_HANDLER - struct sigaction act; - memset(&act,0, sizeof act); - act.sa_sigaction = sigbushandler; - act.sa_flags = SA_SIGINFO; - sigaction(SIGBUS, &act, &oldact); -#endif } MediaPlayerService::~MediaPlayerService() { -#if USE_SIGBUS_HANDLER - sigaction(SIGBUS, &oldact, NULL); -#endif - pthread_key_delete(sigbuskey); LOGV("MediaPlayerService destroyed"); } @@ -314,6 +218,104 @@ static int myTid() { #endif } +#if defined(__arm__) +extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize, + size_t* infoSize, size_t* totalMemory, size_t* backtraceSize); +extern "C" void free_malloc_leak_info(uint8_t* info); + +void memStatus(int fd, const Vector& args) +{ + const size_t SIZE = 256; + char buffer[SIZE]; + String8 result; + + typedef struct { + size_t size; + size_t dups; + intptr_t * backtrace; + } AllocEntry; + + uint8_t *info = NULL; + size_t overallSize = 0; + size_t infoSize = 0; + size_t totalMemory = 0; + size_t backtraceSize = 0; + + get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize); + if (info) { + uint8_t *ptr = info; + size_t count = overallSize / infoSize; + + snprintf(buffer, SIZE, " Allocation count %i\n", count); + result.append(buffer); + + AllocEntry * entries = new AllocEntry[count]; + + for (size_t i = 0; i < count; i++) { + // Each entry should be size_t, size_t, intptr_t[backtraceSize] + AllocEntry *e = &entries[i]; + + e->size = *reinterpret_cast(ptr); + ptr += sizeof(size_t); + + e->dups = *reinterpret_cast(ptr); + ptr += sizeof(size_t); + + e->backtrace = reinterpret_cast(ptr); + ptr += sizeof(intptr_t) * backtraceSize; + } + + // Now we need to sort the entries. They come sorted by size but + // not by stack trace which causes problems using diff. + bool moved; + do { + moved = false; + for (size_t i = 0; i < (count - 1); i++) { + AllocEntry *e1 = &entries[i]; + AllocEntry *e2 = &entries[i+1]; + + bool swap = e1->size < e2->size; + if (e1->size == e2->size) { + for(size_t j = 0; j < backtraceSize; j++) { + if (e1->backtrace[j] == e2->backtrace[j]) { + continue; + } + swap = e1->backtrace[j] < e2->backtrace[j]; + break; + } + } + if (swap) { + AllocEntry t = entries[i]; + entries[i] = entries[i+1]; + entries[i+1] = t; + moved = true; + } + } + } while (moved); + + for (size_t i = 0; i < count; i++) { + AllocEntry *e = &entries[i]; + + snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups); + result.append(buffer); + for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) { + if (ct) { + result.append(", "); + } + snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]); + result.append(buffer); + } + result.append("\n"); + } + + delete[] entries; + free_malloc_leak_info(info); + } + + write(fd, result.string(), result.size()); +} +#endif + status_t MediaPlayerService::dump(int fd, const Vector& args) { const size_t SIZE = 256; @@ -396,6 +398,18 @@ status_t MediaPlayerService::dump(int fd, const Vector& args) result.append(buffer); result.append("\n"); } + +#if defined(__arm__) + bool dumpMem = false; + for (size_t i = 0; i < args.size(); i++) { + if (args[i] == String16("-m")) { + dumpMem = true; + } + } + if (dumpMem) { + memStatus(fd, args); + } +#endif } write(fd, result.string(), result.size()); return NO_ERROR; @@ -481,7 +495,7 @@ static player_type getPlayerType(int fd, int64_t offset, int64_t length) locator.offset = offset; locator.length = length; EAS_HANDLE eashandle; - if (EAS_OpenFile(easdata, &locator, &eashandle, NULL) == EAS_SUCCESS) { + if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) { EAS_CloseFile(easdata, eashandle); EAS_Shutdown(easdata); return SONIVOX_PLAYER; @@ -498,22 +512,16 @@ static player_type getPlayerType(const char* url) // use MidiFile for MIDI extensions int lenURL = strlen(url); - for (int i = 0; i < NELEM(MIDI_FILE_EXTS); ++i) { - int len = strlen(MIDI_FILE_EXTS[i]); + for (int i = 0; i < NELEM(FILE_EXTS); ++i) { + int len = strlen(FILE_EXTS[i].extension); int start = lenURL - len; if (start > 0) { - if (!strncmp(url + start, MIDI_FILE_EXTS[i], len)) { - LOGV("Type is MIDI"); - return SONIVOX_PLAYER; + if (!strncmp(url + start, FILE_EXTS[i].extension, len)) { + return FILE_EXTS[i].playertype; } } } - if (strcmp(url + strlen(url) - 4, ".ogg") == 0) { - LOGV("Type is Vorbis"); - return VORBIS_PLAYER; - } - // Fall through to PV return PV_PLAYER; } @@ -539,7 +547,6 @@ static sp createPlayer(player_type playerType, void* cookie, if (p != NULL) { if (p->initCheck() == NO_ERROR) { p->setNotifyCallback(cookie, notifyFunc); - p->setSigBusHandlerStructTLSKey(sigbuskey); } else { p.clear(); } @@ -921,7 +928,7 @@ Exit: MediaPlayerService::AudioOutput::AudioOutput() { mTrack = 0; - mStreamType = AudioTrack::MUSIC; + mStreamType = AudioSystem::MUSIC; mLeftVolume = 1.0; mRightVolume = 1.0; mLatency = 0; @@ -1003,15 +1010,15 @@ status_t MediaPlayerService::AudioOutput::open(uint32_t sampleRate, int channelC int afFrameCount; int frameCount; - if (AudioSystem::getOutputFrameCount(&afFrameCount) != NO_ERROR) { + if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) { return NO_INIT; } - if (AudioSystem::getOutputSamplingRate(&afSampleRate) != NO_ERROR) { + if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) { return NO_INIT; } - frameCount = (sampleRate*afFrameCount)/afSampleRate; - AudioTrack *t = new AudioTrack(mStreamType, sampleRate, format, channelCount, frameCount*bufferCount); + frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate; + AudioTrack *t = new AudioTrack(mStreamType, sampleRate, format, channelCount, frameCount); if ((t == 0) || (t->initCheck() != NO_ERROR)) { LOGE("Unable to create audio track"); delete t; diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp index f326a0e3af1ca5db67acefcf67c7c8c69636c766..5d1887d8988843bf5c5663204efcd23c944b5438 100644 --- a/media/libmediaplayerservice/MediaRecorderClient.cpp +++ b/media/libmediaplayerservice/MediaRecorderClient.cpp @@ -121,6 +121,17 @@ status_t MediaRecorderClient::setOutputFile(const char* path) return mRecorder->setOutputFile(path); } +status_t MediaRecorderClient::setOutputFile(int fd, int64_t offset, int64_t length) +{ + LOGV("setOutputFile(%d, %lld, %lld)", fd, offset, length); + Mutex::Autolock lock(mLock); + if (mRecorder == NULL) { + LOGE("recorder is not initialized"); + return NO_INIT; + } + return mRecorder->setOutputFile(fd, offset, length); +} + status_t MediaRecorderClient::setVideoSize(int width, int height) { LOGV("setVideoSize(%dx%d)", width, height); @@ -143,6 +154,16 @@ status_t MediaRecorderClient::setVideoFrameRate(int frames_per_second) return mRecorder->setVideoFrameRate(frames_per_second); } +status_t MediaRecorderClient::setParameters(const String8& params) { + LOGV("setParameters(%s)", params.string()); + Mutex::Autolock lock(mLock); + if (mRecorder == NULL) { + LOGE("recorder is not initialized"); + return NO_INIT; + } + return mRecorder->setParameters(params); +} + status_t MediaRecorderClient::prepare() { LOGV("prepare"); @@ -247,5 +268,16 @@ MediaRecorderClient::~MediaRecorderClient() release(); } +status_t MediaRecorderClient::setListener(const sp& listener) +{ + LOGV("setListener"); + Mutex::Autolock lock(mLock); + if (mRecorder == NULL) { + LOGE("recorder is not initialized"); + return NO_INIT; + } + return mRecorder->setListener(listener); +} + }; // namespace android diff --git a/media/libmediaplayerservice/MediaRecorderClient.h b/media/libmediaplayerservice/MediaRecorderClient.h index 3158017ba7fa099e1b931b9421e2e31c8ef1de04..6a1c2d5c4636481321079c15c85f88566c45ad5d 100644 --- a/media/libmediaplayerservice/MediaRecorderClient.h +++ b/media/libmediaplayerservice/MediaRecorderClient.h @@ -36,8 +36,11 @@ public: virtual status_t setVideoEncoder(int ve); virtual status_t setAudioEncoder(int ae); virtual status_t setOutputFile(const char* path); + virtual status_t setOutputFile(int fd, int64_t offset, int64_t length); virtual status_t setVideoSize(int width, int height); virtual status_t setVideoFrameRate(int frames_per_second); + virtual status_t setParameters(const String8& params); + virtual status_t setListener(const sp& listener); virtual status_t prepare(); virtual status_t getMaxAmplitude(int* max); virtual status_t start(); diff --git a/media/libmediaplayerservice/MidiFile.cpp b/media/libmediaplayerservice/MidiFile.cpp index cfad66c8ffe29cd39e4507dc31a37a14d5cca338..d03caa5e5d9fa562e27f46b4ae264a28a929eb13 100644 --- a/media/libmediaplayerservice/MidiFile.cpp +++ b/media/libmediaplayerservice/MidiFile.cpp @@ -40,8 +40,6 @@ static pid_t myTid() { return getpid(); } // ---------------------------------------------------------------------------- -extern pthread_key_t EAS_sigbuskey; - namespace android { // ---------------------------------------------------------------------------- @@ -60,7 +58,7 @@ static const S_EAS_LIB_CONFIG* pLibConfig = NULL; MidiFile::MidiFile() : mEasData(NULL), mEasHandle(NULL), mAudioBuffer(NULL), mPlayTime(-1), mDuration(-1), mState(EAS_STATE_ERROR), - mStreamType(AudioTrack::MUSIC), mLoop(false), mExit(false), + mStreamType(AudioSystem::MUSIC), mLoop(false), mExit(false), mPaused(false), mRender(false), mTid(-1) { LOGV("constructor"); @@ -132,7 +130,7 @@ status_t MidiFile::setDataSource(const char* path) mFileLocator.fd = -1; mFileLocator.offset = 0; mFileLocator.length = 0; - EAS_RESULT result = EAS_OpenFile(mEasData, &mFileLocator, &mEasHandle, &mMemFailedVar); + EAS_RESULT result = EAS_OpenFile(mEasData, &mFileLocator, &mEasHandle); if (result == EAS_SUCCESS) { updateState(); } @@ -148,12 +146,6 @@ status_t MidiFile::setDataSource(const char* path) return NO_ERROR; } -status_t MidiFile::setSigBusHandlerStructTLSKey(pthread_key_t key) -{ - EAS_sigbuskey = key; - return 0; -} - status_t MidiFile::setDataSource(int fd, int64_t offset, int64_t length) { LOGV("MidiFile::setDataSource fd=%d", fd); @@ -168,7 +160,7 @@ status_t MidiFile::setDataSource(int fd, int64_t offset, int64_t length) mFileLocator.fd = dup(fd); mFileLocator.offset = offset; mFileLocator.length = length; - EAS_RESULT result = EAS_OpenFile(mEasData, &mFileLocator, &mEasHandle, &mMemFailedVar); + EAS_RESULT result = EAS_OpenFile(mEasData, &mFileLocator, &mEasHandle); updateState(); if (result != EAS_SUCCESS) { @@ -332,7 +324,7 @@ status_t MidiFile::getDuration(int* duration) EAS_HANDLE easHandle = NULL; EAS_RESULT result = EAS_Init(&easData); if (result == EAS_SUCCESS) { - result = EAS_OpenFile(easData, &mFileLocator, &easHandle, NULL); + result = EAS_OpenFile(easData, &mFileLocator, &easHandle); } if (result == EAS_SUCCESS) { result = EAS_Prepare(easData, easHandle); @@ -451,8 +443,6 @@ int MidiFile::render() { LOGV("MidiFile::render"); - struct mediasigbushandler sigbushandler; - // allocate render buffer mAudioBuffer = new EAS_PCM[pLibConfig->mixBufferSize * pLibConfig->numChannels * NUM_BUFFERS]; if (!mAudioBuffer) { @@ -468,10 +458,6 @@ int MidiFile::render() { mCondition.signal(); } - sigbushandler.handlesigbus = NULL; - sigbushandler.sigbusvar = mMemFailedVar; - pthread_setspecific(EAS_sigbuskey, &sigbushandler); - while (1) { mMutex.lock(); diff --git a/media/libmediaplayerservice/MidiFile.h b/media/libmediaplayerservice/MidiFile.h index 9d2dfdd72f9d6485a6a5e221b4d8b8e97d16edca..302f1cf2f8e4633afae6cc0728d1dedaa7a0d5e0 100644 --- a/media/libmediaplayerservice/MidiFile.h +++ b/media/libmediaplayerservice/MidiFile.h @@ -30,7 +30,6 @@ public: ~MidiFile(); virtual status_t initCheck(); - virtual status_t setSigBusHandlerStructTLSKey(pthread_key_t key); virtual status_t setDataSource(const char* path); virtual status_t setDataSource(int fd, int64_t offset, int64_t length); virtual status_t setVideoSurface(const sp& surface) { return UNKNOWN_ERROR; } @@ -57,7 +56,6 @@ private: Mutex mMutex; Condition mCondition; - int* mMemFailedVar; EAS_DATA_HANDLE mEasData; EAS_HANDLE mEasHandle; EAS_PCM* mAudioBuffer; diff --git a/media/libmediaplayerservice/VorbisPlayer.cpp b/media/libmediaplayerservice/VorbisPlayer.cpp index 9a644034a75206b3e16a4bbb4dd7827c9f12a05f..0ad335f84d10712d0a97ecb2afb8079d77e95b0d 100644 --- a/media/libmediaplayerservice/VorbisPlayer.cpp +++ b/media/libmediaplayerservice/VorbisPlayer.cpp @@ -55,7 +55,7 @@ static status_t STATE_OPEN = 2; VorbisPlayer::VorbisPlayer() : mAudioBuffer(NULL), mPlayTime(-1), mDuration(-1), mState(STATE_ERROR), - mStreamType(AudioTrack::MUSIC), mLoop(false), mAndroidLoop(false), + mStreamType(AudioSystem::MUSIC), mLoop(false), mAndroidLoop(false), mExit(false), mPaused(false), mRender(false), mRenderTid(-1) { LOGV("constructor\n"); @@ -455,13 +455,15 @@ int VorbisPlayer::render() { current_section = 0; numread = ov_read(&mVorbisFile, mAudioBuffer, AUDIOBUFFER_SIZE, ¤t_section); } else { - sendEvent(MEDIA_PLAYBACK_COMPLETE); mAudioSink->stop(); audioStarted = false; mRender = false; mPaused = true; int endpos = ov_time_tell(&mVorbisFile); + LOGV("send MEDIA_PLAYBACK_COMPLETE"); + sendEvent(MEDIA_PLAYBACK_COMPLETE); + // wait until we're started again LOGV("playback complete - wait for signal"); mCondition.wait(mMutex); diff --git a/media/sdutils/sdutil.cpp b/media/sdutils/sdutil.cpp index 0daa52314e2d0ddbd594d9f63b3386eaa5afbd29..a9aabf03624a8e561afeb33240431bae5dfd3fba 100644 --- a/media/sdutils/sdutil.cpp +++ b/media/sdutils/sdutil.cpp @@ -114,6 +114,16 @@ static int unmount(const char* path) { return -1; } +static int format(const char* path) { + String16 string(path); + + if (isMounted(path)) + return -EBUSY; + gMountService->formatMedia(string); + + return 0; +} + static int umsEnable(bool enable) { gMountService->setMassStorageEnabled(enable); return 0; @@ -129,6 +139,9 @@ int main(int argc, char **argv) if (strcmp(command, "mount") == 0) { android::init(); return android::mount(argument); + } else if (strcmp(command, "format") == 0) { + android::init(); + return android::format(argument); } else if (strcmp(command, "unmount") == 0) { android::init(); return android::unmount(argument); @@ -145,6 +158,7 @@ int main(int argc, char **argv) fprintf(stderr, "usage:\n" " sdutil mount - mounts the SD card at the given mount point\n" " sdutil unmount - unmounts the SD card at the given mount point\n" + " sdutil format - formats the SD card at the given mount point\n" " sdutil ums enable - enables USB mass storage\n" " sdutil ums disable - disnables USB mass storage\n" ); diff --git a/media/tests/MediaFrameworkTest/AndroidManifest.xml b/media/tests/MediaFrameworkTest/AndroidManifest.xml index 16e658a327a5da179f497c9d78b3a48c76d80896..a32f5907f391fe47c3e8a12e3c06a4ae48aa160e 100644 --- a/media/tests/MediaFrameworkTest/AndroidManifest.xml +++ b/media/tests/MediaFrameworkTest/AndroidManifest.xml @@ -42,5 +42,10 @@ android:targetPackage="com.android.mediaframeworktest" android:label="MediaFramework unit tests InstrumentationRunner"> + + + diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkTestRunner.java index 3d3878efd21f7b5df02c2fa3cae1afdc1486e11b..3c449c90530b520007f93458e9d4fce563fa3be4 100755 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkTestRunner.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkTestRunner.java @@ -21,6 +21,7 @@ import com.android.mediaframeworktest.functional.SimTonesTest; import com.android.mediaframeworktest.functional.MediaMetadataTest; import com.android.mediaframeworktest.functional.CameraTest; import com.android.mediaframeworktest.functional.MediaRecorderTest; +import com.android.mediaframeworktest.functional.MediaAudioTrackTest; import junit.framework.TestSuite; @@ -48,6 +49,7 @@ public class MediaFrameworkTestRunner extends InstrumentationTestRunner { suite.addTestSuite(MediaMetadataTest.class); suite.addTestSuite(CameraTest.class); suite.addTestSuite(MediaRecorderTest.class); + suite.addTestSuite(MediaAudioTrackTest.class); return suite; } @@ -57,3 +59,4 @@ public class MediaFrameworkTestRunner extends InstrumentationTestRunner { } } + diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaNames.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaNames.java index 584300775a87ea7cef61953b28e3bd5a355abbf5..07b43bb34f107d7ab84eac04fa739d0a3d7f9068 100755 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaNames.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaNames.java @@ -25,16 +25,16 @@ package com.android.mediaframeworktest; public class MediaNames { //Audio files - public static final String MP3CBR = "/sdcard/music/MP3CBR.mp3"; - public static final String MP3VBR = "/sdcard/music/MP3VBR.mp3"; - public static final String SHORTMP3 = "/sdcard/music/SHORTMP3.mp3"; - public static final String MIDI = "/sdcard/music/MIDI.mid"; - public static final String WMA9 = "/sdcard/music/WMA9.wma"; - public static final String WMA10 = "/sdcard/music/WMA10.wma"; - public static final String WAV = "/sdcard/music/complicated_wav.wav"; - public static final String AMR = "/sdcard/music/AMRNB.amr"; - public static final String OGG = "/sdcard/music/Mists_of_Time-4T.ogg"; - public static final String OGGSHORT = "/sdcard/music/Skippy.ogg"; + public static final String MP3CBR = "/sdcard/media_api/music/MP3CBR.mp3"; + public static final String MP3VBR = "/sdcard/media_api/music/MP3VBR.mp3"; + public static final String SHORTMP3 = "/sdcard/media_api/music/SHORTMP3.mp3"; + public static final String MIDI = "/sdcard/media_api/music/MIDI.mid"; + public static final String WMA9 = "/sdcard/media_api/music/WMA9.wma"; + public static final String WMA10 = "/sdcard/media_api/music/WMA10.wma"; + public static final String WAV = "/sdcard/media_api/music/complicated_wav.wav"; + public static final String AMR = "/sdcard/media_api/music/AMRNB.amr"; + public static final String OGG = "/sdcard/media_api/music/Mists_of_Time-4T.ogg"; + public static final String OGGSHORT = "/sdcard/media_api/music/Skippy.ogg"; public static final int MP3CBR_LENGTH = 231116; public static final int MP3VBR_LENGTH = 126407; @@ -60,20 +60,20 @@ public class MediaNames { //public static final String VIDEO_RTSP3GP = "rtsp://193.159.241.21/sp/alizee05.3gp"; //local video - public static final String VIDEO_MP4 = "/sdcard/video/gingerkids.MP4"; - public static final String VIDEO_LONG_3GP = "/sdcard/video/radiohead.3gp"; - public static final String VIDEO_SHORT_3GP = "/sdcard/video/short.3gp"; - public static final String VIDEO_LARGE_SIZE_3GP = "/sdcard/video/border_large.3gp"; - public static final String VIDEO_H263_AAC = "/sdcard/video/H263_AAC.3gp"; - public static final String VIDEO_H263_AMR = "/sdcard/video/H263_AMR.3gp"; - public static final String VIDEO_H264_AAC = "/sdcard/video/H264_AAC.3gp"; - public static final String VIDEO_H264_AMR = "/sdcard/video/H264_AMR.3gp"; - public static final String VIDEO_WMV = "/sdcard/video/bugs.wmv"; - public static final String VIDEO_HIGHRES_H263 = "/sdcard/video/h263_qcif_30fps.3gp"; - public static final String VIDEO_HIGHRES_MP4 = "/sdcard/video/mpeg4_qvga_24fps.3gp"; + public static final String VIDEO_MP4 = "/sdcard/media_api/video/gingerkids.MP4"; + public static final String VIDEO_LONG_3GP = "/sdcard/media_api/video/radiohead.3gp"; + public static final String VIDEO_SHORT_3GP = "/sdcard/media_api/video/short.3gp"; + public static final String VIDEO_LARGE_SIZE_3GP = "/sdcard/media_api/video/border_large.3gp"; + public static final String VIDEO_H263_AAC = "/sdcard/media_api/video/H263_AAC.3gp"; + public static final String VIDEO_H263_AMR = "/sdcard/media_api/video/H263_AMR.3gp"; + public static final String VIDEO_H264_AAC = "/sdcard/media_api/video/H264_AAC.3gp"; + public static final String VIDEO_H264_AMR = "/sdcard/media_api/video/H264_AMR.3gp"; + public static final String VIDEO_WMV = "/sdcard/media_api/video/bugs.wmv"; + public static final String VIDEO_HIGHRES_H263 = "/sdcard/media_api/video/h263_qcif_30fps.3gp"; + public static final String VIDEO_HIGHRES_MP4 = "/sdcard/media_api/video/mpeg4_qvga_24fps.3gp"; //ringtone - public static final String ringtone = "/sdcard/ringtones/F1_NewVoicemail.mp3"; + public static final String ringtone = "/sdcard/media_api/ringtones/F1_NewVoicemail.mp3"; //streaming mp3 public static final String STREAM_LARGE_MP3 = @@ -110,264 +110,266 @@ public class MediaNames { "http://wms.pv.com:7070/MediaDownloadContent/UserUploads/beefcake.mp3"; //Sonivox - public static String MIDIFILES[] = { "/sdcard/music/Leadsol.mxmf", - "/sdcard/music/abba.imy", "/sdcard/music/ants.mid", - "/sdcard/music/greensleeves.rtttl", "/sdcard/music/test.ota"}; + public static String MIDIFILES[] = { + "/sdcard/media_api/music/Leadsol.mxmf", + "/sdcard/media_api/music/abba.imy", "/sdcard/media_api/music/ants.mid", + "/sdcard/media_api/music/greensleeves.rtttl", "/sdcard/media_api/music/test.ota"}; //Performance measurement - public static String[] WAVFILES = { "/sdcard/music_perf/WAV/M1F1-AlawWE-AFsp.wav", - "/sdcard/music_perf/WAV/M1F1-float64-AFsp.wav", - "/sdcard/music_perf/WAV/song.wav", - "/sdcard/music_perf/WAV/WAVEtest.wav", - "/sdcard/music_perf/WAV/WAVEtest_out.wav", - "/sdcard/music_perf/WAV/test_out.wav"}; - + public static String[] WAVFILES = { + "/sdcard/media_api/music_perf/WAV/M1F1-AlawWE-AFsp.wav", + "/sdcard/media_api/music_perf/WAV/M1F1-float64-AFsp.wav", + "/sdcard/media_api/music_perf/WAV/song.wav", + "/sdcard/media_api/music_perf/WAV/WAVEtest.wav", + "/sdcard/media_api/music_perf/WAV/WAVEtest_out.wav", + "/sdcard/media_api/music_perf/WAV/test_out.wav"}; + public static String[] AMRNBFILES = { - "/sdcard/music_perf/AMR/AI_AMR-NB_5.9kbps_6.24kbps_8khz_mono_NMC.amr", - "/sdcard/music_perf/AMR/AI_AMR-NB_5.15kbps_5.46kbps_8khz_mono_NMC.amr", - "/sdcard/music_perf/AMR/AI_AMR-NB_7.4kbps_7.80kbps_8khz_mono_NMC.amr", - "/sdcard/music_perf/AMR/AI_AMR-NB_7.95kbps_9.6kbps_8khz_mono_NMC.amr", - "/sdcard/music_perf/AMR/AI_AMR-NB_10.2kbps_10.48kbps_8khz_mono_NMC.amr"}; + "/sdcard/media_api/music_perf/AMR/AI_AMR-NB_5.9kbps_6.24kbps_8khz_mono_NMC.amr", + "/sdcard/media_api/music_perf/AMR/AI_AMR-NB_5.15kbps_5.46kbps_8khz_mono_NMC.amr", + "/sdcard/media_api/music_perf/AMR/AI_AMR-NB_7.4kbps_7.80kbps_8khz_mono_NMC.amr", + "/sdcard/media_api/music_perf/AMR/AI_AMR-NB_7.95kbps_9.6kbps_8khz_mono_NMC.amr", + "/sdcard/media_api/music_perf/AMR/AI_AMR-NB_10.2kbps_10.48kbps_8khz_mono_NMC.amr"}; public static String[] AMRWBFILES = { - "/sdcard/music_perf/AMRWB/NIN_AMR-WB_15.85kbps_16kbps.amr", - "/sdcard/music_perf/AMRWB/NIN_AMR-WB_18.25kbps_18kbps.amr", - "/sdcard/music_perf/AMRWB/NIN_AMR-WB_19.85kbps_20kbps.amr", - "/sdcard/music_perf/AMRWB/NIN_AMR-WB_23.05kbps_23kbps.amr", - "/sdcard/music_perf/AMRWB/NIN_AMR-WB_23.85kbps_24kbps.amr", - "/sdcard/music_perf/AMRWB/PD_AMR-WB_19.85kbps_20kbps.amr", - "/sdcard/music_perf/AMRWB/PD_AMR-WB_23.05kbps_23kbps.amr", - "/sdcard/music_perf/AMRWB/PD_AMR-WB_23.85kbps_24kbps.amr", - "/sdcard/music_perf/AMRWB/WC_AMR-WB_23.05kbps_23kbps.amr", - "/sdcard/music_perf/AMRWB/WC_AMR-WB_23.85kbps_24kbps.amr", }; + "/sdcard/media_api/music_perf/AMRWB/NIN_AMR-WB_15.85kbps_16kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/NIN_AMR-WB_18.25kbps_18kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/NIN_AMR-WB_19.85kbps_20kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/NIN_AMR-WB_23.05kbps_23kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/NIN_AMR-WB_23.85kbps_24kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/PD_AMR-WB_19.85kbps_20kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/PD_AMR-WB_23.05kbps_23kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/PD_AMR-WB_23.85kbps_24kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/WC_AMR-WB_23.05kbps_23kbps.amr", + "/sdcard/media_api/music_perf/AMRWB/WC_AMR-WB_23.85kbps_24kbps.amr", }; public static String[] MP3FILES = { - "/sdcard/music_perf/MP3/NIN_56kbps_32khz_stereo_VBR_MCA.MP3", - "/sdcard/music_perf/MP3/NIN_80kbps_32khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_80kbps_44.1khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_80kbps_48khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_112kbps_32khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_112kbps_44.1khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_112kbps_48khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_192kbps_32khz_mono_CBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_192kbps_44.1khz_mono_CBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_192kbps_48khz_mono_CBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_256kbps_44.1khz_mono_CBR_MCA.mp3", - "/sdcard/music_perf/MP3/NIN_256kbps_48khz_mono_CBR_MCA.mp3", - "/sdcard/music_perf/MP3/PD_112kbps_32khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/PD_112kbps_44.1khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/PD_112kbps_48khz_stereo_VBR_MCA.mp3", - "/sdcard/music_perf/MP3/PD_192kbps_32khz_mono_CBR_DPA.mp3", - "/sdcard/music_perf/MP3/PD_256kbps_44.1khz_mono_CBR_DPA.mp3", - "/sdcard/music_perf/MP3/PD_256kbps_48khz_mono_CBR_MCA.mp3", - "/sdcard/music_perf/MP3/WC_256kbps_44.1khz_mono_CBR_DPA.mp3", - "/sdcard/music_perf/MP3/WC_256kbps_48khz_mono_CBR_DPA.mp3", - "/sdcard/music_perf/regular_album_photo/Apologize.mp3", - "/sdcard/music_perf/regular_album_photo/Because_Of_You.mp3", - "/sdcard/music_perf/regular_album_photo/Complicated.mp3", - "/sdcard/music_perf/regular_album_photo/Glamorous.mp3", - "/sdcard/music_perf/regular_album_photo/Im_With_You.mp3", - "/sdcard/music_perf/regular_album_photo/Smile.mp3", - "/sdcard/music_perf/regular_album_photo/Suddenly_I_See.mp3", - "/sdcard/music_perf/regular_album_photo/When You Say Nothing At All.mp3", - "/sdcard/music_perf/regular_album_photo/my_happy_ending.mp3"}; + "/sdcard/media_api/music_perf/MP3/NIN_56kbps_32khz_stereo_VBR_MCA.MP3", + "/sdcard/media_api/music_perf/MP3/NIN_80kbps_32khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_80kbps_44.1khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_80kbps_48khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_112kbps_32khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_112kbps_44.1khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_112kbps_48khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_192kbps_32khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_192kbps_44.1khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_192kbps_48khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_256kbps_44.1khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/NIN_256kbps_48khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/PD_112kbps_32khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/PD_112kbps_44.1khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/PD_112kbps_48khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/PD_192kbps_32khz_mono_CBR_DPA.mp3", + "/sdcard/media_api/music_perf/MP3/PD_256kbps_44.1khz_mono_CBR_DPA.mp3", + "/sdcard/media_api/music_perf/MP3/PD_256kbps_48khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/music_perf/MP3/WC_256kbps_44.1khz_mono_CBR_DPA.mp3", + "/sdcard/media_api/music_perf/MP3/WC_256kbps_48khz_mono_CBR_DPA.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/Apologize.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/Because_Of_You.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/Complicated.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/Glamorous.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/Im_With_You.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/Smile.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/Suddenly_I_See.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/When You Say Nothing At All.mp3", + "/sdcard/media_api/music_perf/regular_album_photo/my_happy_ending.mp3"}; public static String[] AACFILES = { - "/sdcard/music_perf/AAC/AI_AAC_24kbps_12khz_Mono_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/AI_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/AI_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/AI_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/AI_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/AI_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/NIN_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/NIN_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/NIN_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/NIN_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/NIN_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/PD_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/PD_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/PD_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/PD_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/PD_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/PV_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/PV_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/PV_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/PV_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/PV_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/WC_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/WC_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", - "/sdcard/music_perf/AAC/WC_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/WC_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", - "/sdcard/music_perf/AAC/WC_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/AI_AAC_24kbps_12khz_Mono_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/AI_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/AI_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/AI_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/AI_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/AI_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/NIN_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/NIN_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/NIN_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/NIN_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/NIN_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PD_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PD_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PD_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PD_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PD_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PV_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PV_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PV_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PV_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/PV_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/WC_AAC_56kbps_22.05khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/WC_AAC_56kbps_32khz_Stereo_CBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/WC_AAC_56kbps_44.1khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/WC_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4", + "/sdcard/media_api/music_perf/AAC/WC_AAC_80kbps_32khz_Stereo_CBR_SSE.mp4", }; - public static String[] VIDEOFILES = { "/sdcard/video_perf/AI_CTO_Mpeg4_32kbps_10fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", - "/sdcard/video_perf/AI_CTO_Mpeg4_32kbps_12fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", - "/sdcard/video_perf/AI_CTO_Mpeg4_32kbps_15fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", - "/sdcard/video_perf/AI_CTO_Mpeg4_32kbps_5fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", - "/sdcard/video_perf/AI_CTO_Mpeg4_32kbps_5fps_SQCIF_128x96+AAC_8kbps_8khz_mono_SSE.mp4", - "/sdcard/video_perf/AI_CTO_Mpeg4_32kbps_7.5fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", - "/sdcard/video_perf/AI_WMV_1024kbps_20fps_QCIF_176x144_noaudio_SSE.wmv", - "/sdcard/video_perf/AI_WMV_1024kbps_25fps_QCIF_176x144_noaudio_SSE.wmv", - "/sdcard/video_perf/Chicken.wmv", - "/sdcard/video_perf/MP_qcif_15fps_100kbps_48kHz_192kbps_30secs.wmv", - "/sdcard/video_perf/NIN_CTO_H264_123kbps_5fps_QCIF_176x144+AMR_12.2kbps_8khz_mono_QTE.3gp", - "/sdcard/video_perf/NIN_CTO_H264_96kbps_10.2fps_QCIF_176x144+AMR_12.2kbps_8khz_mono_QTE.3gp", - "/sdcard/video_perf/NIN_CTO_H264_96kbps_12fps_QCIF_176x144+AMR_12.2kbps_8khz_mono_QTE.3gp", - "/sdcard/video_perf/NIN_CTO_H264_96kbps_15fps_QCIF_176x144+AMR_12.2kbps_8khz_mono_QTE.3gp", - "/sdcard/video_perf/NIN_CTO_Mpeg4_123kbps_15fps_QCIF_176x144+AAC_32kbps_22khz_mono_SSE.3gp", - "/sdcard/video_perf/NIN_CTO_Mpeg4_123kbps_7.5fps_QCIF_176x144+AAC_32kbps_22khz_stereo_SSE.3gp", - "/sdcard/video_perf/NIN_CTO_Mpeg4_128kbps_10fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", - "/sdcard/video_perf/NIN_CTO_Mpeg4_128kbps_12fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", - "/sdcard/video_perf/NIN_CTO_Mpeg4_128kbps_15fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", - "/sdcard/video_perf/NIN_CTO_Mpeg4_128kbps_5fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", - "/sdcard/video_perf/NIN_CTO_Mpeg4_128kbps_7.5fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", - "/sdcard/video_perf/NIN_H263_128kbps_10fps_QCIF_174x144_noaudio_SSE.mp4", - "/sdcard/video_perf/NIN_H263_128kbps_15fps_QCIF_174x144_noaudio_SSE.mp4", - "/sdcard/video_perf/NIN_H263_48kbps_10fps_QCIF_174x144_noaudio_SSE.3gp", - "/sdcard/video_perf/NIN_H263_48kbps_12fps_QCIF_174x144_noaudio_SSE.3gp", - "/sdcard/video_perf/NIN_H264_123kbps_15fps_QCIF_176x144+AAC_32kbps_22khz_stereo_SSE.3gp", - "/sdcard/video_perf/NIN_H264_123kbps_7.5fps_QCIF_176x144+AAC_32kbps_22khz_stereo_SSE.3gp", - "/sdcard/video_perf/PV_H264_2000kbps_20fps_CIF_352x288+AAC_96kbps_48khz_stereo_SSE.mp4", - "/sdcard/video_perf/PV_H264_2000kbps_25fps_CIF_352x288+AAC_96kbps_48khz_stereo_SSE.mp4", - "/sdcard/video_perf/PV_H264_2000kbps_30fps_CIF_352x288+AAC_128kbps_48khz_stereo_SSE.mp4", - "/sdcard/video_perf/Stevie-1.wmv", - "/sdcard/video_perf/WC_H264_1600kbps_20fps_QCIF_176x144+AAC_96kbps_48khz_mono_SSE.mp4", - "/sdcard/video_perf/WC_H264_1600kbps_25fps_QCIF_176x144+AAC_96kbps_48khz_mono_SSE.mp4", - "/sdcard/video_perf/WC_H264_1600kbps_30fps_QCIF_176x144+AAC_96kbps_48khz_mono_SSE.mp4", - "/sdcard/video_perf/bugs.wmv", - "/sdcard/video_perf/niceday.wmv", - "/sdcard/video_perf/eaglesatopnflpe.wmv", + public static String[] VIDEOFILES = { "/sdcard/media_api/video_perf/AI_CTO_Mpeg4_32kbps_10fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", + "/sdcard/media_api/video_perf/AI_CTO_Mpeg4_32kbps_12fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", + "/sdcard/media_api/video_perf/AI_CTO_Mpeg4_32kbps_15fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", + "/sdcard/media_api/video_perf/AI_CTO_Mpeg4_32kbps_5fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", + "/sdcard/media_api/video_perf/AI_CTO_Mpeg4_32kbps_5fps_SQCIF_128x96+AAC_8kbps_8khz_mono_SSE.mp4", + "/sdcard/media_api/video_perf/AI_CTO_Mpeg4_32kbps_7.5fps_SQCIF_128x96+AAC_8kbps_8khz_mono_QTE.mp4", + "/sdcard/media_api/video_perf/AI_WMV_1024kbps_20fps_QCIF_176x144_noaudio_SSE.wmv", + "/sdcard/media_api/video_perf/AI_WMV_1024kbps_25fps_QCIF_176x144_noaudio_SSE.wmv", + "/sdcard/media_api/video_perf/Chicken.wmv", + "/sdcard/media_api/video_perf/MP_qcif_15fps_100kbps_48kHz_192kbps_30secs.wmv", + "/sdcard/media_api/video_perf/NIN_CTO_H264_123kbps_5fps_QCIF_176x144+AMR_12.2kbps_8khz_mono_QTE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_H264_96kbps_10.2fps_QCIF_176x144+AMR_12.2kbps_8khz_mono_QTE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_H264_96kbps_12fps_QCIF_176x144+AMR_12.2kbps_8khz_mono_QTE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_H264_96kbps_15fps_QCIF_176x144+AMR_12.2kbps_8khz_mono_QTE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_Mpeg4_123kbps_15fps_QCIF_176x144+AAC_32kbps_22khz_mono_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_Mpeg4_123kbps_7.5fps_QCIF_176x144+AAC_32kbps_22khz_stereo_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_Mpeg4_128kbps_10fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_Mpeg4_128kbps_12fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_Mpeg4_128kbps_15fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_Mpeg4_128kbps_5fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_CTO_Mpeg4_128kbps_7.5fps_QCIF_176x144+AAC+_32kbps_48khz_stereo_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_H263_128kbps_10fps_QCIF_174x144_noaudio_SSE.mp4", + "/sdcard/media_api/video_perf/NIN_H263_128kbps_15fps_QCIF_174x144_noaudio_SSE.mp4", + "/sdcard/media_api/video_perf/NIN_H263_48kbps_10fps_QCIF_174x144_noaudio_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_H263_48kbps_12fps_QCIF_174x144_noaudio_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_H264_123kbps_15fps_QCIF_176x144+AAC_32kbps_22khz_stereo_SSE.3gp", + "/sdcard/media_api/video_perf/NIN_H264_123kbps_7.5fps_QCIF_176x144+AAC_32kbps_22khz_stereo_SSE.3gp", + "/sdcard/media_api/video_perf/PV_H264_2000kbps_20fps_CIF_352x288+AAC_96kbps_48khz_stereo_SSE.mp4", + "/sdcard/media_api/video_perf/PV_H264_2000kbps_25fps_CIF_352x288+AAC_96kbps_48khz_stereo_SSE.mp4", + "/sdcard/media_api/video_perf/PV_H264_2000kbps_30fps_CIF_352x288+AAC_128kbps_48khz_stereo_SSE.mp4", + "/sdcard/media_api/video_perf/Stevie-1.wmv", + "/sdcard/media_api/video_perf/WC_H264_1600kbps_20fps_QCIF_176x144+AAC_96kbps_48khz_mono_SSE.mp4", + "/sdcard/media_api/video_perf/WC_H264_1600kbps_25fps_QCIF_176x144+AAC_96kbps_48khz_mono_SSE.mp4", + "/sdcard/media_api/video_perf/WC_H264_1600kbps_30fps_QCIF_176x144+AAC_96kbps_48khz_mono_SSE.mp4", + "/sdcard/media_api/video_perf/bugs.wmv", + "/sdcard/media_api/video_perf/niceday.wmv", + "/sdcard/media_api/video_perf/eaglesatopnflpe.wmv", }; //wma - only support up to wma 9 public static String[] WMASUPPORTED = { - "/sdcard/music_perf/WMASUPPORTED/AI_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/AI_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/NIN_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/NIN_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/PD_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/PD_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/PV_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/PV_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/WC_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", - "/sdcard/music_perf/WMASUPPORTED/WC_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma" + "/sdcard/media_api/music_perf/WMASUPPORTED/AI_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/AI_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/NIN_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/NIN_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/PD_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/PD_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/PV_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/PV_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/WC_WMA9.2_32kbps_44.1khz_mono_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMASUPPORTED/WC_WMA9.2_48kbps_44.1khz_mono_CBR_DPA.wma" }; public static String[] WMAUNSUPPORTED = { - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_127kbps_48khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_128kbps_44.1khz_stereo_2pVBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_128kbps_48khz_stereo_2pVBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_128kbps_88khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_128kbps_96khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_192kbps_44.1khz_stereo_2pVBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_192kbps_88khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_192kbps_96khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_256kbps_44khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_256kbps_48khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_256kbps_88khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_256kbps_96khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_384kbps_44khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_384kbps_48khz_stereo_CBR_DPA.wma", - "/sdcard/music_perf/WMAUNSUPPORTED/AI_WMA10_384kbps_88khz_stereo_CBR_DPA.wma" + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_127kbps_48khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_128kbps_44.1khz_stereo_2pVBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_128kbps_48khz_stereo_2pVBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_128kbps_88khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_128kbps_96khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_192kbps_44.1khz_stereo_2pVBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_192kbps_88khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_192kbps_96khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_256kbps_44khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_256kbps_48khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_256kbps_88khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_256kbps_96khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_384kbps_44khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_384kbps_48khz_stereo_CBR_DPA.wma", + "/sdcard/media_api/music_perf/WMAUNSUPPORTED/AI_WMA10_384kbps_88khz_stereo_CBR_DPA.wma" }; //Media Recorder - public static final String RECORDER_OUTPUT = "/sdcard/recorderOutput.amr"; + public static final String RECORDER_OUTPUT = "/sdcard/media_api/recorderOutput.amr"; //video thumbnail - public static final String THUMBNAIL_OUTPUT = "/sdcard/videoThumbnail.png"; - public static final String GOLDEN_THUMBNAIL_OUTPUT = "/sdcard/goldenThumbnail.png"; + public static final String THUMBNAIL_OUTPUT = "/sdcard/media_api/videoThumbnail.png"; + public static final String GOLDEN_THUMBNAIL_OUTPUT = "/sdcard/media_api/goldenThumbnail.png"; //Metadata Utility public static final String[] THUMBNAIL_CAPTURE_TEST_FILES = { - "/sdcard/metadata/test.mp4", - "/sdcard/metadata/test1.3gp", - "/sdcard/metadata/test2.3gp", - "/sdcard/metadata/test3.3gp", - "/sdcard/metadata/test4.3gp", - "/sdcard/metadata/test5.3gp", - "/sdcard/metadata/test6.3gp", - "/sdcard/metadata/test7.3gp", - "/sdcard/metadata/test8.3gp", - "/sdcard/metadata/test9.3gp", - "/sdcard/metadata/test10.3gp", - "/sdcard/metadata/test11.3gp", - "/sdcard/metadata/test12.3gp", - "/sdcard/metadata/test13.3gp", - "/sdcard/metadata/test14.3gp", - "/sdcard/metadata/test15.3gp", - "/sdcard/metadata/test16.3gp", - "/sdcard/metadata/test17.3gp", - "/sdcard/metadata/test18.3gp", - "/sdcard/metadata/test19.3gp", - "/sdcard/metadata/test20.3gp", - "/sdcard/metadata/test21.3gp", - "/sdcard/metadata/test22.3gp", - "/sdcard/metadata/test23.3gp", - "/sdcard/metadata/test24.3gp", - "/sdcard/metadata/test25.3gp", - "/sdcard/metadata/test26.3gp", - "/sdcard/metadata/test27.3gp", - "/sdcard/metadata/test28.3gp", - "/sdcard/metadata/test29.3gp", - "/sdcard/metadata/test30.3gp", - "/sdcard/metadata/test31.3gp", - "/sdcard/metadata/test32.3gp", - "/sdcard/metadata/test33.3gp", - "/sdcard/metadata/test35.mp4", - "/sdcard/metadata/test36.m4v", - "/sdcard/metadata/test34.wmv", - "/sdcard/metadata/test_metadata.mp4", + "/sdcard/media_api/metadata/test.mp4", + "/sdcard/media_api/metadata/test1.3gp", + "/sdcard/media_api/metadata/test2.3gp", + "/sdcard/media_api/metadata/test3.3gp", + "/sdcard/media_api/metadata/test4.3gp", + "/sdcard/media_api/metadata/test5.3gp", + "/sdcard/media_api/metadata/test6.3gp", + "/sdcard/media_api/metadata/test7.3gp", + "/sdcard/media_api/metadata/test8.3gp", + "/sdcard/media_api/metadata/test9.3gp", + "/sdcard/media_api/metadata/test10.3gp", + "/sdcard/media_api/metadata/test11.3gp", + "/sdcard/media_api/metadata/test12.3gp", + "/sdcard/media_api/metadata/test13.3gp", + "/sdcard/media_api/metadata/test14.3gp", + "/sdcard/media_api/metadata/test15.3gp", + "/sdcard/media_api/metadata/test16.3gp", + "/sdcard/media_api/metadata/test17.3gp", + "/sdcard/media_api/metadata/test18.3gp", + "/sdcard/media_api/metadata/test19.3gp", + "/sdcard/media_api/metadata/test20.3gp", + "/sdcard/media_api/metadata/test21.3gp", + "/sdcard/media_api/metadata/test22.3gp", + "/sdcard/media_api/metadata/test23.3gp", + "/sdcard/media_api/metadata/test24.3gp", + "/sdcard/media_api/metadata/test25.3gp", + "/sdcard/media_api/metadata/test26.3gp", + "/sdcard/media_api/metadata/test27.3gp", + "/sdcard/media_api/metadata/test28.3gp", + "/sdcard/media_api/metadata/test29.3gp", + "/sdcard/media_api/metadata/test30.3gp", + "/sdcard/media_api/metadata/test31.3gp", + "/sdcard/media_api/metadata/test32.3gp", + "/sdcard/media_api/metadata/test33.3gp", + "/sdcard/media_api/metadata/test35.mp4", + "/sdcard/media_api/metadata/test36.m4v", + "/sdcard/media_api/metadata/test34.wmv", + "/sdcard/media_api/metadata/test_metadata.mp4", }; public static final String[] METADATA_RETRIEVAL_TEST_FILES = { // Raw AAC is not supported - // "/sdcard/test_raw.aac", - // "/sdcard/test_adts.aac", - // "/sdcard/test_adif.aac", - "/sdcard/metadata/test_metadata.mp4", - "/sdcard/metadata/WMA10.wma", - "/sdcard/metadata/Leadsol_out.wav", - "/sdcard/metadata/test_aac.mp4", - "/sdcard/metadata/test_amr.mp4", - "/sdcard/metadata/test_avc_amr.mp4", - "/sdcard/metadata/test_metadata.mp4", - "/sdcard/metadata/test_vbr.mp3", - "/sdcard/metadata/test_cbr.mp3", - "/sdcard/metadata/metadata_test1.mp3", - "/sdcard/metadata/test33.3gp", - "/sdcard/metadata/test35.mp4", - "/sdcard/metadata/test36.m4v", - "/sdcard/metadata/test_m4v_amr.mp4", - "/sdcard/metadata/test_h263_amr.mp4", - "/sdcard/metadata/test34.wmv", + // "/sdcard/media_api/test_raw.aac", + // "/sdcard/media_api/test_adts.aac", + // "/sdcard/media_api/test_adif.aac", + "/sdcard/media_api/metadata/test_metadata.mp4", + "/sdcard/media_api/metadata/WMA10.wma", + "/sdcard/media_api/metadata/Leadsol_out.wav", + "/sdcard/media_api/metadata/test_aac.mp4", + "/sdcard/media_api/metadata/test_amr.mp4", + "/sdcard/media_api/metadata/test_avc_amr.mp4", + "/sdcard/media_api/metadata/test_metadata.mp4", + "/sdcard/media_api/metadata/test_vbr.mp3", + "/sdcard/media_api/metadata/test_cbr.mp3", + "/sdcard/media_api/metadata/metadata_test1.mp3", + "/sdcard/media_api/metadata/test33.3gp", + "/sdcard/media_api/metadata/test35.mp4", + "/sdcard/media_api/metadata/test36.m4v", + "/sdcard/media_api/metadata/test_m4v_amr.mp4", + "/sdcard/media_api/metadata/test_h263_amr.mp4", + "/sdcard/media_api/metadata/test34.wmv", }; public static final String[] ALBUMART_TEST_FILES = { - "/sdcard/album_photo/test_22_16_mp3.mp3", - "/sdcard/album_photo/PD_256kbps_48khz_mono_CBR_MCA.mp3", - "/sdcard/album_photo/PD_256kbps_44.1khz_mono_CBR_DPA.mp3", - "/sdcard/album_photo/PD_192kbps_32khz_mono_CBR_DPA.mp3", - "/sdcard/album_photo/NIN_256kbps_48khz_mono_CBR_MCA.mp3", - "/sdcard/album_photo/NIN_256kbps_44.1khz_mono_CBR_MCA.mp3", - "/sdcard/album_photo/NIN_112kbps(96kbps)_48khz_stereo_VBR_MCA.mp3", - "/sdcard/album_photo/NIN_112kbps(96kbps)_44.1khz_stereo_VBR_MCA.mp3", - "/sdcard/album_photo/lightGreen1.mp3", - "/sdcard/album_photo/babyBlue2 1.mp3", - "/sdcard/album_photo/2-01 01 NIN_56kbps(64kbps)_32khz_stereo_VBR_MCA.mp3", - "/sdcard/album_photo/02_NIN_112kbps(80kbps)_32khz_stereo_VBR_MCA.mp3", - "/sdcard/album_photo/No_Woman_No_Cry_128K.wma", - "/sdcard/album_photo/Beethoven_2.wma", + "/sdcard/media_api/album_photo/test_22_16_mp3.mp3", + "/sdcard/media_api/album_photo/PD_256kbps_48khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/album_photo/PD_256kbps_44.1khz_mono_CBR_DPA.mp3", + "/sdcard/media_api/album_photo/PD_192kbps_32khz_mono_CBR_DPA.mp3", + "/sdcard/media_api/album_photo/NIN_256kbps_48khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/album_photo/NIN_256kbps_44.1khz_mono_CBR_MCA.mp3", + "/sdcard/media_api/album_photo/NIN_112kbps(96kbps)_48khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/album_photo/NIN_112kbps(96kbps)_44.1khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/album_photo/lightGreen1.mp3", + "/sdcard/media_api/album_photo/babyBlue2 1.mp3", + "/sdcard/media_api/album_photo/2-01 01 NIN_56kbps(64kbps)_32khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/album_photo/02_NIN_112kbps(80kbps)_32khz_stereo_VBR_MCA.mp3", + "/sdcard/media_api/album_photo/No_Woman_No_Cry_128K.wma", + "/sdcard/media_api/album_photo/Beethoven_2.wma", }; //TEST_PATH_1: is a video and contains metadata for key "num-tracks" // TEST_PATH_2: any valid media file. // TEST_PATH_3: invalid media file - public static final String TEST_PATH_1 = "/sdcard/metadata/test.mp4"; - public static final String TEST_PATH_3 = "/sdcard/data.txt"; + public static final String TEST_PATH_1 = "/sdcard/media_api/metadata/test.mp4"; + public static final String TEST_PATH_3 = "/sdcard/media_api/data.txt"; public static final String TEST_PATH_4 = "somenonexistingpathname"; public static final String TEST_PATH_5 = "mem://012345"; @@ -376,81 +378,81 @@ public class MediaNames { //cd_track_number, album, artist, author, composer, date, genre //title, years, duration public static final String META_DATA_MP3 [][] = { - {"/sdcard/metaDataTestMedias/MP3/ID3V1_ID3V2.mp3", "1/10", "ID3V2.3 Album", "ID3V2.3 Artist", + {"/sdcard/media_api/metaDataTestMedias/MP3/ID3V1_ID3V2.mp3", "1/10", "ID3V2.3 Album", "ID3V2.3 Artist", "ID3V2.3 Lyricist", "ID3V2.3 Composer", null, "Blues", "ID3V2.3 Title", "1234", "321", "1"}, - {"/sdcard/metaDataTestMedias/MP3/ID3V2.mp3", "1/10", "ID3V2.3 Album", "ID3V2.3 Artist", + {"/sdcard/media_api/metaDataTestMedias/MP3/ID3V2.mp3", "1/10", "ID3V2.3 Album", "ID3V2.3 Artist", "ID3V2.3 Lyricist", "ID3V2.3 Composer", null, "Blues", "ID3V2.3 Title", "1234", "313", "1"}, - {"/sdcard/metaDataTestMedias/MP3/ID3V1.mp3", null, "test ID3V1 Album", "test ID3V1 Artist", + {"/sdcard/media_api/metaDataTestMedias/MP3/ID3V1.mp3", null, "test ID3V1 Album", "test ID3V1 Artist", null, null, null, null, "test ID3V1 Title", "1234", "231332", "1"}, - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V1.mp3" , null, null, null, + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V1.mp3" , null, null, null, null, null, null, null, null, null, "231330", "1"}, //The corrupted TALB field in id3v2 would not switch to id3v1 tag automatically - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V2_TALB.mp3", "01", null, "ID3V2.3 Artist", + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TALB.mp3", "01", null, "ID3V2.3 Artist", "ID3V2.3 Lyricist", "ID3V2.3 Composer", null, "Blues", "ID3V2.3 Title", "1234", "321", "1"}, - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V2_TCOM.mp3", "01", "ID3V2.3 Album", + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TCOM.mp3", "01", "ID3V2.3 Album", "ID3V2.3 Artist", "ID3V2.3 Lyricist", null, null, "Blues", "ID3V2.3 Title", "1234", "321", "1"}, - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V2_TCOM_2.mp3", "01", "ID3V2.3 Album", + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TCOM_2.mp3", "01", "ID3V2.3 Album", "ID3V2.3 Artist", null, null, null, "Blues", "ID3V2.3 Title", "1234", "321", "1"}, - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V2_TRCK.mp3", "dd", "ID3V2.3 Album", + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TRCK.mp3", "dd", "ID3V2.3 Album", "ID3V2.3 Artist", "ID3V2.3 Lyricist", "ID3V2.3 Composer", null, "Blues", "ID3V2.3 Title", "1234", "321", "1"}, - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V2_TRCK_2.mp3", "01", "ID3V2.3 Album", + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TRCK_2.mp3", "01", "ID3V2.3 Album", "ID3V2.3 Artist", null, null, null, null, "ID3V2.3 Title", null, "321", "1"}, - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V2_TYER.mp3", "01", "ID3V2.3 Album", + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TYER.mp3", "01", "ID3V2.3 Album", "ID3V2.3 Artist", null, null, null, null, "ID3V2.3 Title", "9999", "321", "1"}, - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V2_TYER_2.mp3", "01", "ID3V2.3 Album", + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TYER_2.mp3", "01", "ID3V2.3 Album", "ID3V2.3 Artist", "ID3V2.3 Lyricist", "ID3V2.3 Composer", null, "Blues", "ID3V2.3 Title", null, "321", "1"}, - {"/sdcard/metaDataTestMedias/MP3/Corrupted_ID3V2_TIT.mp3", null, null, null, + {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TIT.mp3", null, null, null, null, null, null, null, null, null, "577", "1"} }; public static final String META_DATA_OTHERS [][] = { - {"/sdcard/metaDataTestMedias/3GP/cat.3gp", null, null, null, + {"/sdcard/media_api/metaDataTestMedias/3GP/cat.3gp", null, null, null, null, null, "20080309T002415.000Z", null, null, null, "1404928", "2"}, - {"/sdcard/metaDataTestMedias/AMR/AMR_NB.amr", null, null, null, + {"/sdcard/media_api/metaDataTestMedias/AMR/AMR_NB.amr", null, null, null, null, null, null, null, null, null, "126540", "1"}, - {"/sdcard/metaDataTestMedias/AMRWB/AMR_WB.amr", null, null, null, + {"/sdcard/media_api/metaDataTestMedias/AMRWB/AMR_WB.amr", null, null, null, null, null, null, null, null, null, "231180", "1"}, - {"/sdcard/metaDataTestMedias/M4A/Jaws Of Life_ver1.m4a", null, "Suspended Animation", + {"/sdcard/media_api/metaDataTestMedias/M4A/Jaws Of Life_ver1.m4a", null, "Suspended Animation", "John Petrucci", null, null, "20070510T125223.000Z", null, null, "2005", "231180", "1"}, - {"/sdcard/metaDataTestMedias/M4V/sample_iPod.m4v", null, null, + {"/sdcard/media_api/metaDataTestMedias/M4V/sample_iPod.m4v", null, null, null, null, null, "20051220T202015.000Z", null, null, null, "3771392", "2"}, - {"/sdcard/metaDataTestMedias/MIDI/MIDI.mid", null, "Suspended Animation", + {"/sdcard/media_api/metaDataTestMedias/MIDI/MIDI.mid", null, "Suspended Animation", "John Petrucci", null, null, "20070510T125223.000Z", null, null, "2005", "231180", "1"}, - {"/sdcard/metaDataTestMedias/MP4/kung_fu_panda_h264.mp4", null, "mp4 album Kung Fu Panda", + {"/sdcard/media_api/metaDataTestMedias/MP4/kung_fu_panda_h264.mp4", null, "mp4 album Kung Fu Panda", "mp4 artist Kung Fu Panda", null, null, "20080517T091451.000Z", "Kung Fu Panda", "Kung Fu Panda", "2008", "5667840", "2"}, - {"/sdcard/metaDataTestMedias/OGG/Ring_Classic_02.ogg", null, "Suspended Animation", + {"/sdcard/media_api/metaDataTestMedias/OGG/Ring_Classic_02.ogg", null, "Suspended Animation", "John Petrucci", null, null, "20070510T125223.000Z", null, null, "2005", "231180", "1"}, - {"/sdcard/metaDataTestMedias/OGG/When You Say Nothing At All.ogg", + {"/sdcard/media_api/metaDataTestMedias/OGG/When You Say Nothing At All.ogg", null, "Suspended Animation", "John Petrucci", null, null, "20070510T125223.000Z", null, null, "2005", "231180", "1"}, - {"/sdcard/metaDataTestMedias/WAV/Im With You.wav", null, null, + {"/sdcard/media_api/metaDataTestMedias/WAV/Im With You.wav", null, null, null, null, null, null, null, null, null, "224000", "1"}, - {"/sdcard/metaDataTestMedias/WMA/WMA9.wma", "6", "Ten Songs in the Key of Betrayal", + {"/sdcard/media_api/metaDataTestMedias/WMA/WMA9.wma", "6", "Ten Songs in the Key of Betrayal", "Alien Crime Syndicate", "Alien Crime Syndicate", "wma 9 Composer", "20040521T175729.483Z", "Rock", "Run for the Money", "2004", "134479", "1"}, - {"/sdcard/metaDataTestMedias/WMA/WMA10.wma", "09", "wma 10 Album", + {"/sdcard/media_api/metaDataTestMedias/WMA/WMA10.wma", "09", "wma 10 Album", "wma 10 Album Artist", "wma 10 Artist", "wma 10 Composer", "20070705T063625.097Z", "Acid Jazz", "wma 10 Title", "2010", "126574", "1"}, - {"/sdcard/metaDataTestMedias/WMV/bugs.wmv", "8", "wmv 9 Album", + {"/sdcard/media_api/metaDataTestMedias/WMV/bugs.wmv", "8", "wmv 9 Album", null, "wmv 9 Artist ", null, "20051122T155247.540Z", null, "Looney Tunes - Hare-Breadth Hurry", "2005", "193482", "2"}, - {"/sdcard/metaDataTestMedias/WMV/clips_ver7.wmv", "50", "wmv 7 Album", + {"/sdcard/media_api/metaDataTestMedias/WMV/clips_ver7.wmv", "50", "wmv 7 Album", null, "Hallau Shoots & Company", null, "20020226T170045.891Z", null, "CODEC Shootout", "1986", "43709", "2"} }; @@ -471,9 +473,39 @@ public class MediaNames { public static final String RECORDED_VIDEO_3GP = "/sdcard/temp.3gp"; + public static final String INVALD_VIDEO_PATH = "/sdcard/media_api/filepathdoesnotexist" + + "/filepathdoesnotexist/temp.3gp"; + - public static final long RECORDED_TIME = 3000; + public static final long RECORDED_TIME = 5000; public static final long VALID_VIDEO_DURATION = 2000; - + //Videos for the mediaplayer stress test + public static String[] H263_STRESS = { + "/sdcard/media_api/video_stress/h263/H263_CIF.3gp", + "/sdcard/media_api/video_stress/h263/H263_QCIF.3gp", + "/sdcard/media_api/video_stress/h263/H263_QVGA.3gp", + "/sdcard/media_api/video_stress/h263/H263_SQVGA.3gp" + }; + + public static String[] MPEG4_STRESS = { + "/sdcard/media_api/video_stress/h263/mpeg4_CIF.mp4", + "/sdcard/media_api/video_stress/h263/mpeg4_QCIF.3gp", + "/sdcard/media_api/video_stress/h263/mpeg4_QVGA.3gp", + "/sdcard/media_api/video_stress/h263/mpeg4_SQVGA.mp4" + }; + + //Streaming test files + public static final String STREAM_H264_480_360_1411k = + "http://sridharg.googlejunta.com/yslau/stress_media/h264_regular.mp4"; + public static final String STREAM_WMV = + "http://sridharg.googlejunta.com/yslau/stress_media/bugs.wmv"; + public static final String STREAM_H263_176x144_325k = + "http://sridharg.googlejunta.com/yslau/stress_media/h263_regular.3gp"; + public static final String STREAM_H264_352x288_1536k = + "http://sridharg.googlejunta.com/yslau/stress_media/h264_highBitRate.mp4"; + public static final String STREAM_MP3= + "http://sridharg.googlejunta.com/yslau/stress_media/mp3_regular.mp3"; + public static final String STREAM_MPEG4_QVGA_128k = + "http://sridharg.googlejunta.com/yslau/stress_media/mpeg4_qvga_24fps.3gp"; } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java new file mode 100755 index 0000000000000000000000000000000000000000..12eacd3402b9175b6de7877af1de9d323692e912 --- /dev/null +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java @@ -0,0 +1,38 @@ +/* + * 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. + */ + +package com.android.mediaframeworktest; + +import android.test.InstrumentationTestRunner; +import android.test.InstrumentationTestSuite; +import com.android.mediaframeworktest.stress.MediaRecorderStressTest; + +import junit.framework.TestSuite; + +public class MediaRecorderStressTestRunner extends InstrumentationTestRunner { + + @Override + public TestSuite getAllTests() { + TestSuite suite = new InstrumentationTestSuite(this); + suite.addTestSuite(MediaRecorderStressTest.class); + return suite; + } + + @Override + public ClassLoader getLoader() { + return MediaRecorderStressTestRunner.class.getClassLoader(); + } +} diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CameraTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CameraTest.java index 5981a1395b42d6fd3fd6e3d38e252f53dfe25870..c30db38317437ed8fb52c084e83d279a3ec91f30 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CameraTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CameraTest.java @@ -100,6 +100,12 @@ public class CameraTest extends ActivityInstrumentationTestCase { + private String TAG = "MediaAudioTrackTest"; + + public MediaAudioTrackTest() { + super("com.android.mediaframeworktest", MediaFrameworkTest.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + private static void assumeTrue(String message, boolean cond) { + assertTrue("(assume)"+message, cond); + } + + private void log(String testName, String message) { + Log.v(TAG, "["+testName+"] "+message); + } + + private void loge(String testName, String message) { + Log.e(TAG, "["+testName+"] "+message); + } + + //----------------------------------------------------------------- + // private class to hold test reslts + public class TestResults { + public boolean mResult = false; + public String mResultLog = ""; + public TestResults(boolean b, String s) { mResult = b; mResultLog = s; } + } + + //----------------------------------------------------------------- + // generic test methods + public TestResults constructorTestMultiSampleRate( + // parameters tested by this method + int _inTest_streamType, int _inTest_mode, + int _inTest_config, int _inTest_format, + // parameter-dependent expected results + int _expected_stateForMode) { + + int[] testSampleRates = {8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000}; + String failedRates = "Failure for rate(s): "; + boolean localRes, finalRes = true; + + for (int i = 0 ; i < testSampleRates.length ; i++) { + //Log.v("MediaAudioTrackTest", "[ constructorTestMultiSampleRate ] testing "+ testSampleRates[i]); + AudioTrack track = null; + try { + track = new AudioTrack( + _inTest_streamType, + testSampleRates[i], + _inTest_config, + _inTest_format, + AudioTrack.getMinBufferSize(testSampleRates[i], + _inTest_config, _inTest_format), + _inTest_mode); + } catch(IllegalArgumentException iae) { + Log.e("MediaAudioTrackTest", "[ constructorTestMultiSampleRate ] exception at SR " + + testSampleRates[i]+": \n" + iae); + localRes = false; + } + if (track != null) { + localRes = (track.getState() == _expected_stateForMode); + track.release(); + } + else { + localRes = false; + } + + if (!localRes) { + //log the error for the test runner + failedRates += Integer.toString(testSampleRates[i]) + "Hz "; + //log the error for logcat + log("constructorTestMultiSampleRate", "failed to construct " + +"AudioTrack(streamType="+_inTest_streamType + +", sampleRateInHz=" + testSampleRates[i] + +", channelConfig=" + _inTest_config + +", audioFormat=" + _inTest_format + +", bufferSizeInBytes=" + AudioTrack.getMinBufferSize(testSampleRates[i], + _inTest_config, AudioFormat.ENCODING_PCM_16BIT) + +", mode="+ _inTest_mode ); + //mark test as failed + finalRes = false; + } + } + return new TestResults(finalRes, failedRates); + } + + //----------------------------------------------------------------- + // AUDIOTRACK TESTS: + //---------------------------------- + + //----------------------------------------------------------------- + // AudioTrack constructor and AudioTrack.getMinBufferSize(...) for 16bit PCM + //---------------------------------- + + //Test case 1: constructor for streaming AudioTrack, mono, 16bit at misc valid sample rates + @LargeTest + public void testConstructorMono16MusicStream() throws Exception { + + TestResults res = constructorTestMultiSampleRate( + AudioManager.STREAM_MUSIC, AudioTrack.MODE_STREAM, + AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, + AudioTrack.STATE_INITIALIZED); + + assertTrue("testConstructorMono16MusicStream: " + res.mResultLog, res.mResult); + } + + + //Test case 2: constructor for streaming AudioTrack, stereo, 16bit at misc valid sample rates + @LargeTest + public void testConstructorStereo16MusicStream() throws Exception { + + TestResults res = constructorTestMultiSampleRate( + AudioManager.STREAM_MUSIC, AudioTrack.MODE_STREAM, + AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, + AudioTrack.STATE_INITIALIZED); + + assertTrue("testConstructorStereo16MusicStream: " + res.mResultLog, res.mResult); + } + + + //Test case 3: constructor for static AudioTrack, mono, 16bit at misc valid sample rates + @LargeTest + public void testConstructorMono16MusicStatic() throws Exception { + + TestResults res = constructorTestMultiSampleRate( + AudioManager.STREAM_MUSIC, AudioTrack.MODE_STATIC, + AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, + AudioTrack.STATE_NO_STATIC_DATA); + + assertTrue("testConstructorMono16MusicStatic: " + res.mResultLog, res.mResult); + } + + + //Test case 4: constructor for static AudioTrack, stereo, 16bit at misc valid sample rates + @LargeTest + public void testConstructorStereo16MusicStatic() throws Exception { + + TestResults res = constructorTestMultiSampleRate( + AudioManager.STREAM_MUSIC, AudioTrack.MODE_STATIC, + AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, + AudioTrack.STATE_NO_STATIC_DATA); + + assertTrue("testConstructorStereo16MusicStatic: " + res.mResultLog, res.mResult); + } + + + //----------------------------------------------------------------- + // AudioTrack constructor and AudioTrack.getMinBufferSize(...) for 8bit PCM + //---------------------------------- + + //Test case 1: constructor for streaming AudioTrack, mono, 8bit at misc valid sample rates + @LargeTest + public void testConstructorMono8MusicStream() throws Exception { + + TestResults res = constructorTestMultiSampleRate( + AudioManager.STREAM_MUSIC, AudioTrack.MODE_STREAM, + AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, + AudioTrack.STATE_INITIALIZED); + + assertTrue("testConstructorMono8MusicStream: " + res.mResultLog, res.mResult); + } + + //Test case 2: constructor for streaming AudioTrack, stereo, 8bit at misc valid sample rates + @LargeTest + public void testConstructorStereo8MusicStream() throws Exception { + + TestResults res = constructorTestMultiSampleRate( + AudioManager.STREAM_MUSIC, AudioTrack.MODE_STREAM, + AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_8BIT, + AudioTrack.STATE_INITIALIZED); + + assertTrue("testConstructorStereo8MusicStream: " + res.mResultLog, res.mResult); + } + + //Test case 3: constructor for static AudioTrack, mono, 8bit at misc valid sample rates + @LargeTest + public void testConstructorMono8MusicStatic() throws Exception { + + TestResults res = constructorTestMultiSampleRate( + AudioManager.STREAM_MUSIC, AudioTrack.MODE_STATIC, + AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, + AudioTrack.STATE_NO_STATIC_DATA); + + assertTrue("testConstructorMono8MusicStatic: " + res.mResultLog, res.mResult); + } + + //Test case 4: constructor for static AudioTrack, stereo, 8bit at misc valid sample rates + @LargeTest + public void testConstructorStereo8MusicStatic() throws Exception { + + TestResults res = constructorTestMultiSampleRate( + AudioManager.STREAM_MUSIC, AudioTrack.MODE_STATIC, + AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_8BIT, + AudioTrack.STATE_NO_STATIC_DATA); + + assertTrue("testConstructorStereo8MusicStatic: " + res.mResultLog, res.mResult); + } + + + //----------------------------------------------------------------- + // AudioTrack constructor for all stream types + //---------------------------------- + + //Test case 1: constructor for all stream types + @LargeTest + public void testConstructorStreamType() throws Exception { + // constants for test + final int TYPE_TEST_SR = 22050; + final int TYPE_TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TYPE_TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TYPE_TEST_MODE = AudioTrack.MODE_STREAM; + final int[] STREAM_TYPES = { AudioManager.STREAM_ALARM, AudioManager.STREAM_BLUETOOTH_SCO, + AudioManager.STREAM_MUSIC, AudioManager.STREAM_NOTIFICATION, + AudioManager.STREAM_RING, AudioManager.STREAM_SYSTEM, + AudioManager.STREAM_VOICE_CALL }; + final String[] STREAM_NAMES = { "STREAM_ALARM", "STREAM_BLUETOOTH_SCO", "STREAM_MUSIC", + "STREAM_NOTIFICATION", "STREAM_RING", "STREAM_SYSTEM", "STREAM_VOICE_CALL" }; + + boolean localTestRes = true; + AudioTrack track = null; + // test: loop constructor on all stream types + for (int i = 0 ; i < STREAM_TYPES.length ; i++) + { + try { + //-------- initialization -------------- + track = new AudioTrack(STREAM_TYPES[i], + TYPE_TEST_SR, TYPE_TEST_CONF, TYPE_TEST_FORMAT, + AudioTrack.getMinBufferSize(TYPE_TEST_SR, TYPE_TEST_CONF, TYPE_TEST_FORMAT), + TYPE_TEST_MODE); + } catch (IllegalArgumentException iae) { + loge("testConstructorStreamType", "exception for stream type " + + STREAM_NAMES[i] + ": "+ iae); + localTestRes = false; + } + //-------- test -------------- + if (track != null) { + if (track.getState() != AudioTrack.STATE_INITIALIZED) { + localTestRes = false; + Log.e("MediaAudioTrackTest", + "[ testConstructorStreamType ] failed for stream type "+STREAM_NAMES[i]); + } + //-------- tear down -------------- + track.release(); + } + else { + localTestRes = false; + } + } + + assertTrue("testConstructorStreamType", localTestRes); + } + + + //----------------------------------------------------------------- + // Playback head position + //---------------------------------- + + //Test case 1: getPlaybackHeadPosition() at 0 after initialization + @LargeTest + public void testPlaybackHeadPositionAfterInit() throws Exception { + // constants for test + final String TEST_NAME = "testPlaybackHeadPositionAfterInit"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT), TEST_MODE); + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, track.getPlaybackHeadPosition() == 0); + //-------- tear down -------------- + track.release(); + } + + //Test case 2: getPlaybackHeadPosition() increases after play() + @LargeTest + public void testPlaybackHeadPositionIncrease() throws Exception { + // constants for test + final String TEST_NAME = "testPlaybackHeadPositionIncrease"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + Thread.sleep(100); + log(TEST_NAME, "position ="+ track.getPlaybackHeadPosition()); + assertTrue(TEST_NAME, track.getPlaybackHeadPosition() > 0); + //-------- tear down -------------- + track.release(); + } + + //Test case 3: getPlaybackHeadPosition() is 0 after flush(); + @LargeTest + public void testPlaybackHeadPositionAfterFlush() throws Exception { + // constants for test + final String TEST_NAME = "testPlaybackHeadPositionAfterFlush"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + Thread.sleep(100); + track.stop(); + track.flush(); + log(TEST_NAME, "position ="+ track.getPlaybackHeadPosition()); + assertTrue(TEST_NAME, track.getPlaybackHeadPosition() == 0); + //-------- tear down -------------- + track.release(); + } + + //Test case 3: getPlaybackHeadPosition() is 0 after stop(); + @LargeTest + public void testPlaybackHeadPositionAfterStop() throws Exception { + // constants for test + final String TEST_NAME = "testPlaybackHeadPositionAfterStop"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + Thread.sleep(100); + track.stop(); + Thread.sleep(100); // TODO: what is a sensible value? + int pos = track.getPlaybackHeadPosition(); + log(TEST_NAME, "position ="+ pos); + assertTrue(TEST_NAME, pos == 0); + //-------- tear down -------------- + track.release(); + } + + //Test case 4: getPlaybackHeadPosition() is > 0 after play(); pause(); + @LargeTest + public void testPlaybackHeadPositionAfterPause() throws Exception { + // constants for test + final String TEST_NAME = "testPlaybackHeadPositionAfterPause"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + Thread.sleep(100); + track.pause(); + int pos = track.getPlaybackHeadPosition(); + log(TEST_NAME, "position ="+ pos); + assertTrue(TEST_NAME, pos > 0); + //-------- tear down -------------- + track.release(); + } + + + //----------------------------------------------------------------- + // Playback properties + //---------------------------------- + + //Test case 1: setStereoVolume() with max volume returns SUCCESS + @LargeTest + public void testSetStereoVolumeMax() throws Exception { + // constants for test + final String TEST_NAME = "testSetStereoVolumeMax"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + float maxVol = AudioTrack.getMaxVolume(); + assertTrue(TEST_NAME, track.setStereoVolume(maxVol, maxVol) == AudioTrack.SUCCESS); + //-------- tear down -------------- + track.release(); + } + + //Test case 2: setStereoVolume() with min volume returns SUCCESS + @LargeTest + public void testSetStereoVolumeMin() throws Exception { + // constants for test + final String TEST_NAME = "testSetStereoVolumeMin"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + float minVol = AudioTrack.getMinVolume(); + assertTrue(TEST_NAME, track.setStereoVolume(minVol, minVol) == AudioTrack.SUCCESS); + //-------- tear down -------------- + track.release(); + } + + //Test case 3: setStereoVolume() with mid volume returns SUCCESS + @LargeTest + public void testSetStereoVolumeMid() throws Exception { + // constants for test + final String TEST_NAME = "testSetStereoVolumeMid"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + float midVol = (AudioTrack.getMaxVolume() - AudioTrack.getMinVolume()) / 2; + assertTrue(TEST_NAME, track.setStereoVolume(midVol, midVol) == AudioTrack.SUCCESS); + //-------- tear down -------------- + track.release(); + } + + //Test case 4: setPlaybackRate() with half the content rate returns SUCCESS + @LargeTest + public void testSetPlaybackRate() throws Exception { + // constants for test + final String TEST_NAME = "testSetPlaybackRate"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + track.write(data, 0, data.length); + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.play(); + assertTrue(TEST_NAME, track.setPlaybackRate((int)(TEST_SR/2)) == AudioTrack.SUCCESS); + //-------- tear down -------------- + track.release(); + } + + //Test case 5: setPlaybackRate(0) returns bad value error + @LargeTest + public void testSetPlaybackRateZero() throws Exception { + // constants for test + final String TEST_NAME = "testSetPlaybackRateZero"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, track.setPlaybackRate(0) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 6: setPlaybackRate() accepts values twice the output sample rate + @LargeTest + public void testSetPlaybackRateTwiceOutputSR() throws Exception { + // constants for test + final String TEST_NAME = "testSetPlaybackRateTwiceOutputSR"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + int outputSR = AudioTrack.getNativeOutputSampleRate(TEST_STREAM_TYPE); + //-------- test -------------- + track.write(data, 0, data.length); + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.play(); + assertTrue(TEST_NAME, track.setPlaybackRate(2*outputSR) == AudioTrack.SUCCESS); + //-------- tear down -------------- + track.release(); + } + + //Test case 7: setPlaybackRate() and retrieve value, should be the same for half the content SR + @LargeTest + public void testSetGetPlaybackRate() throws Exception { + // constants for test + final String TEST_NAME = "testSetGetPlaybackRate"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize/2]; + //-------- test -------------- + track.write(data, 0, data.length); + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.play(); + track.setPlaybackRate((int)(TEST_SR/2)); + assertTrue(TEST_NAME, track.getPlaybackRate() == (int)(TEST_SR/2)); + //-------- tear down -------------- + track.release(); + } + + //Test case 8: setPlaybackRate() invalid operation if track not initialized + @LargeTest + public void testSetPlaybackRateUninit() throws Exception { + // constants for test + final String TEST_NAME = "testSetPlaybackRateUninit"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STATIC; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_NO_STATIC_DATA); + assertTrue(TEST_NAME, + track.setPlaybackRate(TEST_SR/2) == AudioTrack.ERROR_INVALID_OPERATION); + //-------- tear down -------------- + track.release(); + } + + //----------------------------------------------------------------- + // Playback progress + //---------------------------------- + + //Test case 1: setPlaybackHeadPosition() on playing track + @LargeTest + public void testSetPlaybackHeadPositionPlaying() throws Exception { + // constants for test + final String TEST_NAME = "testSetPlaybackHeadPositionPlaying"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + assertTrue(TEST_NAME, + track.setPlaybackHeadPosition(10) == AudioTrack.ERROR_INVALID_OPERATION); + //-------- tear down -------------- + track.release(); + } + + //Test case 2: setPlaybackHeadPosition() on stopped track + @LargeTest + public void testSetPlaybackHeadPositionStopped() throws Exception { + // constants for test + final String TEST_NAME = "testSetPlaybackHeadPositionStopped"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + track.stop(); + assumeTrue(TEST_NAME, track.getPlayState() == AudioTrack.PLAYSTATE_STOPPED); + assertTrue(TEST_NAME, track.setPlaybackHeadPosition(10) == AudioTrack.SUCCESS); + //-------- tear down -------------- + track.release(); + } + + //Test case 3: setPlaybackHeadPosition() on paused track + @LargeTest + public void testSetPlaybackHeadPositionPaused() throws Exception { + // constants for test + final String TEST_NAME = "testSetPlaybackHeadPositionPaused"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + track.pause(); + assumeTrue(TEST_NAME, track.getPlayState() == AudioTrack.PLAYSTATE_PAUSED); + assertTrue(TEST_NAME, track.setPlaybackHeadPosition(10) == AudioTrack.SUCCESS); + //-------- tear down -------------- + track.release(); + } + + //Test case 4: setPlaybackHeadPosition() beyond what has been written + @LargeTest + public void testSetPlaybackHeadPositionTooFar() throws Exception { + // constants for test + final String TEST_NAME = "testSetPlaybackHeadPositionTooFar"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + // make up a frame index that's beyond what has been written: go from buffer size to frame + // count (given the audio track properties), and add 77. + int frameIndexTooFar = (2*minBuffSize/2) + 77; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + track.write(data, 0, data.length); + track.write(data, 0, data.length); + track.play(); + track.stop(); + assumeTrue(TEST_NAME, track.getPlayState() == AudioTrack.PLAYSTATE_STOPPED); + assertTrue(TEST_NAME, track.setPlaybackHeadPosition(frameIndexTooFar) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + + //Test case 5: setLoopPoints() fails for MODE_STREAM + @LargeTest + public void testSetLoopPointsStream() throws Exception { + // constants for test + final String TEST_NAME = "testSetLoopPointsStream"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, track.setLoopPoints(2, 50, 2) == AudioTrack.ERROR_INVALID_OPERATION); + //-------- tear down -------------- + track.release(); + } + + //Test case 6: setLoopPoints() fails start > end + @LargeTest + public void testSetLoopPointsStartAfterEnd() throws Exception { + // constants for test + final String TEST_NAME = "testSetLoopPointsStartAfterEnd"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STATIC; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, track.setLoopPoints(50, 0, 2) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 6: setLoopPoints() success + @LargeTest + public void testSetLoopPointsSuccess() throws Exception { + // constants for test + final String TEST_NAME = "testSetLoopPointsSuccess"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STATIC; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, track.setLoopPoints(0, 50, 2) == AudioTrack.SUCCESS); + //-------- tear down -------------- + track.release(); + } + + //Test case 7: setLoopPoints() fails with loop length bigger than content + @LargeTest + public void testSetLoopPointsLoopTooLong() throws Exception { + // constants for test + final String TEST_NAME = "testSetLoopPointsLoopTooLong"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STATIC; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + int dataSizeInFrames = minBuffSize/2; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_NO_STATIC_DATA); + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.setLoopPoints(10, dataSizeInFrames+20, 2) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + //Test case 8: setLoopPoints() fails with start beyond what can be written for the track + @LargeTest + public void testSetLoopPointsStartTooFar() throws Exception { + // constants for test + final String TEST_NAME = "testSetLoopPointsStartTooFar"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STATIC; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + int dataSizeInFrames = minBuffSize/2;//16bit data + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_NO_STATIC_DATA); + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.setLoopPoints(dataSizeInFrames+20, dataSizeInFrames+50, 2) + == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 9: setLoopPoints() fails with end beyond what can be written for the track + @LargeTest + public void testSetLoopPointsEndTooFar() throws Exception { + // constants for test + final String TEST_NAME = "testSetLoopPointsEndTooFar"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STATIC; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + int dataSizeInFrames = minBuffSize/2;//16bit data + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_NO_STATIC_DATA); + track.write(data, 0, data.length); + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.setLoopPoints(dataSizeInFrames-10, dataSizeInFrames+50, 2) + == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + + //----------------------------------------------------------------- + // Audio data supply + //---------------------------------- + + //Test case 1: write() fails when supplying less data (bytes) than declared + @LargeTest + public void testWriteByteOffsetTooBig() throws Exception { + // constants for test + final String TEST_NAME = "testWriteByteOffsetTooBig"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 10, data.length) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 2: write() fails when supplying less data (shorts) than declared + @LargeTest + public void testWriteShortOffsetTooBig() throws Exception { + // constants for test + final String TEST_NAME = "testWriteShortOffsetTooBig"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + short data[] = new short[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 10, data.length) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 3: write() fails when supplying less data (bytes) than declared + @LargeTest + public void testWriteByteSizeTooBig() throws Exception { + // constants for test + final String TEST_NAME = "testWriteByteSizeTooBig"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 0, data.length + 10) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 4: write() fails when supplying less data (shorts) than declared + @LargeTest + public void testWriteShortSizeTooBig() throws Exception { + // constants for test + final String TEST_NAME = "testWriteShortSizeTooBig"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + short data[] = new short[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 0, data.length + 10) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 5: write() fails with negative offset + @LargeTest + public void testWriteByteNegativeOffset() throws Exception { + // constants for test + final String TEST_NAME = "testWriteByteNegativeOffset"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, -10, data.length - 10) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 6: write() fails with negative offset + @LargeTest + public void testWriteShortNegativeOffset() throws Exception { + // constants for test + final String TEST_NAME = "testWriteShortNegativeOffset"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + short data[] = new short[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, -10, data.length - 10) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 7: write() fails with negative size + @LargeTest + public void testWriteByteNegativeSize() throws Exception { + // constants for test + final String TEST_NAME = "testWriteByteNegativeSize"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 0, -10) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 8: write() fails with negative size + @LargeTest + public void testWriteShortNegativeSize() throws Exception { + // constants for test + final String TEST_NAME = "testWriteShortNegativeSize"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + short data[] = new short[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 0, -10) == AudioTrack.ERROR_BAD_VALUE); + //-------- tear down -------------- + track.release(); + } + + //Test case 9: write() succeeds and returns the size that was written for 16bit + @LargeTest + public void testWriteByte() throws Exception { + // constants for test + final String TEST_NAME = "testWriteByte"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 0, data.length) == data.length); + //-------- tear down -------------- + track.release(); + } + + //Test case 10: write() succeeds and returns the size that was written for 16bit + @LargeTest + public void testWriteShort() throws Exception { + // constants for test + final String TEST_NAME = "testWriteShort"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + short data[] = new short[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 0, data.length) == data.length); + //-------- tear down -------------- + track.release(); + } + + //Test case 11: write() succeeds and returns the size that was written for 8bit + @LargeTest + public void testWriteByte8bit() throws Exception { + // constants for test + final String TEST_NAME = "testWriteByte8bit"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_8BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + byte data[] = new byte[minBuffSize]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 0, data.length) == data.length); + //-------- tear down -------------- + track.release(); + } + + //Test case 12: write() succeeds and returns the size that was written for 8bit + @LargeTest + public void testWriteShort8bit() throws Exception { + // constants for test + final String TEST_NAME = "testWriteShort8bit"; + final int TEST_SR = 22050; + final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO; + final int TEST_FORMAT = AudioFormat.ENCODING_PCM_8BIT; + final int TEST_MODE = AudioTrack.MODE_STREAM; + final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC; + + //-------- initialization -------------- + int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT); + AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT, + 2*minBuffSize, TEST_MODE); + short data[] = new short[minBuffSize/2]; + //-------- test -------------- + assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED); + assertTrue(TEST_NAME, + track.write(data, 0, data.length) == data.length); + //-------- tear down -------------- + track.release(); + } + +} + diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerApiTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerApiTest.java index 20f213ee9558d6206728234b582457d57e39dbd0..ee6a727dadb73fa969c5c6b1d617e6ea38b5cf96 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerApiTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerApiTest.java @@ -52,7 +52,8 @@ public class MediaPlayerApiTest extends ActivityInstrumentationTestCase { private String TAG = "MediaRecorderTest"; @@ -60,12 +59,48 @@ public class MediaRecorderTest extends ActivityInstrumentationTestCase { - - - private boolean mIsPlaying = true; - private String TAG = "MediaPlayerApiTest"; - Context mContext; - private SQLiteDatabase mDB; - - - public MediaPlayerPerformance() { - super("com.android.mediaframeworktest", MediaFrameworkTest.class); - } + * Junit / Instrumentation - performance measurement for media player and + * recorder + */ +public class MediaPlayerPerformance extends ActivityInstrumentationTestCase { + + private String TAG = "MediaFrameworkPerformance"; + + private SQLiteDatabase mDB; + private SurfaceHolder mSurfaceHolder = null; + private static final int NUM_STRESS_LOOP = 10; + private static final int NUM_PLAYBACk_IN_EACH_LOOP = 20; + private static final long MEDIA_STRESS_WAIT_TIME = 5000; //5 seconds + private static final String H263_VIDEO_PLAYBACK_MEMOUT = + "/sdcard/h263VideoPlaybackMemOut.txt"; + private static final String H264_VIDEO_PLAYBACK_MEMOUT = + "/sdcard/h264VideoPlaybackMemOut.txt"; + private static final String WMV_VIDEO_PLAYBACK_MEMOUT = + "/sdcard/WmvVideoPlaybackMemOut.txt"; + private static final String H263_VIDEO_ONLY_RECORD_MEMOUT = + "/sdcard/recordH263VideoOnlyMemOut.txt"; + private static final String MP4_VIDEO_ONLY_RECORD_MEMOUT = + "/sdcard/recordMPEG4VideoOnlyMemOut.txt"; + private static final String H263_VIDEO_AUDIO_RECORD_MEMOUT = + "/sdcard/recordVideoH263AudioMemOut.txt"; + private static final String AUDIO_ONLY_RECORD_MEMOUT = + "/sdcard/recordAudioOnlyMemOut.txt"; + + + public MediaPlayerPerformance() { + super("com.android.mediaframeworktest", MediaFrameworkTest.class); + } protected void setUp() throws Exception { - - super.setUp(); - } - - public void createDB(){ - mDB = SQLiteDatabase.openOrCreateDatabase("/sdcard/perf.db",null); - mDB.execSQL("CREATE TABLE perfdata (_id INTEGER PRIMARY KEY," - + "file TEXT," + "setdatatime LONG," +"preparetime LONG," +"playtime LONG" + ");"); - } - - public void audioPlaybackStartupTime(String[] testFile){ - long t1 = 0; - long t2 = 0; - long t3 = 0; - long t4 =0; - - long setDataSourceDuration = 0; - long prepareDuration = 0; - long startDuration=0; - - long totalSetDataTime=0; - long totalPrepareTime=0; - long totalStartDuration=0; - - int numberOfFiles = testFile.length; - Log.v(TAG, "File lenght " + numberOfFiles); - for (int k=0; k { + + + private String TAG = "MediaRecorderStressTest"; + private MediaRecorder mRecorder; + private Camera mCamera; + + private static final int NUMBER_OF_CAMERA_STRESS_LOOPS = 100; + private static final int NUMBER_OF_RECORDER_STRESS_LOOPS = 100; + private static final int NUMBER_OF_RECORDERANDPLAY_STRESS_LOOPS = 50; + private static final int NUMBER_OF_SWTICHING_LOOPS_BW_CAMERA_AND_RECORDER = 200; + private static final long WAIT_TIME_CAMERA_TEST = 3000; // 3 second + private static final long WAIT_TIME_RECORDER_TEST = 60000; // 6 second + private static final long WAIT_TIME_RECORD = 100000; // 10 seconds + private static final long WAIT_TIME_PLAYBACK = 60000; // 6 second + private static final String OUTPUT_FILE = "/sdcard/temp"; + private static final String OUTPUT_FILE_EXT = ".3gp"; + + public MediaRecorderStressTest() { + super("com.android.mediaframeworktest", MediaFrameworkTest.class); + } + + protected void setUp() throws Exception { + getActivity(); + super.setUp(); + } + + //Test case for stressing the camera preview. + @LargeTest + public void testStressCamera() throws Exception { + SurfaceHolder mSurfaceHolder; + mSurfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder(); + try { + Log.v(TAG, "Start preview"); + for (int i = 0; i< NUMBER_OF_CAMERA_STRESS_LOOPS; i++){ + mCamera = Camera.open(); + mCamera.setPreviewDisplay(mSurfaceHolder); + mCamera.startPreview(); + Thread.sleep(WAIT_TIME_CAMERA_TEST); + mCamera.stopPreview(); + mCamera.release(); + } + } catch (Exception e) { + Log.v(TAG, e.toString()); + } + } + + //Test case for stressing the camera preview. + @LargeTest + public void testStressRecorder() throws Exception { + String filename; + SurfaceHolder mSurfaceHolder; + mSurfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder(); + try { + Log.v(TAG, "Start preview"); + for (int i = 0; i < NUMBER_OF_RECORDER_STRESS_LOOPS; i++){ + Log.v(TAG, "counter = " + i); + filename = OUTPUT_FILE + i + OUTPUT_FILE_EXT; + Log.v(TAG, filename); + mRecorder = new MediaRecorder(); + mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); + mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); + mRecorder.setOutputFile(filename); + mRecorder.setVideoFrameRate(20); + mRecorder.setVideoSize(176,144); + Log.v(TAG, "setEncoder"); + mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); + mSurfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder(); + Log.v(TAG, "setPreview"); + mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); + Log.v(TAG, "prepare"); + mRecorder.prepare(); + Log.v(TAG, "before release"); + Thread.sleep(WAIT_TIME_RECORDER_TEST); + mRecorder.reset(); + mRecorder.release(); + } + } catch (Exception e) { + Log.v(TAG, e.toString()); + } + } + + + //Stress test case for switching camera and video recorder preview. + @LargeTest + public void testStressCameraSwitchRecorder() throws Exception { + String filename; + SurfaceHolder mSurfaceHolder; + mSurfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder(); + try { + Log.v(TAG, "Start preview"); + for (int i = 0; i < NUMBER_OF_SWTICHING_LOOPS_BW_CAMERA_AND_RECORDER; i++){ + mCamera = Camera.open(); + mCamera.setPreviewDisplay(mSurfaceHolder); + mCamera.startPreview(); + Thread.sleep(WAIT_TIME_CAMERA_TEST); + mCamera.stopPreview(); + mCamera.release(); + mCamera = null; + Log.v(TAG, "release camera"); + filename = OUTPUT_FILE + i + OUTPUT_FILE_EXT; + Log.v(TAG, filename); + mRecorder = new MediaRecorder(); + mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); + mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); + mRecorder.setOutputFile(filename); + mRecorder.setVideoFrameRate(20); + mRecorder.setVideoSize(176,144); + Log.v(TAG, "Media recorder setEncoder"); + mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); + Log.v(TAG, "mediaRecorder setPreview"); + mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); + Log.v(TAG, "prepare"); + mRecorder.prepare(); + Log.v(TAG, "before release"); + Thread.sleep(WAIT_TIME_CAMERA_TEST); + mRecorder.release(); + Log.v(TAG, "release video recorder"); + } + } catch (Exception e) { + Log.v(TAG, e.toString()); + } + } + + //Stress test case for record a video and play right away. + @LargeTest + public void testStressRecordVideoAndPlayback() throws Exception { + String filename; + SurfaceHolder mSurfaceHolder; + mSurfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder(); + try { + for (int i = 0; i < NUMBER_OF_RECORDERANDPLAY_STRESS_LOOPS; i++){ + filename = OUTPUT_FILE + i + OUTPUT_FILE_EXT; + Log.v(TAG, filename); + mRecorder = new MediaRecorder(); + mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); + mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); + mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); + mRecorder.setOutputFile(filename); + mRecorder.setVideoFrameRate(20); + mRecorder.setVideoSize(352,288); + mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); + mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); + Log.v(TAG, "mediaRecorder setPreview"); + mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); + mRecorder.prepare(); + mRecorder.start(); + Thread.sleep(WAIT_TIME_RECORD); + Log.v(TAG, "Before stop"); + mRecorder.stop(); + mRecorder.release(); + //start the playback + MediaPlayer mp = new MediaPlayer(); + mp.setDataSource(filename); + mp.setDisplay(MediaFrameworkTest.mSurfaceView.getHolder()); + mp.prepare(); + mp.start(); + Thread.sleep(WAIT_TIME_PLAYBACK); + mp.release(); + } + } catch (Exception e) { + Log.v(TAG, e.toString()); + } + } +} + diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaMetadataRetrieverTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaMetadataRetrieverTest.java index 61a8a296d31841cf928ee731b09d4338adca28e1..4fa673509fbb7dc373ceb559052aec24155d927f 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaMetadataRetrieverTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaMetadataRetrieverTest.java @@ -22,7 +22,8 @@ import android.graphics.Bitmap; import java.io.FileOutputStream; import android.test.AndroidTestCase; import com.android.mediaframeworktest.MediaNames; -import android.test.suitebuilder.annotation.*; +import android.test.suitebuilder.annotation.LargeTest; +import android.test.suitebuilder.annotation.Suppress; /** * WARNING: @@ -34,7 +35,7 @@ public class MediaMetadataRetrieverTest extends AndroidTestCase { private static final String TAG = "MediaMetadataRetrieverTest"; // Test album art extraction. - @MediumTest + @LargeTest public static void testAlbumArt() throws Exception { Log.v(TAG, "testAlbumArt starts."); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); @@ -108,7 +109,7 @@ public class MediaMetadataRetrieverTest extends AndroidTestCase { // If the specified call order and valid media file is used, no exception // should be thrown. - @MediumTest + @LargeTest public static void testBasicNormalMethodCallSequence() throws Exception { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY); @@ -135,7 +136,7 @@ public class MediaMetadataRetrieverTest extends AndroidTestCase { // If setDataSource() has not been called, both captureFrame() and extractMetadata() must // return null. - @MediumTest + @LargeTest public static void testBasicAbnormalMethodCallSequence() { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY); @@ -144,7 +145,7 @@ public class MediaMetadataRetrieverTest extends AndroidTestCase { } // Test setDataSource() - @MediumTest + @LargeTest public static void testSetDataSource() { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY); @@ -189,7 +190,7 @@ public class MediaMetadataRetrieverTest extends AndroidTestCase { // Due to the lack of permission to access hardware decoder, any calls // attempting to capture a frame will fail. These are commented out for now // until we find a solution to this access permission problem. - @MediumTest + @LargeTest public static void testIntendedUsage() { // By default, capture frame and retrieve metadata MediaMetadataRetriever retriever = new MediaMetadataRetriever(); diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderPrepareStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderPrepareStateUnitTest.java index 366b6ffce7a1bc59771338d704d674ae8d01d18b..bde000bac6a162126a2494bd20ca4694e003c0c1 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderPrepareStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderPrepareStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaRecorder; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; import java.io.IOException; @@ -55,14 +55,11 @@ public class MediaRecorderPrepareStateUnitTest extends AndroidTestCase implement try { recorder.prepare(); } catch (IOException exception) { - fail("recorder.prepare() failed"); + throw new RuntimeException(); } } - //TODO(elaurent) - //reactivate the test until bug#1495237 fix - @Suppress - @MediumTest + @LargeTest public void testPrepare() { mTestTemplate.runTestOnMethod(this); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderResetStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderResetStateUnitTest.java index a45f7baa2e47f2c4b9bc28adafe774781d4628fe..80532c35184fdd4afdf46567c2168dc6c5e403ae 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderResetStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderResetStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaRecorder; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; /** @@ -54,10 +54,7 @@ public class MediaRecorderResetStateUnitTest extends AndroidTestCase implements recorder.reset(); } - //TODO(elaurent) - //reactivate the test until bug#1495237 fix - @Suppress - @MediumTest + @LargeTest public void testReset() { mTestTemplate.runTestOnMethod(this); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetAudioEncoderStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetAudioEncoderStateUnitTest.java index f17d017d8325fadb15250fab97ca4d0a658eca44..e387a77fd71cefe64d58b93b0a319cec2dc1e374 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetAudioEncoderStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetAudioEncoderStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaRecorder; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; /** @@ -54,10 +54,7 @@ public class MediaRecorderSetAudioEncoderStateUnitTest extends AndroidTestCase i recorder.setAudioEncoder(MediaRecorderStateUnitTestTemplate.AUDIO_ENCODER); } - //TODO(elaurent) - //reactivate the test until bug#1495237 fix - @Suppress - @MediumTest + @LargeTest public void testSetAudioEncoder() { mTestTemplate.runTestOnMethod(this); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetAudioSourceStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetAudioSourceStateUnitTest.java index a972daeae4520956caa5530639d59333206ae81d..60af54c53af8c0395b64cb533499f515d000c408 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetAudioSourceStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetAudioSourceStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaRecorder; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; /** @@ -54,10 +54,7 @@ public class MediaRecorderSetAudioSourceStateUnitTest extends AndroidTestCase im recorder.setAudioSource(MediaRecorderStateUnitTestTemplate.AUDIO_SOURCE); } - //TODO(elaurent) - //reactivate the test until bug#1495237 fix - @Suppress - @MediumTest + @LargeTest public void testSetAudioSource() { mTestTemplate.runTestOnMethod(this); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetOutputFileStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetOutputFileStateUnitTest.java index b5e7bb79d6403c7c728f37d97b93cefd83853502..37d97e9d2c2e53a14704607b1aceeaa44506ac15 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetOutputFileStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetOutputFileStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaRecorder; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; /** @@ -29,34 +29,29 @@ public class MediaRecorderSetOutputFileStateUnitTest extends AndroidTestCase imp private MediaRecorderStateUnitTestTemplate mTestTemplate = new MediaRecorderStateUnitTestTemplate(); /** * 1. It is valid to call setOutputFile() in the following states: - * {DataSourceConfigured}. + * {DataSourceConfigured, Initial, Initialized, Prepared, Recording, Error}. * 2. It is invalid to call setOutputFile() in the following states: - * {Initial, Initialized, Prepared, Recording, Error} + * {} * * @param stateErrors the MediaRecorderStateErrors to check against. */ public void checkStateErrors(MediaRecorderStateErrors stateErrors) { // Valid states. assertTrue(!stateErrors.errorInDataSourceConfiguredState); - - // Invalid states. - assertTrue(stateErrors.errorInPreparedState); - assertTrue(stateErrors.errorInRecordingState); - assertTrue(stateErrors.errorInErrorState); - assertTrue(stateErrors.errorInInitialState); - assertTrue(stateErrors.errorInInitialStateAfterReset); - assertTrue(stateErrors.errorInInitialStateAfterStop); - assertTrue(stateErrors.errorInInitializedState); + assertTrue(!stateErrors.errorInPreparedState); + assertTrue(!stateErrors.errorInRecordingState); + assertTrue(!stateErrors.errorInErrorState); + assertTrue(!stateErrors.errorInInitialState); + assertTrue(!stateErrors.errorInInitialStateAfterReset); + assertTrue(!stateErrors.errorInInitialStateAfterStop); + assertTrue(!stateErrors.errorInInitializedState); } public void invokeMethodUnderTest(MediaRecorder recorder) { recorder.setOutputFile(MediaRecorderStateUnitTestTemplate.RECORD_OUTPUT_PATH); } - //TODO(elaurent) - //reactivate the test until bug#1495237 fix - @Suppress - @MediumTest + @LargeTest public void testSetOutputFile() { mTestTemplate.runTestOnMethod(this); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetOutputFormatStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetOutputFormatStateUnitTest.java index 3d6f87fa692309565e8c2dbfecfe9c7a8893492a..a7ee2d4473a6249df096f35e4f5fb2bf4011d8ff 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetOutputFormatStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderSetOutputFormatStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaRecorder; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; /** @@ -54,10 +54,7 @@ public class MediaRecorderSetOutputFormatStateUnitTest extends AndroidTestCase i recorder.setOutputFormat(MediaRecorderStateUnitTestTemplate.OUTPUT_FORMAT); } - //TODO(elaurent) - //reactivate the test until bug#1495237 fix - @Suppress - @MediumTest + @LargeTest public void testSetOutputFormat() { mTestTemplate.runTestOnMethod(this); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStartStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStartStateUnitTest.java index 03180d56b3df5270807a7b939053965fdb116217..4af596756a828e9a8e399f36fa0a0fce7e2eab33 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStartStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStartStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaRecorder; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; /** @@ -54,10 +54,7 @@ public class MediaRecorderStartStateUnitTest extends AndroidTestCase implements recorder.start(); } - //TODO(elaurent) - //reactivate the test until bug#1495237 fix - @Suppress - @MediumTest + @LargeTest public void testStart() { mTestTemplate.runTestOnMethod(this); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStateUnitTestTemplate.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStateUnitTestTemplate.java index f350467cf380bddbc37dfb5318bb4271c040223f..9edc9aa2b861fa9433690df6b2c963b81d2b0d81 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStateUnitTestTemplate.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStateUnitTestTemplate.java @@ -90,9 +90,15 @@ class MediaRecorderStateUnitTestTemplate extends AndroidTestCase { } } + // FIXME: + // In the past, stop() == reset(). + // However, this is no longer true. The plan is to have a STOPPED state. + // and from STOPPED state, start can be called without the need to + // do the recording configuration again. private void setMediaRecorderToInitialStateAfterStop() { try { mMediaRecorder.reset(); +/* mMediaRecorder.setAudioSource(AUDIO_SOURCE); mMediaRecorder.setOutputFormat(OUTPUT_FORMAT); mMediaRecorder.setAudioEncoder(AUDIO_ENCODER); @@ -100,6 +106,7 @@ class MediaRecorderStateUnitTestTemplate extends AndroidTestCase { mMediaRecorder.prepare(); mMediaRecorder.start(); mMediaRecorder.stop(); +*/ } catch(Exception e) { fail("setMediaRecorderToInitialStateAfterReset: Exception " + e.getClass().getName() + " was thrown."); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStopStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStopStateUnitTest.java index 330e8abeb3f3ad597704c2c478abc75b92f8155a..5475900e341ee3602d906d52443524da372aeb57 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStopStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaRecorderStopStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaRecorder; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; /** @@ -54,10 +54,7 @@ public class MediaRecorderStopStateUnitTest extends AndroidTestCase implements M recorder.stop(); } - //TODO(elaurent) - //reactivate the test until bug#1495237 fix - @Suppress - @MediumTest + @LargeTest public void testStop() { mTestTemplate.runTestOnMethod(this); } diff --git a/opengl/include/EGL/egl.h b/opengl/include/EGL/egl.h new file mode 100644 index 0000000000000000000000000000000000000000..c269976f4ad31a35a8855aaa8969d2d87f9fd794 --- /dev/null +++ b/opengl/include/EGL/egl.h @@ -0,0 +1,330 @@ +/* -*- mode: c; tab-width: 8; -*- */ +/* vi: set sw=4 ts=8: */ +/* Reference version of egl.h for EGL 1.4. + * $Revision: 7244 $ on $Date: 2009-01-20 17:06:59 -0800 (Tue, 20 Jan 2009) $ + */ + +/* +** Copyright (c) 2007-2009 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +#ifndef __egl_h_ +#define __egl_h_ + +/* All platform-dependent types and macro boilerplate (such as EGLAPI + * and EGLAPIENTRY) should go in eglplatform.h. + */ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* EGL Types */ +/* EGLint is defined in eglplatform.h */ +typedef unsigned int EGLBoolean; +typedef unsigned int EGLenum; +typedef void *EGLConfig; +typedef void *EGLContext; +typedef void *EGLDisplay; +typedef void *EGLSurface; +typedef void *EGLClientBuffer; + +/* EGL Versioning */ +#define EGL_VERSION_1_0 1 +#define EGL_VERSION_1_1 1 +#define EGL_VERSION_1_2 1 +#define EGL_VERSION_1_3 1 +#define EGL_VERSION_1_4 1 + +/* EGL Enumerants. Bitmasks and other exceptional cases aside, most + * enums are assigned unique values starting at 0x3000. + */ + +/* EGL aliases */ +#define EGL_FALSE 0 +#define EGL_TRUE 1 + +/* Out-of-band handle values */ +#define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0) +#define EGL_NO_CONTEXT ((EGLContext)0) +#define EGL_NO_DISPLAY ((EGLDisplay)0) +#define EGL_NO_SURFACE ((EGLSurface)0) + +/* Out-of-band attribute value */ +#define EGL_DONT_CARE ((EGLint)-1) + +/* Errors / GetError return values */ +#define EGL_SUCCESS 0x3000 +#define EGL_NOT_INITIALIZED 0x3001 +#define EGL_BAD_ACCESS 0x3002 +#define EGL_BAD_ALLOC 0x3003 +#define EGL_BAD_ATTRIBUTE 0x3004 +#define EGL_BAD_CONFIG 0x3005 +#define EGL_BAD_CONTEXT 0x3006 +#define EGL_BAD_CURRENT_SURFACE 0x3007 +#define EGL_BAD_DISPLAY 0x3008 +#define EGL_BAD_MATCH 0x3009 +#define EGL_BAD_NATIVE_PIXMAP 0x300A +#define EGL_BAD_NATIVE_WINDOW 0x300B +#define EGL_BAD_PARAMETER 0x300C +#define EGL_BAD_SURFACE 0x300D +#define EGL_CONTEXT_LOST 0x300E /* EGL 1.1 - IMG_power_management */ + +/* Reserved 0x300F-0x301F for additional errors */ + +/* Config attributes */ +#define EGL_BUFFER_SIZE 0x3020 +#define EGL_ALPHA_SIZE 0x3021 +#define EGL_BLUE_SIZE 0x3022 +#define EGL_GREEN_SIZE 0x3023 +#define EGL_RED_SIZE 0x3024 +#define EGL_DEPTH_SIZE 0x3025 +#define EGL_STENCIL_SIZE 0x3026 +#define EGL_CONFIG_CAVEAT 0x3027 +#define EGL_CONFIG_ID 0x3028 +#define EGL_LEVEL 0x3029 +#define EGL_MAX_PBUFFER_HEIGHT 0x302A +#define EGL_MAX_PBUFFER_PIXELS 0x302B +#define EGL_MAX_PBUFFER_WIDTH 0x302C +#define EGL_NATIVE_RENDERABLE 0x302D +#define EGL_NATIVE_VISUAL_ID 0x302E +#define EGL_NATIVE_VISUAL_TYPE 0x302F +#define EGL_PRESERVED_RESOURCES 0x3030 +#define EGL_SAMPLES 0x3031 +#define EGL_SAMPLE_BUFFERS 0x3032 +#define EGL_SURFACE_TYPE 0x3033 +#define EGL_TRANSPARENT_TYPE 0x3034 +#define EGL_TRANSPARENT_BLUE_VALUE 0x3035 +#define EGL_TRANSPARENT_GREEN_VALUE 0x3036 +#define EGL_TRANSPARENT_RED_VALUE 0x3037 +#define EGL_NONE 0x3038 /* Attrib list terminator */ +#define EGL_BIND_TO_TEXTURE_RGB 0x3039 +#define EGL_BIND_TO_TEXTURE_RGBA 0x303A +#define EGL_MIN_SWAP_INTERVAL 0x303B +#define EGL_MAX_SWAP_INTERVAL 0x303C +#define EGL_LUMINANCE_SIZE 0x303D +#define EGL_ALPHA_MASK_SIZE 0x303E +#define EGL_COLOR_BUFFER_TYPE 0x303F +#define EGL_RENDERABLE_TYPE 0x3040 +#define EGL_MATCH_NATIVE_PIXMAP 0x3041 /* Pseudo-attribute (not queryable) */ +#define EGL_CONFORMANT 0x3042 + +/* Reserved 0x3041-0x304F for additional config attributes */ + +/* Config attribute values */ +#define EGL_SLOW_CONFIG 0x3050 /* EGL_CONFIG_CAVEAT value */ +#define EGL_NON_CONFORMANT_CONFIG 0x3051 /* EGL_CONFIG_CAVEAT value */ +#define EGL_TRANSPARENT_RGB 0x3052 /* EGL_TRANSPARENT_TYPE value */ +#define EGL_RGB_BUFFER 0x308E /* EGL_COLOR_BUFFER_TYPE value */ +#define EGL_LUMINANCE_BUFFER 0x308F /* EGL_COLOR_BUFFER_TYPE value */ + +/* More config attribute values, for EGL_TEXTURE_FORMAT */ +#define EGL_NO_TEXTURE 0x305C +#define EGL_TEXTURE_RGB 0x305D +#define EGL_TEXTURE_RGBA 0x305E +#define EGL_TEXTURE_2D 0x305F + +/* Config attribute mask bits */ +#define EGL_PBUFFER_BIT 0x0001 /* EGL_SURFACE_TYPE mask bits */ +#define EGL_PIXMAP_BIT 0x0002 /* EGL_SURFACE_TYPE mask bits */ +#define EGL_WINDOW_BIT 0x0004 /* EGL_SURFACE_TYPE mask bits */ +#define EGL_VG_COLORSPACE_LINEAR_BIT 0x0020 /* EGL_SURFACE_TYPE mask bits */ +#define EGL_VG_ALPHA_FORMAT_PRE_BIT 0x0040 /* EGL_SURFACE_TYPE mask bits */ +#define EGL_MULTISAMPLE_RESOLVE_BOX_BIT 0x0200 /* EGL_SURFACE_TYPE mask bits */ +#define EGL_SWAP_BEHAVIOR_PRESERVED_BIT 0x0400 /* EGL_SURFACE_TYPE mask bits */ + +#define EGL_OPENGL_ES_BIT 0x0001 /* EGL_RENDERABLE_TYPE mask bits */ +#define EGL_OPENVG_BIT 0x0002 /* EGL_RENDERABLE_TYPE mask bits */ +#define EGL_OPENGL_ES2_BIT 0x0004 /* EGL_RENDERABLE_TYPE mask bits */ +#define EGL_OPENGL_BIT 0x0008 /* EGL_RENDERABLE_TYPE mask bits */ + +/* QueryString targets */ +#define EGL_VENDOR 0x3053 +#define EGL_VERSION 0x3054 +#define EGL_EXTENSIONS 0x3055 +#define EGL_CLIENT_APIS 0x308D + +/* QuerySurface / SurfaceAttrib / CreatePbufferSurface targets */ +#define EGL_HEIGHT 0x3056 +#define EGL_WIDTH 0x3057 +#define EGL_LARGEST_PBUFFER 0x3058 +#define EGL_TEXTURE_FORMAT 0x3080 +#define EGL_TEXTURE_TARGET 0x3081 +#define EGL_MIPMAP_TEXTURE 0x3082 +#define EGL_MIPMAP_LEVEL 0x3083 +#define EGL_RENDER_BUFFER 0x3086 +#define EGL_VG_COLORSPACE 0x3087 +#define EGL_VG_ALPHA_FORMAT 0x3088 +#define EGL_HORIZONTAL_RESOLUTION 0x3090 +#define EGL_VERTICAL_RESOLUTION 0x3091 +#define EGL_PIXEL_ASPECT_RATIO 0x3092 +#define EGL_SWAP_BEHAVIOR 0x3093 +#define EGL_MULTISAMPLE_RESOLVE 0x3099 + +/* EGL_RENDER_BUFFER values / BindTexImage / ReleaseTexImage buffer targets */ +#define EGL_BACK_BUFFER 0x3084 +#define EGL_SINGLE_BUFFER 0x3085 + +/* OpenVG color spaces */ +#define EGL_VG_COLORSPACE_sRGB 0x3089 /* EGL_VG_COLORSPACE value */ +#define EGL_VG_COLORSPACE_LINEAR 0x308A /* EGL_VG_COLORSPACE value */ + +/* OpenVG alpha formats */ +#define EGL_VG_ALPHA_FORMAT_NONPRE 0x308B /* EGL_ALPHA_FORMAT value */ +#define EGL_VG_ALPHA_FORMAT_PRE 0x308C /* EGL_ALPHA_FORMAT value */ + +/* Constant scale factor by which fractional display resolutions & + * aspect ratio are scaled when queried as integer values. + */ +#define EGL_DISPLAY_SCALING 10000 + +/* Unknown display resolution/aspect ratio */ +#define EGL_UNKNOWN ((EGLint)-1) + +/* Back buffer swap behaviors */ +#define EGL_BUFFER_PRESERVED 0x3094 /* EGL_SWAP_BEHAVIOR value */ +#define EGL_BUFFER_DESTROYED 0x3095 /* EGL_SWAP_BEHAVIOR value */ + +/* CreatePbufferFromClientBuffer buffer types */ +#define EGL_OPENVG_IMAGE 0x3096 + +/* QueryContext targets */ +#define EGL_CONTEXT_CLIENT_TYPE 0x3097 + +/* CreateContext attributes */ +#define EGL_CONTEXT_CLIENT_VERSION 0x3098 + +/* Multisample resolution behaviors */ +#define EGL_MULTISAMPLE_RESOLVE_DEFAULT 0x309A /* EGL_MULTISAMPLE_RESOLVE value */ +#define EGL_MULTISAMPLE_RESOLVE_BOX 0x309B /* EGL_MULTISAMPLE_RESOLVE value */ + +/* BindAPI/QueryAPI targets */ +#define EGL_OPENGL_ES_API 0x30A0 +#define EGL_OPENVG_API 0x30A1 +#define EGL_OPENGL_API 0x30A2 + +/* GetCurrentSurface targets */ +#define EGL_DRAW 0x3059 +#define EGL_READ 0x305A + +/* WaitNative engines */ +#define EGL_CORE_NATIVE_ENGINE 0x305B + +/* EGL 1.2 tokens renamed for consistency in EGL 1.3 */ +#define EGL_COLORSPACE EGL_VG_COLORSPACE +#define EGL_ALPHA_FORMAT EGL_VG_ALPHA_FORMAT +#define EGL_COLORSPACE_sRGB EGL_VG_COLORSPACE_sRGB +#define EGL_COLORSPACE_LINEAR EGL_VG_COLORSPACE_LINEAR +#define EGL_ALPHA_FORMAT_NONPRE EGL_VG_ALPHA_FORMAT_NONPRE +#define EGL_ALPHA_FORMAT_PRE EGL_VG_ALPHA_FORMAT_PRE + +/* EGL extensions must request enum blocks from the Khronos + * API Registrar, who maintains the enumerant registry. Submit + * a bug in Khronos Bugzilla against task "Registry". + */ + + + +/* EGL Functions */ + +EGLAPI EGLint EGLAPIENTRY eglGetError(void); + +EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id); +EGLAPI EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor); +EGLAPI EGLBoolean EGLAPIENTRY eglTerminate(EGLDisplay dpy); + +EGLAPI const char * EGLAPIENTRY eglQueryString(EGLDisplay dpy, EGLint name); + +EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs(EGLDisplay dpy, EGLConfig *configs, + EGLint config_size, EGLint *num_config); +EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, + EGLConfig *configs, EGLint config_size, + EGLint *num_config); +EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, + EGLint attribute, EGLint *value); + +EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, + EGLNativeWindowType win, + const EGLint *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, + const EGLint *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, + EGLNativePixmapType pixmap, + const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface(EGLDisplay dpy, EGLSurface surface); +EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface(EGLDisplay dpy, EGLSurface surface, + EGLint attribute, EGLint *value); + +EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI(EGLenum api); +EGLAPI EGLenum EGLAPIENTRY eglQueryAPI(void); + +EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient(void); + +EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread(void); + +EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer( + EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, + EGLConfig config, const EGLint *attrib_list); + +EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, + EGLint attribute, EGLint value); +EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer); +EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer); + + +EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval(EGLDisplay dpy, EGLint interval); + + +EGLAPI EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig config, + EGLContext share_context, + const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext(EGLDisplay dpy, EGLContext ctx); +EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, + EGLSurface read, EGLContext ctx); + +EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext(void); +EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface(EGLint readdraw); +EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay(void); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext(EGLDisplay dpy, EGLContext ctx, + EGLint attribute, EGLint *value); + +EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL(void); +EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative(EGLint engine); +EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface surface); +EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, + EGLNativePixmapType target); + +/* This is a generic function pointer type, whose name indicates it must + * be cast to the proper type *and calling convention* before use. + */ +typedef void (*__eglMustCastToProperFunctionPointerType)(void); + +/* Now, define eglGetProcAddress using the generic function ptr. type */ +EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY + eglGetProcAddress(const char *procname); + +#ifdef __cplusplus +} +#endif + +#endif /* __egl_h_ */ diff --git a/opengl/include/EGL/eglext.h b/opengl/include/EGL/eglext.h new file mode 100644 index 0000000000000000000000000000000000000000..25cfcb832fb2920ec976240c705c36702f385b24 --- /dev/null +++ b/opengl/include/EGL/eglext.h @@ -0,0 +1,138 @@ +#ifndef __eglext_h_ +#define __eglext_h_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright (c) 2007-2009 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +#include + +/*************************************************************/ + +/* Header file version number */ +/* Current version at http://www.khronos.org/registry/egl/ */ +/* $Revision: 7244 $ on $Date: 2009-01-20 17:06:59 -0800 (Tue, 20 Jan 2009) $ */ +#define EGL_EGLEXT_VERSION 3 + +#ifndef EGL_KHR_config_attribs +#define EGL_KHR_config_attribs 1 +#define EGL_CONFORMANT_KHR 0x3042 /* EGLConfig attribute */ +#define EGL_VG_COLORSPACE_LINEAR_BIT_KHR 0x0020 /* EGL_SURFACE_TYPE bitfield */ +#define EGL_VG_ALPHA_FORMAT_PRE_BIT_KHR 0x0040 /* EGL_SURFACE_TYPE bitfield */ +#endif + +#ifndef EGL_KHR_lock_surface +#define EGL_KHR_lock_surface 1 +#define EGL_READ_SURFACE_BIT_KHR 0x0001 /* EGL_LOCK_USAGE_HINT_KHR bitfield */ +#define EGL_WRITE_SURFACE_BIT_KHR 0x0002 /* EGL_LOCK_USAGE_HINT_KHR bitfield */ +#define EGL_LOCK_SURFACE_BIT_KHR 0x0080 /* EGL_SURFACE_TYPE bitfield */ +#define EGL_OPTIMAL_FORMAT_BIT_KHR 0x0100 /* EGL_SURFACE_TYPE bitfield */ +#define EGL_MATCH_FORMAT_KHR 0x3043 /* EGLConfig attribute */ +#define EGL_FORMAT_RGB_565_EXACT_KHR 0x30C0 /* EGL_MATCH_FORMAT_KHR value */ +#define EGL_FORMAT_RGB_565_KHR 0x30C1 /* EGL_MATCH_FORMAT_KHR value */ +#define EGL_FORMAT_RGBA_8888_EXACT_KHR 0x30C2 /* EGL_MATCH_FORMAT_KHR value */ +#define EGL_FORMAT_RGBA_8888_KHR 0x30C3 /* EGL_MATCH_FORMAT_KHR value */ +#define EGL_MAP_PRESERVE_PIXELS_KHR 0x30C4 /* eglLockSurfaceKHR attribute */ +#define EGL_LOCK_USAGE_HINT_KHR 0x30C5 /* eglLockSurfaceKHR attribute */ +#define EGL_BITMAP_POINTER_KHR 0x30C6 /* eglQuerySurface attribute */ +#define EGL_BITMAP_PITCH_KHR 0x30C7 /* eglQuerySurface attribute */ +#define EGL_BITMAP_ORIGIN_KHR 0x30C8 /* eglQuerySurface attribute */ +#define EGL_BITMAP_PIXEL_RED_OFFSET_KHR 0x30C9 /* eglQuerySurface attribute */ +#define EGL_BITMAP_PIXEL_GREEN_OFFSET_KHR 0x30CA /* eglQuerySurface attribute */ +#define EGL_BITMAP_PIXEL_BLUE_OFFSET_KHR 0x30CB /* eglQuerySurface attribute */ +#define EGL_BITMAP_PIXEL_ALPHA_OFFSET_KHR 0x30CC /* eglQuerySurface attribute */ +#define EGL_BITMAP_PIXEL_LUMINANCE_OFFSET_KHR 0x30CD /* eglQuerySurface attribute */ +#define EGL_LOWER_LEFT_KHR 0x30CE /* EGL_BITMAP_ORIGIN_KHR value */ +#define EGL_UPPER_LEFT_KHR 0x30CF /* EGL_BITMAP_ORIGIN_KHR value */ +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglLockSurfaceKHR (EGLDisplay display, EGLSurface surface, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglUnlockSurfaceKHR (EGLDisplay display, EGLSurface surface); +#endif /* EGL_EGLEXT_PROTOTYPES */ +typedef EGLBoolean (EGLAPIENTRYP PFNEGLLOCKSURFACEKHRPROC) (EGLDisplay display, EGLSurface surface, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNLOCKSURFACEKHRPROC) (EGLDisplay display, EGLSurface surface); +#endif + +#ifndef EGL_KHR_image +#define EGL_KHR_image 1 +#define EGL_NATIVE_PIXMAP_KHR 0x30B0 /* eglCreateImageKHR target */ +typedef void *EGLImageKHR; +#define EGL_NO_IMAGE_KHR ((EGLImageKHR)0) +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR (EGLDisplay dpy, EGLImageKHR image); +#endif /* EGL_EGLEXT_PROTOTYPES */ +typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image); +#endif + +#ifndef EGL_KHR_vg_parent_image +#define EGL_KHR_vg_parent_image 1 +#define EGL_VG_PARENT_IMAGE_KHR 0x30BA /* eglCreateImageKHR target */ +#endif + +#ifndef EGL_KHR_gl_texture_2D_image +#define EGL_KHR_gl_texture_2D_image 1 +#define EGL_GL_TEXTURE_2D_KHR 0x30B1 /* eglCreateImageKHR target */ +#define EGL_GL_TEXTURE_LEVEL_KHR 0x30BC /* eglCreateImageKHR attribute */ +#endif + +#ifndef EGL_KHR_gl_texture_cubemap_image +#define EGL_KHR_gl_texture_cubemap_image 1 +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR 0x30B3 /* eglCreateImageKHR target */ +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR 0x30B4 /* eglCreateImageKHR target */ +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR 0x30B5 /* eglCreateImageKHR target */ +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR 0x30B6 /* eglCreateImageKHR target */ +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR 0x30B7 /* eglCreateImageKHR target */ +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR 0x30B8 /* eglCreateImageKHR target */ +#endif + +#ifndef EGL_KHR_gl_texture_3D_image +#define EGL_KHR_gl_texture_3D_image 1 +#define EGL_GL_TEXTURE_3D_KHR 0x30B2 /* eglCreateImageKHR target */ +#define EGL_GL_TEXTURE_ZOFFSET_KHR 0x30BD /* eglCreateImageKHR attribute */ +#endif + +#ifndef EGL_KHR_gl_renderbuffer_image +#define EGL_KHR_gl_renderbuffer_image 1 +#define EGL_GL_RENDERBUFFER_KHR 0x30B9 /* eglCreateImageKHR target */ +#endif + +#ifndef EGL_KHR_image_base +#define EGL_KHR_image_base 1 +/* Most interfaces defined by EGL_KHR_image_pixmap above */ +#define EGL_IMAGE_PRESERVED_KHR 0x30D2 /* eglCreateImageKHR attribute */ +#endif + +#ifndef EGL_KHR_image_pixmap +#define EGL_KHR_image_pixmap 1 +/* Interfaces defined by EGL_KHR_image above */ +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/GLES/eglnatives.h b/opengl/include/EGL/eglnatives.h similarity index 86% rename from include/GLES/eglnatives.h rename to opengl/include/EGL/eglnatives.h index 1cd57d0684e8bbc5bd155aa91c63b6d8f2b7ab78..21622dc5a68c4e0298e331d334a6354345b492dc 100644 --- a/include/GLES/eglnatives.h +++ b/opengl/include/EGL/eglnatives.h @@ -22,23 +22,8 @@ #ifdef __cplusplus extern "C" { #endif -/*****************************************************************************/ - -struct egl_native_window_t; -struct egl_native_pixmap_t; - - -typedef struct egl_native_window_t* NativeWindowType; -typedef struct egl_native_pixmap_t* NativePixmapType; -typedef void* NativeDisplayType; - -/* - * This a convenience function to create a NativeWindowType surface - * that maps to the whole screen - * This function is actually implemented in libui.so - */ -NativeWindowType android_createDisplaySurface(); +/*****************************************************************************/ /* flags returned from swapBuffer */ #define EGL_NATIVES_FLAG_SIZE_CHANGED 0x00000001 @@ -151,48 +136,46 @@ struct egl_native_window_t /* * Hook called by EGL to hold a reference on this structure */ - void (*incRef)(NativeWindowType window); + void (*incRef)(struct egl_native_window_t* window); /* * Hook called by EGL to release a reference on this structure */ - void (*decRef)(NativeWindowType window); + void (*decRef)(struct egl_native_window_t* window); /* * Hook called by EGL to perform a page flip. This function * may update the size attributes above, in which case it returns * the EGL_NATIVES_FLAG_SIZE_CHANGED bit set. */ - uint32_t (*swapBuffers)(NativeWindowType window); + uint32_t (*swapBuffers)(struct egl_native_window_t* window); /* - * Hook called by EGL to set the swap rectangle. this hook can be - * null (operation not supported) + * Reserved for future use. MUST BE ZERO. */ - void (*setSwapRectangle)(NativeWindowType window, int l, int t, int w, int h); + void (*reserved_proc_0)(void); /* * Reserved for future use. MUST BE ZERO. */ - void (*reserved_proc_0)(void); - + void (*reserved_proc_1)(void); /* - * Hook called by EGL to retrieve the next buffer to render into. - * This call updates this structure. + * Reserved for future use. MUST BE ZERO. */ - uint32_t (*nextBuffer)(NativeWindowType window); + void (*reserved_proc_2)(void); + /* * Hook called by EGL when the native surface is associated to EGL * (eglCreateWindowSurface). Can be NULL. */ - void (*connect)(NativeWindowType window); + void (*connect)(struct egl_native_window_t* window); /* * Hook called by EGL when eglDestroySurface is called. Can be NULL. */ - void (*disconnect)(NativeWindowType window); + void (*disconnect)(struct egl_native_window_t* window); /* * Reserved for future use. MUST BE ZERO. @@ -224,6 +207,17 @@ struct egl_native_pixmap_t /*****************************************************************************/ +/* + * This a convenience function to create a NativeWindowType surface + * that maps to the whole screen + * This function is actually implemented in libui.so + */ + +struct egl_native_window_t* android_createDisplaySurface(); + +/*****************************************************************************/ + + /* * OEM's egl's library (libhgl.so) must imlement these hooks to allocate * the GPU memory they need diff --git a/opengl/include/EGL/eglplatform.h b/opengl/include/EGL/eglplatform.h new file mode 100644 index 0000000000000000000000000000000000000000..ac0090102c31f9c405e20960e558a4d745e8dabf --- /dev/null +++ b/opengl/include/EGL/eglplatform.h @@ -0,0 +1,117 @@ +#ifndef __eglplatform_h_ +#define __eglplatform_h_ + +/* +** Copyright (c) 2007-2009 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Platform-specific types and definitions for egl.h + * $Revision: 7244 $ on $Date: 2009-01-20 17:06:59 -0800 (Tue, 20 Jan 2009) $ + * + * Adopters may modify khrplatform.h and this file to suit their platform. + * You are encouraged to submit all modifications to the Khronos group so that + * they can be included in future versions of this file. Please submit changes + * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla) + * by filing a bug against product "EGL" component "Registry". + */ + +#include + +/* Macros used in EGL function prototype declarations. + * + * EGL functions should be prototyped as: + * + * EGLAPI return-type EGLAPIENTRY eglFunction(arguments); + * typedef return-type (EXPAPIENTRYP PFNEGLFUNCTIONPROC) (arguments); + * + * KHRONOS_APICALL and KHRONOS_APIENTRY are defined in KHR/khrplatform.h + */ + +#ifndef EGLAPI +#define EGLAPI KHRONOS_APICALL +#endif + +#define EGLAPIENTRY KHRONOS_APIENTRY +#define EGLAPIENTRYP KHRONOS_APIENTRY* + +/* The types NativeDisplayType, NativeWindowType, and NativePixmapType + * are aliases of window-system-dependent types, such as X Display * or + * Windows Device Context. They must be defined in platform-specific + * code below. The EGL-prefixed versions of Native*Type are the same + * types, renamed in EGL 1.3 so all types in the API start with "EGL". + */ + +#if defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include + +typedef HDC EGLNativeDisplayType; +typedef HBITMAP EGLNativePixmapType; +typedef HWND EGLNativeWindowType; + +#elif defined(__WINSCW__) || defined(__SYMBIAN32__) /* Symbian */ + +typedef int EGLNativeDisplayType; +typedef void *EGLNativeWindowType; +typedef void *EGLNativePixmapType; + +#elif defined(__unix__) && !defined(ANDROID) + +/* X11 (tentative) */ +#include +#include + +typedef Display *EGLNativeDisplayType; +typedef Pixmap EGLNativePixmapType; +typedef Window EGLNativeWindowType; + + +#elif defined(ANDROID) + +#include + +typedef struct egl_native_window_t* EGLNativeWindowType; +typedef struct egl_native_pixmap_t* EGLNativePixmapType; +typedef void* EGLNativeDisplayType; + +#else +#error "Platform not recognized" +#endif + +/* EGL 1.2 types, renamed for consistency in EGL 1.3 */ +typedef EGLNativeDisplayType NativeDisplayType; +typedef EGLNativePixmapType NativePixmapType; +typedef EGLNativeWindowType NativeWindowType; + + +/* Define EGLint. This must be a signed integral type large enough to contain + * all legal attribute names and values passed into and out of EGL, whether + * their type is boolean, bitmask, enumerant (symbolic constant), integer, + * handle, or other. While in general a 32-bit integer will suffice, if + * handles are 64 bit types, then EGLint should be defined as a signed 64-bit + * integer type. + */ +typedef khronos_int32_t EGLint; + +#endif /* __eglplatform_h */ diff --git a/opengl/include/GLES/egl.h b/opengl/include/GLES/egl.h new file mode 100644 index 0000000000000000000000000000000000000000..5778e00509c27b94f7b47b8b445c1b6b8aa3284e --- /dev/null +++ b/opengl/include/GLES/egl.h @@ -0,0 +1,15 @@ +/* + * Skeleton egl.h to provide compatibility for early GLES 1.0 + * applications. Several early implementations included gl.h + * in egl.h leading applications to include only egl.h + * + * $Revision: 6252 $ on $Date:: 2008-08-06 16:35:08 -0700 #$ + */ + +#ifndef __legacy_egl_h_ +#define __legacy_egl_h_ + +#include +#include + +#endif /* __legacy_egl_h_ */ diff --git a/opengl/include/GLES/gl.h b/opengl/include/GLES/gl.h new file mode 100644 index 0000000000000000000000000000000000000000..2e8b97107ac97ca4ec1205a4fae9cec21e276788 --- /dev/null +++ b/opengl/include/GLES/gl.h @@ -0,0 +1,769 @@ +#ifndef __gl_h_ +#define __gl_h_ + +/* $Revision: 7172 $ on $Date:: 2009-01-09 11:17:41 -0800 #$ */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * This document is licensed under the SGI Free Software B License Version + * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ . + */ + +typedef void GLvoid; +typedef unsigned int GLenum; +typedef unsigned char GLboolean; +typedef unsigned int GLbitfield; +typedef khronos_int8_t GLbyte; +typedef short GLshort; +typedef int GLint; +typedef int GLsizei; +typedef khronos_uint8_t GLubyte; +typedef unsigned short GLushort; +typedef unsigned int GLuint; +typedef khronos_float_t GLfloat; +typedef khronos_float_t GLclampf; +typedef khronos_int32_t GLfixed; +typedef khronos_int32_t GLclampx; + +typedef khronos_intptr_t GLintptr; +typedef khronos_ssize_t GLsizeiptr; + + +/*************************************************************/ + +/* OpenGL ES core versions */ +#define GL_VERSION_ES_CM_1_0 1 +#define GL_VERSION_ES_CL_1_0 1 +#define GL_VERSION_ES_CM_1_1 1 +#define GL_VERSION_ES_CL_1_1 1 + +/* ClearBufferMask */ +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_COLOR_BUFFER_BIT 0x00004000 + +/* Boolean */ +#define GL_FALSE 0 +#define GL_TRUE 1 + +/* BeginMode */ +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 + +/* AlphaFunction */ +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 + +/* BlendingFactorDest */ +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 + +/* BlendingFactorSrc */ +/* GL_ZERO */ +/* GL_ONE */ +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 +/* GL_SRC_ALPHA */ +/* GL_ONE_MINUS_SRC_ALPHA */ +/* GL_DST_ALPHA */ +/* GL_ONE_MINUS_DST_ALPHA */ + +/* ClipPlaneName */ +#define GL_CLIP_PLANE0 0x3000 +#define GL_CLIP_PLANE1 0x3001 +#define GL_CLIP_PLANE2 0x3002 +#define GL_CLIP_PLANE3 0x3003 +#define GL_CLIP_PLANE4 0x3004 +#define GL_CLIP_PLANE5 0x3005 + +/* ColorMaterialFace */ +/* GL_FRONT_AND_BACK */ + +/* ColorMaterialParameter */ +/* GL_AMBIENT_AND_DIFFUSE */ + +/* ColorPointerType */ +/* GL_UNSIGNED_BYTE */ +/* GL_FLOAT */ +/* GL_FIXED */ + +/* CullFaceMode */ +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_FRONT_AND_BACK 0x0408 + +/* DepthFunction */ +/* GL_NEVER */ +/* GL_LESS */ +/* GL_EQUAL */ +/* GL_LEQUAL */ +/* GL_GREATER */ +/* GL_NOTEQUAL */ +/* GL_GEQUAL */ +/* GL_ALWAYS */ + +/* EnableCap */ +#define GL_FOG 0x0B60 +#define GL_LIGHTING 0x0B50 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_CULL_FACE 0x0B44 +#define GL_ALPHA_TEST 0x0BC0 +#define GL_BLEND 0x0BE2 +#define GL_COLOR_LOGIC_OP 0x0BF2 +#define GL_DITHER 0x0BD0 +#define GL_STENCIL_TEST 0x0B90 +#define GL_DEPTH_TEST 0x0B71 +/* GL_LIGHT0 */ +/* GL_LIGHT1 */ +/* GL_LIGHT2 */ +/* GL_LIGHT3 */ +/* GL_LIGHT4 */ +/* GL_LIGHT5 */ +/* GL_LIGHT6 */ +/* GL_LIGHT7 */ +#define GL_POINT_SMOOTH 0x0B10 +#define GL_LINE_SMOOTH 0x0B20 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_COLOR_MATERIAL 0x0B57 +#define GL_NORMALIZE 0x0BA1 +#define GL_RESCALE_NORMAL 0x803A +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_VERTEX_ARRAY 0x8074 +#define GL_NORMAL_ARRAY 0x8075 +#define GL_COLOR_ARRAY 0x8076 +#define GL_TEXTURE_COORD_ARRAY 0x8078 +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 + +/* ErrorCode */ +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_STACK_OVERFLOW 0x0503 +#define GL_STACK_UNDERFLOW 0x0504 +#define GL_OUT_OF_MEMORY 0x0505 + +/* FogMode */ +/* GL_LINEAR */ +#define GL_EXP 0x0800 +#define GL_EXP2 0x0801 + +/* FogParameter */ +#define GL_FOG_DENSITY 0x0B62 +#define GL_FOG_START 0x0B63 +#define GL_FOG_END 0x0B64 +#define GL_FOG_MODE 0x0B65 +#define GL_FOG_COLOR 0x0B66 + +/* FrontFaceDirection */ +#define GL_CW 0x0900 +#define GL_CCW 0x0901 + +/* GetPName */ +#define GL_CURRENT_COLOR 0x0B00 +#define GL_CURRENT_NORMAL 0x0B02 +#define GL_CURRENT_TEXTURE_COORDS 0x0B03 +#define GL_POINT_SIZE 0x0B11 +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_LINE_WIDTH 0x0B21 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_SHADE_MODEL 0x0B54 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_MATRIX_MODE 0x0BA0 +#define GL_VIEWPORT 0x0BA2 +#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 +#define GL_PROJECTION_STACK_DEPTH 0x0BA4 +#define GL_TEXTURE_STACK_DEPTH 0x0BA5 +#define GL_MODELVIEW_MATRIX 0x0BA6 +#define GL_PROJECTION_MATRIX 0x0BA7 +#define GL_TEXTURE_MATRIX 0x0BA8 +#define GL_ALPHA_TEST_FUNC 0x0BC1 +#define GL_ALPHA_TEST_REF 0x0BC2 +#define GL_BLEND_DST 0x0BE0 +#define GL_BLEND_SRC 0x0BE1 +#define GL_LOGIC_OP_MODE 0x0BF0 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_LIGHTS 0x0D31 +#define GL_MAX_CLIP_PLANES 0x0D32 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 +#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 +#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_RED_BITS 0x0D52 +#define GL_GREEN_BITS 0x0D53 +#define GL_BLUE_BITS 0x0D54 +#define GL_ALPHA_BITS 0x0D55 +#define GL_DEPTH_BITS 0x0D56 +#define GL_STENCIL_BITS 0x0D57 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_VERTEX_ARRAY_SIZE 0x807A +#define GL_VERTEX_ARRAY_TYPE 0x807B +#define GL_VERTEX_ARRAY_STRIDE 0x807C +#define GL_NORMAL_ARRAY_TYPE 0x807E +#define GL_NORMAL_ARRAY_STRIDE 0x807F +#define GL_COLOR_ARRAY_SIZE 0x8081 +#define GL_COLOR_ARRAY_TYPE 0x8082 +#define GL_COLOR_ARRAY_STRIDE 0x8083 +#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A +#define GL_VERTEX_ARRAY_POINTER 0x808E +#define GL_NORMAL_ARRAY_POINTER 0x808F +#define GL_COLOR_ARRAY_POINTER 0x8090 +#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB + +/* GetTextureParameter */ +/* GL_TEXTURE_MAG_FILTER */ +/* GL_TEXTURE_MIN_FILTER */ +/* GL_TEXTURE_WRAP_S */ +/* GL_TEXTURE_WRAP_T */ + +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 + +/* HintMode */ +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 + +/* HintTarget */ +#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 +#define GL_POINT_SMOOTH_HINT 0x0C51 +#define GL_LINE_SMOOTH_HINT 0x0C52 +#define GL_FOG_HINT 0x0C54 +#define GL_GENERATE_MIPMAP_HINT 0x8192 + +/* LightModelParameter */ +#define GL_LIGHT_MODEL_AMBIENT 0x0B53 +#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 + +/* LightParameter */ +#define GL_AMBIENT 0x1200 +#define GL_DIFFUSE 0x1201 +#define GL_SPECULAR 0x1202 +#define GL_POSITION 0x1203 +#define GL_SPOT_DIRECTION 0x1204 +#define GL_SPOT_EXPONENT 0x1205 +#define GL_SPOT_CUTOFF 0x1206 +#define GL_CONSTANT_ATTENUATION 0x1207 +#define GL_LINEAR_ATTENUATION 0x1208 +#define GL_QUADRATIC_ATTENUATION 0x1209 + +/* DataType */ +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_FLOAT 0x1406 +#define GL_FIXED 0x140C + +/* LogicOp */ +#define GL_CLEAR 0x1500 +#define GL_AND 0x1501 +#define GL_AND_REVERSE 0x1502 +#define GL_COPY 0x1503 +#define GL_AND_INVERTED 0x1504 +#define GL_NOOP 0x1505 +#define GL_XOR 0x1506 +#define GL_OR 0x1507 +#define GL_NOR 0x1508 +#define GL_EQUIV 0x1509 +#define GL_INVERT 0x150A +#define GL_OR_REVERSE 0x150B +#define GL_COPY_INVERTED 0x150C +#define GL_OR_INVERTED 0x150D +#define GL_NAND 0x150E +#define GL_SET 0x150F + +/* MaterialFace */ +/* GL_FRONT_AND_BACK */ + +/* MaterialParameter */ +#define GL_EMISSION 0x1600 +#define GL_SHININESS 0x1601 +#define GL_AMBIENT_AND_DIFFUSE 0x1602 +/* GL_AMBIENT */ +/* GL_DIFFUSE */ +/* GL_SPECULAR */ + +/* MatrixMode */ +#define GL_MODELVIEW 0x1700 +#define GL_PROJECTION 0x1701 +#define GL_TEXTURE 0x1702 + +/* NormalPointerType */ +/* GL_BYTE */ +/* GL_SHORT */ +/* GL_FLOAT */ +/* GL_FIXED */ + +/* PixelFormat */ +#define GL_ALPHA 0x1906 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE_ALPHA 0x190A + +/* PixelStoreParameter */ +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_ALIGNMENT 0x0D05 + +/* PixelType */ +/* GL_UNSIGNED_BYTE */ +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 + +/* ShadingModel */ +#define GL_FLAT 0x1D00 +#define GL_SMOOTH 0x1D01 + +/* StencilFunction */ +/* GL_NEVER */ +/* GL_LESS */ +/* GL_EQUAL */ +/* GL_LEQUAL */ +/* GL_GREATER */ +/* GL_NOTEQUAL */ +/* GL_GEQUAL */ +/* GL_ALWAYS */ + +/* StencilOp */ +/* GL_ZERO */ +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 +/* GL_INVERT */ + +/* StringName */ +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 + +/* TexCoordPointerType */ +/* GL_SHORT */ +/* GL_FLOAT */ +/* GL_FIXED */ +/* GL_BYTE */ + +/* TextureEnvMode */ +#define GL_MODULATE 0x2100 +#define GL_DECAL 0x2101 +/* GL_BLEND */ +#define GL_ADD 0x0104 +/* GL_REPLACE */ + +/* TextureEnvParameter */ +#define GL_TEXTURE_ENV_MODE 0x2200 +#define GL_TEXTURE_ENV_COLOR 0x2201 + +/* TextureEnvTarget */ +#define GL_TEXTURE_ENV 0x2300 + +/* TextureMagFilter */ +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 + +/* TextureMinFilter */ +/* GL_NEAREST */ +/* GL_LINEAR */ +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 + +/* TextureParameterName */ +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_GENERATE_MIPMAP 0x8191 + +/* TextureTarget */ +/* GL_TEXTURE_2D */ + +/* TextureUnit */ +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 + +/* TextureWrapMode */ +#define GL_REPEAT 0x2901 +#define GL_CLAMP_TO_EDGE 0x812F + +/* VertexPointerType */ +/* GL_SHORT */ +/* GL_FLOAT */ +/* GL_FIXED */ +/* GL_BYTE */ + +/* LightName */ +#define GL_LIGHT0 0x4000 +#define GL_LIGHT1 0x4001 +#define GL_LIGHT2 0x4002 +#define GL_LIGHT3 0x4003 +#define GL_LIGHT4 0x4004 +#define GL_LIGHT5 0x4005 +#define GL_LIGHT6 0x4006 +#define GL_LIGHT7 0x4007 + +/* Buffer Objects */ +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 + +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A + +#define GL_STATIC_DRAW 0x88E4 +#define GL_DYNAMIC_DRAW 0x88E8 + +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 + +/* Texture combine + dot3 */ +#define GL_SUBTRACT 0x84E7 +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A + +#define GL_ALPHA_SCALE 0x0D1C + +#define GL_SRC0_RGB 0x8580 +#define GL_SRC1_RGB 0x8581 +#define GL_SRC2_RGB 0x8582 +#define GL_SRC0_ALPHA 0x8588 +#define GL_SRC1_ALPHA 0x8589 +#define GL_SRC2_ALPHA 0x858A + +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF + +/*------------------------------------------------------------------------* + * required OES extension tokens + *------------------------------------------------------------------------*/ + +/* OES_read_format */ +#ifndef GL_OES_read_format +#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B +#endif + +/* GL_OES_compressed_paletted_texture */ +#ifndef GL_OES_compressed_paletted_texture +#define GL_PALETTE4_RGB8_OES 0x8B90 +#define GL_PALETTE4_RGBA8_OES 0x8B91 +#define GL_PALETTE4_R5_G6_B5_OES 0x8B92 +#define GL_PALETTE4_RGBA4_OES 0x8B93 +#define GL_PALETTE4_RGB5_A1_OES 0x8B94 +#define GL_PALETTE8_RGB8_OES 0x8B95 +#define GL_PALETTE8_RGBA8_OES 0x8B96 +#define GL_PALETTE8_R5_G6_B5_OES 0x8B97 +#define GL_PALETTE8_RGBA4_OES 0x8B98 +#define GL_PALETTE8_RGB5_A1_OES 0x8B99 +#endif + +/* OES_point_size_array */ +#ifndef GL_OES_point_size_array +#define GL_POINT_SIZE_ARRAY_OES 0x8B9C +#define GL_POINT_SIZE_ARRAY_TYPE_OES 0x898A +#define GL_POINT_SIZE_ARRAY_STRIDE_OES 0x898B +#define GL_POINT_SIZE_ARRAY_POINTER_OES 0x898C +#define GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES 0x8B9F +#endif + +/* GL_OES_point_sprite */ +#ifndef GL_OES_point_sprite +#define GL_POINT_SPRITE_OES 0x8861 +#define GL_COORD_REPLACE_OES 0x8862 +#endif + +/*************************************************************/ + +/* Available only in Common profile */ +GL_API void GL_APIENTRY glAlphaFunc (GLenum func, GLclampf ref); +GL_API void GL_APIENTRY glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); +GL_API void GL_APIENTRY glClearDepthf (GLclampf depth); +GL_API void GL_APIENTRY glClipPlanef (GLenum plane, const GLfloat *equation); +GL_API void GL_APIENTRY glColor4f (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GL_API void GL_APIENTRY glDepthRangef (GLclampf zNear, GLclampf zFar); +GL_API void GL_APIENTRY glFogf (GLenum pname, GLfloat param); +GL_API void GL_APIENTRY glFogfv (GLenum pname, const GLfloat *params); +GL_API void GL_APIENTRY glFrustumf (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar); +GL_API void GL_APIENTRY glGetClipPlanef (GLenum pname, GLfloat eqn[4]); +GL_API void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat *params); +GL_API void GL_APIENTRY glGetLightfv (GLenum light, GLenum pname, GLfloat *params); +GL_API void GL_APIENTRY glGetMaterialfv (GLenum face, GLenum pname, GLfloat *params); +GL_API void GL_APIENTRY glGetTexEnvfv (GLenum env, GLenum pname, GLfloat *params); +GL_API void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params); +GL_API void GL_APIENTRY glLightModelf (GLenum pname, GLfloat param); +GL_API void GL_APIENTRY glLightModelfv (GLenum pname, const GLfloat *params); +GL_API void GL_APIENTRY glLightf (GLenum light, GLenum pname, GLfloat param); +GL_API void GL_APIENTRY glLightfv (GLenum light, GLenum pname, const GLfloat *params); +GL_API void GL_APIENTRY glLineWidth (GLfloat width); +GL_API void GL_APIENTRY glLoadMatrixf (const GLfloat *m); +GL_API void GL_APIENTRY glMaterialf (GLenum face, GLenum pname, GLfloat param); +GL_API void GL_APIENTRY glMaterialfv (GLenum face, GLenum pname, const GLfloat *params); +GL_API void GL_APIENTRY glMultMatrixf (const GLfloat *m); +GL_API void GL_APIENTRY glMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GL_API void GL_APIENTRY glNormal3f (GLfloat nx, GLfloat ny, GLfloat nz); +GL_API void GL_APIENTRY glOrthof (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar); +GL_API void GL_APIENTRY glPointParameterf (GLenum pname, GLfloat param); +GL_API void GL_APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params); +GL_API void GL_APIENTRY glPointSize (GLfloat size); +GL_API void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units); +GL_API void GL_APIENTRY glRotatef (GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +GL_API void GL_APIENTRY glScalef (GLfloat x, GLfloat y, GLfloat z); +GL_API void GL_APIENTRY glTexEnvf (GLenum target, GLenum pname, GLfloat param); +GL_API void GL_APIENTRY glTexEnvfv (GLenum target, GLenum pname, const GLfloat *params); +GL_API void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param); +GL_API void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params); +GL_API void GL_APIENTRY glTranslatef (GLfloat x, GLfloat y, GLfloat z); + +/* Available in both Common and Common-Lite profiles */ +GL_API void GL_APIENTRY glActiveTexture (GLenum texture); +GL_API void GL_APIENTRY glAlphaFuncx (GLenum func, GLclampx ref); +GL_API void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer); +GL_API void GL_APIENTRY glBindTexture (GLenum target, GLuint texture); +GL_API void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor); +GL_API void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage); +GL_API void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data); +GL_API void GL_APIENTRY glClear (GLbitfield mask); +GL_API void GL_APIENTRY glClearColorx (GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha); +GL_API void GL_APIENTRY glClearDepthx (GLclampx depth); +GL_API void GL_APIENTRY glClearStencil (GLint s); +GL_API void GL_APIENTRY glClientActiveTexture (GLenum texture); +GL_API void GL_APIENTRY glClipPlanex (GLenum plane, const GLfixed *equation); +GL_API void GL_APIENTRY glColor4ub (GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); +GL_API void GL_APIENTRY glColor4x (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GL_API void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +GL_API void GL_APIENTRY glColorPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +GL_API void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); +GL_API void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); +GL_API void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GL_API void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GL_API void GL_APIENTRY glCullFace (GLenum mode); +GL_API void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); +GL_API void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures); +GL_API void GL_APIENTRY glDepthFunc (GLenum func); +GL_API void GL_APIENTRY glDepthMask (GLboolean flag); +GL_API void GL_APIENTRY glDepthRangex (GLclampx zNear, GLclampx zFar); +GL_API void GL_APIENTRY glDisable (GLenum cap); +GL_API void GL_APIENTRY glDisableClientState (GLenum array); +GL_API void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count); +GL_API void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices); +GL_API void GL_APIENTRY glEnable (GLenum cap); +GL_API void GL_APIENTRY glEnableClientState (GLenum array); +GL_API void GL_APIENTRY glFinish (void); +GL_API void GL_APIENTRY glFlush (void); +GL_API void GL_APIENTRY glFogx (GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glFogxv (GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glFrontFace (GLenum mode); +GL_API void GL_APIENTRY glFrustumx (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar); +GL_API void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean *params); +GL_API void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); +GL_API void GL_APIENTRY glGetClipPlanex (GLenum pname, GLfixed eqn[4]); +GL_API void GL_APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); +GL_API void GL_APIENTRY glGenTextures (GLsizei n, GLuint *textures); +GL_API GLenum GL_APIENTRY glGetError (void); +GL_API void GL_APIENTRY glGetFixedv (GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glGetIntegerv (GLenum pname, GLint *params); +GL_API void GL_APIENTRY glGetLightxv (GLenum light, GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glGetMaterialxv (GLenum face, GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glGetPointerv (GLenum pname, void **params); +GL_API const GLubyte * GL_APIENTRY glGetString (GLenum name); +GL_API void GL_APIENTRY glGetTexEnviv (GLenum env, GLenum pname, GLint *params); +GL_API void GL_APIENTRY glGetTexEnvxv (GLenum env, GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params); +GL_API void GL_APIENTRY glGetTexParameterxv (GLenum target, GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glHint (GLenum target, GLenum mode); +GL_API GLboolean GL_APIENTRY glIsBuffer (GLuint buffer); +GL_API GLboolean GL_APIENTRY glIsEnabled (GLenum cap); +GL_API GLboolean GL_APIENTRY glIsTexture (GLuint texture); +GL_API void GL_APIENTRY glLightModelx (GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glLightModelxv (GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glLightx (GLenum light, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glLightxv (GLenum light, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glLineWidthx (GLfixed width); +GL_API void GL_APIENTRY glLoadIdentity (void); +GL_API void GL_APIENTRY glLoadMatrixx (const GLfixed *m); +GL_API void GL_APIENTRY glLogicOp (GLenum opcode); +GL_API void GL_APIENTRY glMaterialx (GLenum face, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glMaterialxv (GLenum face, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glMatrixMode (GLenum mode); +GL_API void GL_APIENTRY glMultMatrixx (const GLfixed *m); +GL_API void GL_APIENTRY glMultiTexCoord4x (GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +GL_API void GL_APIENTRY glNormal3x (GLfixed nx, GLfixed ny, GLfixed nz); +GL_API void GL_APIENTRY glNormalPointer (GLenum type, GLsizei stride, const GLvoid *pointer); +GL_API void GL_APIENTRY glOrthox (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar); +GL_API void GL_APIENTRY glPixelStorei (GLenum pname, GLint param); +GL_API void GL_APIENTRY glPointParameterx (GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glPointParameterxv (GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glPointSizex (GLfixed size); +GL_API void GL_APIENTRY glPolygonOffsetx (GLfixed factor, GLfixed units); +GL_API void GL_APIENTRY glPopMatrix (void); +GL_API void GL_APIENTRY glPushMatrix (void); +GL_API void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels); +GL_API void GL_APIENTRY glRotatex (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +GL_API void GL_APIENTRY glSampleCoverage (GLclampf value, GLboolean invert); +GL_API void GL_APIENTRY glSampleCoveragex (GLclampx value, GLboolean invert); +GL_API void GL_APIENTRY glScalex (GLfixed x, GLfixed y, GLfixed z); +GL_API void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height); +GL_API void GL_APIENTRY glShadeModel (GLenum mode); +GL_API void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask); +GL_API void GL_APIENTRY glStencilMask (GLuint mask); +GL_API void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass); +GL_API void GL_APIENTRY glTexCoordPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +GL_API void GL_APIENTRY glTexEnvi (GLenum target, GLenum pname, GLint param); +GL_API void GL_APIENTRY glTexEnvx (GLenum target, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glTexEnviv (GLenum target, GLenum pname, const GLint *params); +GL_API void GL_APIENTRY glTexEnvxv (GLenum target, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +GL_API void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param); +GL_API void GL_APIENTRY glTexParameterx (GLenum target, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params); +GL_API void GL_APIENTRY glTexParameterxv (GLenum target, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); +GL_API void GL_APIENTRY glTranslatex (GLfixed x, GLfixed y, GLfixed z); +GL_API void GL_APIENTRY glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +GL_API void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height); + +/*------------------------------------------------------------------------* + * Required OES extension functions + *------------------------------------------------------------------------*/ + +/* GL_OES_read_format */ +#ifndef GL_OES_read_format +#define GL_OES_read_format 1 +#endif + +/* GL_OES_compressed_paletted_texture */ +#ifndef GL_OES_compressed_paletted_texture +#define GL_OES_compressed_paletted_texture 1 +#endif + +/* GL_OES_point_size_array */ +#ifndef GL_OES_point_size_array +#define GL_OES_point_size_array 1 +GL_API void GL_APIENTRY glPointSizePointerOES (GLenum type, GLsizei stride, const GLvoid *pointer); +#endif + +/* GL_OES_point_sprite */ +#ifndef GL_OES_point_sprite +#define GL_OES_point_sprite 1 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __gl_h_ */ + diff --git a/opengl/include/GLES/glext.h b/opengl/include/GLES/glext.h new file mode 100644 index 0000000000000000000000000000000000000000..4c01871aeec589a2fdc91fd404871d1dcaf79fac --- /dev/null +++ b/opengl/include/GLES/glext.h @@ -0,0 +1,622 @@ +#ifndef __glext_h_ +#define __glext_h_ + +/* $Revision: 7172 $ on $Date:: 2009-01-09 11:17:41 -0800 #$ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * This document is licensed under the SGI Free Software B License Version + * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ . + */ + +#ifndef GL_APIENTRYP +# define GL_APIENTRYP GL_APIENTRY* +#endif + +/*------------------------------------------------------------------------* + * OES extension tokens + *------------------------------------------------------------------------*/ + +/* GL_OES_blend_equation_separate */ +#ifndef GL_OES_blend_equation_separate +/* BLEND_EQUATION_RGB_OES same as BLEND_EQUATION_OES */ +#define GL_BLEND_EQUATION_RGB_OES 0x8009 +#define GL_BLEND_EQUATION_ALPHA_OES 0x883D +#endif + +/* GL_OES_blend_func_separate */ +#ifndef GL_OES_blend_func_separate +#define GL_BLEND_DST_RGB_OES 0x80C8 +#define GL_BLEND_SRC_RGB_OES 0x80C9 +#define GL_BLEND_DST_ALPHA_OES 0x80CA +#define GL_BLEND_SRC_ALPHA_OES 0x80CB +#endif + +/* GL_OES_blend_subtract */ +#ifndef GL_OES_blend_subtract +#define GL_BLEND_EQUATION_OES 0x8009 +#define GL_FUNC_ADD_OES 0x8006 +#define GL_FUNC_SUBTRACT_OES 0x800A +#define GL_FUNC_REVERSE_SUBTRACT_OES 0x800B +#endif + +/* GL_OES_compressed_ETC1_RGB8_texture */ +#ifndef GL_OES_compressed_ETC1_RGB8_texture +#define GL_ETC1_RGB8_OES 0x8D64 +#endif + +/* GL_OES_depth24 */ +#ifndef GL_OES_depth24 +#define GL_DEPTH_COMPONENT24_OES 0x81A6 +#endif + +/* GL_OES_depth32 */ +#ifndef GL_OES_depth32 +#define GL_DEPTH_COMPONENT32_OES 0x81A7 +#endif + +/* GL_OES_draw_texture */ +#ifndef GL_OES_draw_texture +#define GL_TEXTURE_CROP_RECT_OES 0x8B9D +#endif + +/* GL_OES_EGL_image */ +#ifndef GL_OES_EGL_image +typedef void* GLeglImageOES; +#endif + +/* GL_OES_fixed_point */ +#ifndef GL_OES_fixed_point +#define GL_FIXED_OES 0x140C +#endif + +/* GL_OES_framebuffer_object */ +#ifndef GL_OES_framebuffer_object +#define GL_NONE_OES 0 +#define GL_FRAMEBUFFER_OES 0x8D40 +#define GL_RENDERBUFFER_OES 0x8D41 +#define GL_RGBA4_OES 0x8056 +#define GL_RGB5_A1_OES 0x8057 +#define GL_RGB565_OES 0x8D62 +#define GL_DEPTH_COMPONENT16_OES 0x81A5 +#define GL_RENDERBUFFER_WIDTH_OES 0x8D42 +#define GL_RENDERBUFFER_HEIGHT_OES 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT_OES 0x8D44 +#define GL_RENDERBUFFER_RED_SIZE_OES 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE_OES 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE_OES 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE_OES 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE_OES 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE_OES 0x8D55 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES 0x8CD3 +#define GL_COLOR_ATTACHMENT0_OES 0x8CE0 +#define GL_DEPTH_ATTACHMENT_OES 0x8D00 +#define GL_STENCIL_ATTACHMENT_OES 0x8D20 +#define GL_FRAMEBUFFER_COMPLETE_OES 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES 0x8CD9 +#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES 0x8CDA +#define GL_FRAMEBUFFER_UNSUPPORTED_OES 0x8CDD +#define GL_FRAMEBUFFER_BINDING_OES 0x8CA6 +#define GL_RENDERBUFFER_BINDING_OES 0x8CA7 +#define GL_MAX_RENDERBUFFER_SIZE_OES 0x84E8 +#define GL_INVALID_FRAMEBUFFER_OPERATION_OES 0x0506 +#endif + +/* GL_OES_mapbuffer */ +#ifndef GL_OES_mapbuffer +#define GL_WRITE_ONLY_OES 0x88B9 +#define GL_BUFFER_ACCESS_OES 0x88BB +#define GL_BUFFER_MAPPED_OES 0x88BC +#define GL_BUFFER_MAP_POINTER_OES 0x88BD +#endif + +/* GL_OES_matrix_get */ +#ifndef GL_OES_matrix_get +#define GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES 0x898D +#define GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES 0x898E +#define GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES 0x898F +#endif + +/* GL_OES_matrix_palette */ +#ifndef GL_OES_matrix_palette +#define GL_MAX_VERTEX_UNITS_OES 0x86A4 +#define GL_MAX_PALETTE_MATRICES_OES 0x8842 +#define GL_MATRIX_PALETTE_OES 0x8840 +#define GL_MATRIX_INDEX_ARRAY_OES 0x8844 +#define GL_WEIGHT_ARRAY_OES 0x86AD +#define GL_CURRENT_PALETTE_MATRIX_OES 0x8843 +#define GL_MATRIX_INDEX_ARRAY_SIZE_OES 0x8846 +#define GL_MATRIX_INDEX_ARRAY_TYPE_OES 0x8847 +#define GL_MATRIX_INDEX_ARRAY_STRIDE_OES 0x8848 +#define GL_MATRIX_INDEX_ARRAY_POINTER_OES 0x8849 +#define GL_MATRIX_INDEX_ARRAY_BUFFER_BINDING_OES 0x8B9E +#define GL_WEIGHT_ARRAY_SIZE_OES 0x86AB +#define GL_WEIGHT_ARRAY_TYPE_OES 0x86A9 +#define GL_WEIGHT_ARRAY_STRIDE_OES 0x86AA +#define GL_WEIGHT_ARRAY_POINTER_OES 0x86AC +#define GL_WEIGHT_ARRAY_BUFFER_BINDING_OES 0x889E +#endif + +/* GL_OES_packed_depth_stencil */ +#ifndef GL_OES_packed_depth_stencil +#define GL_DEPTH_STENCIL_OES 0x84F9 +#define GL_UNSIGNED_INT_24_8_OES 0x84FA +#define GL_DEPTH24_STENCIL8_OES 0x88F0 +#endif + +/* GL_OES_rgb8_rgba8 */ +#ifndef GL_OES_rgb8_rgba8 +#define GL_RGB8_OES 0x8051 +#define GL_RGBA8_OES 0x8058 +#endif + +/* GL_OES_stencil1 */ +#ifndef GL_OES_stencil1 +#define GL_STENCIL_INDEX1_OES 0x8D46 +#endif + +/* GL_OES_stencil4 */ +#ifndef GL_OES_stencil4 +#define GL_STENCIL_INDEX4_OES 0x8D47 +#endif + +/* GL_OES_stencil8 */ +#ifndef GL_OES_stencil8 +#define GL_STENCIL_INDEX8_OES 0x8D48 +#endif + +/* GL_OES_stencil_wrap */ +#ifndef GL_OES_stencil_wrap +#define GL_INCR_WRAP_OES 0x8507 +#define GL_DECR_WRAP_OES 0x8508 +#endif + +/* GL_OES_texture_cube_map */ +#ifndef GL_OES_texture_cube_map +#define GL_NORMAL_MAP_OES 0x8511 +#define GL_REFLECTION_MAP_OES 0x8512 +#define GL_TEXTURE_CUBE_MAP_OES 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_OES 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_OES 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_OES 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_OES 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_OES 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_OES 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_OES 0x851A +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_OES 0x851C +#define GL_TEXTURE_GEN_MODE_OES 0x2500 +#define GL_TEXTURE_GEN_STR_OES 0x8D60 +#endif + +/* GL_OES_texture_mirrored_repeat */ +#ifndef GL_OES_texture_mirrored_repeat +#define GL_MIRRORED_REPEAT_OES 0x8370 +#endif + +/*------------------------------------------------------------------------* + * AMD extension tokens + *------------------------------------------------------------------------*/ + +/* GL_AMD_compressed_3DC_texture */ +#ifndef GL_AMD_compressed_3DC_texture +#define GL_3DC_X_AMD 0x87F9 +#define GL_3DC_XY_AMD 0x87FA +#endif + +/* GL_AMD_compressed_ATC_texture */ +#ifndef GL_AMD_compressed_ATC_texture +#define GL_ATC_RGB_AMD 0x8C92 +#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93 +#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE +#endif + +/*------------------------------------------------------------------------* + * EXT extension tokens + *------------------------------------------------------------------------*/ + +/* GL_EXT_texture_filter_anisotropic */ +#ifndef GL_EXT_texture_filter_anisotropic +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#endif + +/*------------------------------------------------------------------------* + * OES extension functions + *------------------------------------------------------------------------*/ + +/* GL_OES_blend_equation_separate */ +#ifndef GL_OES_blend_equation_separate +#define GL_OES_blend_equation_separate 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glBlendEquationSeparateOES (GLenum modeRGB, GLenum modeAlpha); +#endif +typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEOESPROC) (GLenum modeRGB, GLenum modeAlpha); +#endif + +/* GL_OES_blend_func_separate */ +#ifndef GL_OES_blend_func_separate +#define GL_OES_blend_func_separate 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glBlendFuncSeparateOES (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +#endif +typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEOESPROC) (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +#endif + +/* GL_OES_blend_subtract */ +#ifndef GL_OES_blend_subtract +#define GL_OES_blend_subtract 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glBlendEquationOES (GLenum mode); +#endif +typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONOESPROC) (GLenum mode); +#endif + +/* GL_OES_byte_coordinates */ +#ifndef GL_OES_byte_coordinates +#define GL_OES_byte_coordinates 1 +#endif + +/* GL_OES_compressed_ETC1_RGB8_texture */ +#ifndef GL_OES_compressed_ETC1_RGB8_texture +#define GL_OES_compressed_ETC1_RGB8_texture 1 +#endif + +/* GL_OES_depth24 */ +#ifndef GL_OES_depth24 +#define GL_OES_depth24 1 +#endif + +/* GL_OES_depth32 */ +#ifndef GL_OES_depth32 +#define GL_OES_depth32 1 +#endif + +/* GL_OES_draw_texture */ +#ifndef GL_OES_draw_texture +#define GL_OES_draw_texture 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glDrawTexsOES (GLshort x, GLshort y, GLshort z, GLshort width, GLshort height); +GL_API void GL_APIENTRY glDrawTexiOES (GLint x, GLint y, GLint z, GLint width, GLint height); +GL_API void GL_APIENTRY glDrawTexxOES (GLfixed x, GLfixed y, GLfixed z, GLfixed width, GLfixed height); +GL_API void GL_APIENTRY glDrawTexsvOES (const GLshort *coords); +GL_API void GL_APIENTRY glDrawTexivOES (const GLint *coords); +GL_API void GL_APIENTRY glDrawTexxvOES (const GLfixed *coords); +GL_API void GL_APIENTRY glDrawTexfOES (GLfloat x, GLfloat y, GLfloat z, GLfloat width, GLfloat height); +GL_API void GL_APIENTRY glDrawTexfvOES (const GLfloat *coords); +#endif +typedef void (GL_APIENTRYP PFNGLDRAWTEXSOESPROC) (GLshort x, GLshort y, GLshort z, GLshort width, GLshort height); +typedef void (GL_APIENTRYP PFNGLDRAWTEXIOESPROC) (GLint x, GLint y, GLint z, GLint width, GLint height); +typedef void (GL_APIENTRYP PFNGLDRAWTEXXOESPROC) (GLfixed x, GLfixed y, GLfixed z, GLfixed width, GLfixed height); +typedef void (GL_APIENTRYP PFNGLDRAWTEXSVOESPROC) (const GLshort *coords); +typedef void (GL_APIENTRYP PFNGLDRAWTEXIVOESPROC) (const GLint *coords); +typedef void (GL_APIENTRYP PFNGLDRAWTEXXVOESPROC) (const GLfixed *coords); +typedef void (GL_APIENTRYP PFNGLDRAWTEXFOESPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat width, GLfloat height); +typedef void (GL_APIENTRYP PFNGLDRAWTEXFVOESPROC) (const GLfloat *coords); +#endif + +/* GL_OES_EGL_image */ +#ifndef GL_OES_EGL_image +#define GL_OES_EGL_image 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image); +GL_API void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image); +#endif +typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image); +typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image); +#endif + +/* GL_OES_element_index_uint */ +#ifndef GL_OES_element_index_uint +#define GL_OES_element_index_uint 1 +#endif + +/* GL_OES_extended_matrix_palette */ +#ifndef GL_OES_extended_matrix_palette +#define GL_OES_extended_matrix_palette 1 +#endif + +/* GL_OES_fbo_render_mipmap */ +#ifndef GL_OES_fbo_render_mipmap +#define GL_OES_fbo_render_mipmap 1 +#endif + +/* GL_OES_fixed_point */ +#ifndef GL_OES_fixed_point +#define GL_OES_fixed_point 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glAlphaFuncxOES (GLenum func, GLclampx ref); +GL_API void GL_APIENTRY glClearColorxOES (GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha); +GL_API void GL_APIENTRY glClearDepthxOES (GLclampx depth); +GL_API void GL_APIENTRY glClipPlanexOES (GLenum plane, const GLfixed *equation); +GL_API void GL_APIENTRY glColor4xOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GL_API void GL_APIENTRY glDepthRangexOES (GLclampx zNear, GLclampx zFar); +GL_API void GL_APIENTRY glFogxOES (GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glFogxvOES (GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glFrustumxOES (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar); +GL_API void GL_APIENTRY glGetClipPlanexOES (GLenum pname, GLfixed eqn[4]); +GL_API void GL_APIENTRY glGetFixedvOES (GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glGetLightxvOES (GLenum light, GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glGetMaterialxvOES (GLenum face, GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glGetTexEnvxvOES (GLenum env, GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glGetTexParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GL_API void GL_APIENTRY glLightModelxOES (GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glLightModelxvOES (GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glLightxOES (GLenum light, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glLightxvOES (GLenum light, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glLineWidthxOES (GLfixed width); +GL_API void GL_APIENTRY glLoadMatrixxOES (const GLfixed *m); +GL_API void GL_APIENTRY glMaterialxOES (GLenum face, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glMaterialxvOES (GLenum face, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glMultMatrixxOES (const GLfixed *m); +GL_API void GL_APIENTRY glMultiTexCoord4xOES (GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +GL_API void GL_APIENTRY glNormal3xOES (GLfixed nx, GLfixed ny, GLfixed nz); +GL_API void GL_APIENTRY glOrthoxOES (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar); +GL_API void GL_APIENTRY glPointParameterxOES (GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glPointParameterxvOES (GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glPointSizexOES (GLfixed size); +GL_API void GL_APIENTRY glPolygonOffsetxOES (GLfixed factor, GLfixed units); +GL_API void GL_APIENTRY glRotatexOES (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +GL_API void GL_APIENTRY glSampleCoveragexOES (GLclampx value, GLboolean invert); +GL_API void GL_APIENTRY glScalexOES (GLfixed x, GLfixed y, GLfixed z); +GL_API void GL_APIENTRY glTexEnvxOES (GLenum target, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glTexEnvxvOES (GLenum target, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glTexParameterxOES (GLenum target, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glTexParameterxvOES (GLenum target, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glTranslatexOES (GLfixed x, GLfixed y, GLfixed z); +#endif +typedef void (GL_APIENTRYP PFNGLALPHAFUNCXOESPROC) (GLenum func, GLclampx ref); +typedef void (GL_APIENTRYP PFNGLCLEARCOLORXOESPROC) (GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha); +typedef void (GL_APIENTRYP PFNGLCLEARDEPTHXOESPROC) (GLclampx depth); +typedef void (GL_APIENTRYP PFNGLCLIPPLANEXOESPROC) (GLenum plane, const GLfixed *equation); +typedef void (GL_APIENTRYP PFNGLCOLOR4XOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (GL_APIENTRYP PFNGLDEPTHRANGEXOESPROC) (GLclampx zNear, GLclampx zFar); +typedef void (GL_APIENTRYP PFNGLFOGXOESPROC) (GLenum pname, GLfixed param); +typedef void (GL_APIENTRYP PFNGLFOGXVOESPROC) (GLenum pname, const GLfixed *params); +typedef void (GL_APIENTRYP PFNGLFRUSTUMXOESPROC) (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar); +typedef void (GL_APIENTRYP PFNGLGETCLIPPLANEXOESPROC) (GLenum pname, GLfixed eqn[4]); +typedef void (GL_APIENTRYP PFNGLGETFIXEDVOESPROC) (GLenum pname, GLfixed *params); +typedef void (GL_APIENTRYP PFNGLGETLIGHTXVOESPROC) (GLenum light, GLenum pname, GLfixed *params); +typedef void (GL_APIENTRYP PFNGLGETMATERIALXVOESPROC) (GLenum face, GLenum pname, GLfixed *params); +typedef void (GL_APIENTRYP PFNGLGETTEXENVXVOESPROC) (GLenum env, GLenum pname, GLfixed *params); +typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (GL_APIENTRYP PFNGLLIGHTMODELXOESPROC) (GLenum pname, GLfixed param); +typedef void (GL_APIENTRYP PFNGLLIGHTMODELXVOESPROC) (GLenum pname, const GLfixed *params); +typedef void (GL_APIENTRYP PFNGLLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed param); +typedef void (GL_APIENTRYP PFNGLLIGHTXVOESPROC) (GLenum light, GLenum pname, const GLfixed *params); +typedef void (GL_APIENTRYP PFNGLLINEWIDTHXOESPROC) (GLfixed width); +typedef void (GL_APIENTRYP PFNGLLOADMATRIXXOESPROC) (const GLfixed *m); +typedef void (GL_APIENTRYP PFNGLMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param); +typedef void (GL_APIENTRYP PFNGLMATERIALXVOESPROC) (GLenum face, GLenum pname, const GLfixed *params); +typedef void (GL_APIENTRYP PFNGLMULTMATRIXXOESPROC) (const GLfixed *m); +typedef void (GL_APIENTRYP PFNGLMULTITEXCOORD4XOESPROC) (GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +typedef void (GL_APIENTRYP PFNGLNORMAL3XOESPROC) (GLfixed nx, GLfixed ny, GLfixed nz); +typedef void (GL_APIENTRYP PFNGLORTHOXOESPROC) (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar); +typedef void (GL_APIENTRYP PFNGLPOINTPARAMETERXOESPROC) (GLenum pname, GLfixed param); +typedef void (GL_APIENTRYP PFNGLPOINTPARAMETERXVOESPROC) (GLenum pname, const GLfixed *params); +typedef void (GL_APIENTRYP PFNGLPOINTSIZEXOESPROC) (GLfixed size); +typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETXOESPROC) (GLfixed factor, GLfixed units); +typedef void (GL_APIENTRYP PFNGLROTATEXOESPROC) (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +typedef void (GL_APIENTRYP PFNGLSAMPLECOVERAGEXOESPROC) (GLclampx value, GLboolean invert); +typedef void (GL_APIENTRYP PFNGLSCALEXOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (GL_APIENTRYP PFNGLTEXENVXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (GL_APIENTRYP PFNGLTEXENVXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (GL_APIENTRYP PFNGLTRANSLATEXOESPROC) (GLfixed x, GLfixed y, GLfixed z); +#endif + +/* GL_OES_framebuffer_object */ +#ifndef GL_OES_framebuffer_object +#define GL_OES_framebuffer_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API GLboolean GL_APIENTRY glIsRenderbufferOES (GLuint renderbuffer); +GL_API void GL_APIENTRY glBindRenderbufferOES (GLenum target, GLuint renderbuffer); +GL_API void GL_APIENTRY glDeleteRenderbuffersOES (GLsizei n, const GLuint* renderbuffers); +GL_API void GL_APIENTRY glGenRenderbuffersOES (GLsizei n, GLuint* renderbuffers); +GL_API void GL_APIENTRY glRenderbufferStorageOES (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GL_API void GL_APIENTRY glGetRenderbufferParameterivOES (GLenum target, GLenum pname, GLint* params); +GL_API GLboolean GL_APIENTRY glIsFramebufferOES (GLuint framebuffer); +GL_API void GL_APIENTRY glBindFramebufferOES (GLenum target, GLuint framebuffer); +GL_API void GL_APIENTRY glDeleteFramebuffersOES (GLsizei n, const GLuint* framebuffers); +GL_API void GL_APIENTRY glGenFramebuffersOES (GLsizei n, GLuint* framebuffers); +GL_API GLenum GL_APIENTRY glCheckFramebufferStatusOES (GLenum target); +GL_API void GL_APIENTRY glFramebufferRenderbufferOES (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GL_API void GL_APIENTRY glFramebufferTexture2DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GL_API void GL_APIENTRY glGetFramebufferAttachmentParameterivOES (GLenum target, GLenum attachment, GLenum pname, GLint* params); +GL_API void GL_APIENTRY glGenerateMipmapOES (GLenum target); +#endif +typedef GLboolean (GL_APIENTRYP PFNGLISRENDERBUFFEROESPROC) (GLuint renderbuffer); +typedef void (GL_APIENTRYP PFNGLBINDRENDERBUFFEROESPROC) (GLenum target, GLuint renderbuffer); +typedef void (GL_APIENTRYP PFNGLDELETERENDERBUFFERSOESPROC) (GLsizei n, const GLuint* renderbuffers); +typedef void (GL_APIENTRYP PFNGLGENRENDERBUFFERSOESPROC) (GLsizei n, GLuint* renderbuffers); +typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVOESPROC) (GLenum target, GLenum pname, GLint* params); +typedef GLboolean (GL_APIENTRYP PFNGLISFRAMEBUFFEROESPROC) (GLuint framebuffer); +typedef void (GL_APIENTRYP PFNGLBINDFRAMEBUFFEROESPROC) (GLenum target, GLuint framebuffer); +typedef void (GL_APIENTRYP PFNGLDELETEFRAMEBUFFERSOESPROC) (GLsizei n, const GLuint* framebuffers); +typedef void (GL_APIENTRYP PFNGLGENFRAMEBUFFERSOESPROC) (GLsizei n, GLuint* framebuffers); +typedef GLenum (GL_APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSOESPROC) (GLenum target); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEROESPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DOESPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (GL_APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOESPROC) (GLenum target, GLenum attachment, GLenum pname, GLint* params); +typedef void (GL_APIENTRYP PFNGLGENERATEMIPMAPOESPROC) (GLenum target); +#endif + +/* GL_OES_mapbuffer */ +#ifndef GL_OES_mapbuffer +#define GL_OES_mapbuffer 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void* GL_APIENTRY glMapBufferOES (GLenum target, GLenum access); +GL_API GLboolean GL_APIENTRY glUnmapBufferOES (GLenum target); +GL_API void GL_APIENTRY glGetBufferPointervOES (GLenum target, GLenum pname, void** params); +#endif +typedef void* (GL_APIENTRYP PFNGLMAPBUFFEROESPROC) (GLenum target, GLenum access); +typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFEROESPROC) (GLenum target); +typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVOESPROC) (GLenum target, GLenum pname, void** params); +#endif + +/* GL_OES_matrix_get */ +#ifndef GL_OES_matrix_get +#define GL_OES_matrix_get 1 +#endif + +/* GL_OES_matrix_palette */ +#ifndef GL_OES_matrix_palette +#define GL_OES_matrix_palette 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glCurrentPaletteMatrixOES (GLuint matrixpaletteindex); +GL_API void GL_APIENTRY glLoadPaletteFromModelViewMatrixOES (void); +GL_API void GL_APIENTRY glMatrixIndexPointerOES (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +GL_API void GL_APIENTRY glWeightPointerOES (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +#endif +typedef void (GL_APIENTRYP PFNGLCURRENTPALETTEMATRIXOESPROC) (GLuint matrixpaletteindex); +typedef void (GL_APIENTRYP PFNGLLOADPALETTEFROMMODELVIEWMATRIXOESPROC) (void); +typedef void (GL_APIENTRYP PFNGLMATRIXINDEXPOINTEROESPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +typedef void (GL_APIENTRYP PFNGLWEIGHTPOINTEROESPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +#endif + +/* GL_OES_packed_depth_stencil */ +#ifndef GL_OES_packed_depth_stencil +#define GL_OES_packed_depth_stencil 1 +#endif + +/* GL_OES_query_matrix */ +#ifndef GL_OES_query_matrix +#define GL_OES_query_matrix 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API GLbitfield GL_APIENTRY glQueryMatrixxOES (GLfixed mantissa[16], GLint exponent[16]); +#endif +typedef GLbitfield (GL_APIENTRYP PFNGLQUERYMATRIXXOESPROC) (GLfixed mantissa[16], GLint exponent[16]); +#endif + +/* GL_OES_rgb8_rgba8 */ +#ifndef GL_OES_rgb8_rgba8 +#define GL_OES_rgb8_rgba8 1 +#endif + +/* GL_OES_single_precision */ +#ifndef GL_OES_single_precision +#define GL_OES_single_precision 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glDepthRangefOES (GLclampf zNear, GLclampf zFar); +GL_API void GL_APIENTRY glFrustumfOES (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar); +GL_API void GL_APIENTRY glOrthofOES (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar); +GL_API void GL_APIENTRY glClipPlanefOES (GLenum plane, const GLfloat *equation); +GL_API void GL_APIENTRY glGetClipPlanefOES (GLenum pname, GLfloat eqn[4]); +GL_API void GL_APIENTRY glClearDepthfOES (GLclampf depth); +#endif +typedef void (GL_APIENTRYP PFNGLDEPTHRANGEFOESPROC) (GLclampf zNear, GLclampf zFar); +typedef void (GL_APIENTRYP PFNGLFRUSTUMFOESPROC) (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar); +typedef void (GL_APIENTRYP PFNGLORTHOFOESPROC) (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar); +typedef void (GL_APIENTRYP PFNGLCLIPPLANEFOESPROC) (GLenum plane, const GLfloat *equation); +typedef void (GL_APIENTRYP PFNGLGETCLIPPLANEFOESPROC) (GLenum pname, GLfloat eqn[4]); +typedef void (GL_APIENTRYP PFNGLCLEARDEPTHFOESPROC) (GLclampf depth); +#endif + +/* GL_OES_stencil1 */ +#ifndef GL_OES_stencil1 +#define GL_OES_stencil1 1 +#endif + +/* GL_OES_stencil4 */ +#ifndef GL_OES_stencil4 +#define GL_OES_stencil4 1 +#endif + +/* GL_OES_stencil8 */ +#ifndef GL_OES_stencil8 +#define GL_OES_stencil8 1 +#endif + +/* GL_OES_stencil_wrap */ +#ifndef GL_OES_stencil_wrap +#define GL_OES_stencil_wrap 1 +#endif + +/* GL_OES_texture_cube_map */ +#ifndef GL_OES_texture_cube_map +#define GL_OES_texture_cube_map 1 +#ifdef GL_GLEXT_PROTOTYPES +GL_API void GL_APIENTRY glTexGenfOES (GLenum coord, GLenum pname, GLfloat param); +GL_API void GL_APIENTRY glTexGenfvOES (GLenum coord, GLenum pname, const GLfloat *params); +GL_API void GL_APIENTRY glTexGeniOES (GLenum coord, GLenum pname, GLint param); +GL_API void GL_APIENTRY glTexGenivOES (GLenum coord, GLenum pname, const GLint *params); +GL_API void GL_APIENTRY glTexGenxOES (GLenum coord, GLenum pname, GLfixed param); +GL_API void GL_APIENTRY glTexGenxvOES (GLenum coord, GLenum pname, const GLfixed *params); +GL_API void GL_APIENTRY glGetTexGenfvOES (GLenum coord, GLenum pname, GLfloat *params); +GL_API void GL_APIENTRY glGetTexGenivOES (GLenum coord, GLenum pname, GLint *params); +GL_API void GL_APIENTRY glGetTexGenxvOES (GLenum coord, GLenum pname, GLfixed *params); +#endif +typedef void (GL_APIENTRYP PFNGLTEXGENFOESPROC) (GLenum coord, GLenum pname, GLfloat param); +typedef void (GL_APIENTRYP PFNGLTEXGENFVOESPROC) (GLenum coord, GLenum pname, const GLfloat *params); +typedef void (GL_APIENTRYP PFNGLTEXGENIOESPROC) (GLenum coord, GLenum pname, GLint param); +typedef void (GL_APIENTRYP PFNGLTEXGENIVOESPROC) (GLenum coord, GLenum pname, const GLint *params); +typedef void (GL_APIENTRYP PFNGLTEXGENXOESPROC) (GLenum coord, GLenum pname, GLfixed param); +typedef void (GL_APIENTRYP PFNGLTEXGENXVOESPROC) (GLenum coord, GLenum pname, const GLfixed *params); +typedef void (GL_APIENTRYP PFNGLGETTEXGENFVOESPROC) (GLenum coord, GLenum pname, GLfloat *params); +typedef void (GL_APIENTRYP PFNGLGETTEXGENIVOESPROC) (GLenum coord, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETTEXGENXVOESPROC) (GLenum coord, GLenum pname, GLfixed *params); +#endif + +/* GL_OES_texture_env_crossbar */ +#ifndef GL_OES_texture_env_crossbar +#define GL_OES_texture_env_crossbar 1 +#endif + +/* GL_OES_texture_mirrored_repeat */ +#ifndef GL_OES_texture_mirrored_repeat +#define GL_OES_texture_mirrored_repeat 1 +#endif + +/*------------------------------------------------------------------------* + * AMD extension functions + *------------------------------------------------------------------------*/ + +/* GL_AMD_compressed_3DC_texture */ +#ifndef GL_AMD_compressed_3DC_texture +#define GL_AMD_compressed_3DC_texture 1 +#endif + +/* GL_AMD_compressed_ATC_texture */ +#ifndef GL_AMD_compressed_ATC_texture +#define GL_AMD_compressed_ATC_texture 1 +#endif + +/*------------------------------------------------------------------------* + * EXT extension functions + *------------------------------------------------------------------------*/ + +/* GL_EXT_texture_filter_anisotropic */ +#ifndef GL_EXT_texture_filter_anisotropic +#define GL_EXT_texture_filter_anisotropic 1 +#endif + +/*------------------------------------------------------------------------* + * dalvik extension functions + *------------------------------------------------------------------------*/ +#ifdef ANDROID +void glColorPointerBounds(GLint size, GLenum type, GLsizei stride, + const GLvoid *ptr, GLsizei count); +void glNormalPointerBounds(GLenum type, GLsizei stride, + const GLvoid *pointer, GLsizei count); +void glTexCoordPointerBounds(GLint size, GLenum type, + GLsizei stride, const GLvoid *pointer, GLsizei count); +void glVertexPointerBounds(GLint size, GLenum type, + GLsizei stride, const GLvoid *pointer, GLsizei count); +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* __glext_h_ */ + diff --git a/opengl/include/GLES/glplatform.h b/opengl/include/GLES/glplatform.h new file mode 100644 index 0000000000000000000000000000000000000000..0924caeaffe92541620b093f7904054226f41bbd --- /dev/null +++ b/opengl/include/GLES/glplatform.h @@ -0,0 +1,39 @@ +#ifndef __glplatform_h_ +#define __glplatform_h_ + +/* $Revision: 7172 $ on $Date:: 2009-01-09 11:17:41 -0800 #$ */ + +/* + * This document is licensed under the SGI Free Software B License Version + * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ . + */ + +/* Platform-specific types and definitions for OpenGL ES 1.X gl.h + * Last modified on 2008/12/19 + * + * Adopters may modify khrplatform.h and this file to suit their platform. + * You are encouraged to submit all modifications to the Khronos group so that + * they can be included in future versions of this file. Please submit changes + * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla) + * by filing a bug against product "OpenGL-ES" component "Registry". + */ + +#include + +#ifndef GL_API +#define GL_API KHRONOS_APICALL +#endif + +#if defined(ANDROID) + +#define GL_APIENTRY KHRONOS_APIENTRY + +// XXX: this should probably not be here +#define GL_DIRECT_TEXTURE_2D_QUALCOMM 0x7E80 + +// XXX: not sure how this is intended to be used +#define GL_GLEXT_PROTOTYPES + +#endif + +#endif /* __glplatform_h_ */ diff --git a/opengl/include/KHR/khrplatform.h b/opengl/include/KHR/khrplatform.h new file mode 100644 index 0000000000000000000000000000000000000000..4cc27c52da8ff67f0c33219770d9b7c72851a212 --- /dev/null +++ b/opengl/include/KHR/khrplatform.h @@ -0,0 +1,241 @@ +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2009 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Platform-specific types and definitions. + * $Revision: 7244 $ on $Date: 2009-01-20 17:06:59 -0800 (Tue, 20 Jan 2009) $ + * + * Adopters may modify this file to suit their platform. Adopters are + * encouraged to submit platform specific modifications to the Khronos + * group so that they can be included in future versions of this file. + * Please submit changes by sending them to the public Khronos Bugzilla + * (http://khronos.org/bugzilla) by filing a bug against product + * "Khronos (general)" component "Registry". + * + * A predefined template which fills in some of the bug fields can be + * reached using http://tinyurl.com/khrplatform-h-bugreport, but you + * must create a Bugzilla login first. + * + * + * See the Implementer's Guidelines for information about where this file + * should be located on your system. + * http://www.khronos.org/registry/implementers_guide.pdf + * + * + * This file should be included as + * #include + * by the Khronos API header file that uses its types and defines. + * + * The types in this file should only be used to define API-specific types. + * Types defined in this file: + * khronos_int8_t signed 8 bit + * khronos_uint8_t unsigned 8 bit + * khronos_int16_t signed 16 bit + * khronos_uint16_t unsigned 16 bit + * khronos_int32_t signed 32 bit + * khronos_uint32_t unsigned 32 bit + * khronos_int64_t signed 64 bit + * khronos_uint64_t unsigned 64 bit + * khronos_intptr_t signed same number of bits as a pointer + * khronos_uintptr_t unsigned same number of bits as a pointer + * khronos_ssize_t signed size + * khronos_usize_t unsigned size + * khronos_float_t signed 32 bit floating point + * khronos_time_ns_t unsigned 64 bit time in nanoseconds + * khronos_utime_nanoseconds_t unsigned time interval or absolute time in + * nanoseconds + * khronos_stime_nanoseconds_t signed time interval in nanoseconds + * + * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. + * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. + * + * + * Macros defined in this file: + * KHRONOS_APICALL + * KHRONOS_APIENTRY + * KHRONOS_APIATTRIBUTES + * These may be used in function prototypes as: + * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( + * int arg1, + * int arg2) KHRONOS_APIATTRIBUTES; + */ + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(_WIN32) && !defined(__SCITECH_SNAP__) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + + +#endif /* __khrplatform_h_ */ diff --git a/opengl/java/android/opengl/Matrix.java b/opengl/java/android/opengl/Matrix.java index 38be6be7dee1010a27b2cef997a10772e363cf96..13ba36e822815ec6174877d1749bcf132f930337 100644 --- a/opengl/java/android/opengl/Matrix.java +++ b/opengl/java/android/opengl/Matrix.java @@ -19,7 +19,7 @@ package android.opengl; /** * Matrix math utilities. These methods operate on OpenGL ES format * matrices and vectors stored in float arrays. - * + * * Matrices are 4 x 4 column-vector matrices stored in column-major * order: *
              @@ -28,7 +28,7 @@ package android.opengl;
                *  m[offset +  2] m[offset +  6] m[offset + 10] m[offset + 14]
                *  m[offset +  3] m[offset +  7] m[offset + 11] m[offset + 15]
                * 
              - * + * * Vectors are 4 row x 1 column column-vectors stored in order: *
                * v[offset + 0]
              @@ -45,11 +45,11 @@ public class Matrix {
                    * matrix multiplication works, the result matrix will have the same
                    * effect as first multiplying by the rhs matrix, then multiplying by
                    * the lhs matrix. This is the opposite of what you might expect.
              -     * 
              +     *
                    * The same float array may be passed for result, lhs, and/or rhs. However,
                    * the result element values are undefined if the result elements overlap
                    * either the lhs or rhs elements.
              -     * 
              +     *
                    * @param result The float array that holds the result.
                    * @param resultOffset The offset into the result array where the result is
                    *        stored.
              @@ -57,7 +57,7 @@ public class Matrix {
                    * @param lhsOffset The offset into the lhs array where the lhs is stored
                    * @param rhs The float array that holds the right-hand-side matrix.
                    * @param rhsOffset The offset into the rhs array where the rhs is stored.
              -     * 
              +     *
                    * @throws IllegalArgumentException if result, lhs, or rhs are null, or if
                    * resultOffset + 16 > result.length or lhsOffset + 16 > lhs.length or
                    * rhsOffset + 16 > rhs.length.
              @@ -68,11 +68,11 @@ public class Matrix {
                   /**
                    * Multiply a 4 element vector by a 4x4 matrix and store the result in a 4
                    * element column vector. In matrix notation: result = lhs x rhs
              -     * 
              +     *
                    * The same float array may be passed for resultVec, lhsMat, and/or rhsVec.
                    * However, the resultVec element values are undefined if the resultVec
                    * elements overlap either the lhsMat or rhsVec elements.
              -     * 
              +     *
                    * @param resultVec The float array that holds the result vector.
                    * @param resultVecOffset The offset into the result array where the result
                    *        vector is stored.
              @@ -90,10 +90,10 @@ public class Matrix {
                   public static native void multiplyMV(float[] resultVec,
                           int resultVecOffset, float[] lhsMat, int lhsMatOffset,
                           float[] rhsVec, int rhsVecOffset);
              -    
              +
                   /**
                    * Transposes a 4 x 4 matrix.
              -     * 
              +     *
                    * @param mTrans the array that holds the output inverted matrix
                    * @param mTransOffset an offset into mInv where the inverted matrix is
                    *        stored.
              @@ -113,7 +113,7 @@ public class Matrix {
               
                   /**
                    * Inverts a 4 x 4 matrix.
              -     * 
              +     *
                    * @param mInv the array that holds the output inverted matrix
                    * @param mInvOffset an offset into mInv where the inverted matrix is
                    *        stored.
              @@ -220,7 +220,7 @@ public class Matrix {
               
                   /**
                    * Computes an orthographic projection matrix.
              -     * 
              +     *
                    * @param m returns the result
                    * @param mOffset
                    * @param left
              @@ -269,8 +269,8 @@ public class Matrix {
                       m[mOffset + 9] = 0.0f;
                       m[mOffset + 11] = 0.0f;
                   }
              -    
              -    
              +
              +
                   /**
                    * Define a projection matrix in terms of six clip planes
                    * @param m the float array that holds the perspective matrix
              @@ -283,7 +283,7 @@ public class Matrix {
                    * @param near
                    * @param far
                    */
              -    
              +
                   public static void frustumM(float[] m, int offset,
                           float left, float right, float bottom, float top,
                           float near, float far) {
              @@ -331,7 +331,7 @@ public class Matrix {
               
                   /**
                    * Computes the length of a vector
              -     * 
              +     *
                    * @param x x coordinate of a vector
                    * @param y y coordinate of a vector
                    * @param z z coordinate of a vector
              @@ -340,7 +340,7 @@ public class Matrix {
                   public static float length(float x, float y, float z) {
                       return (float) Math.sqrt(x * x + y * y + z * z);
                   }
              - 
              +
                   /**
                    * Sets matrix m to the identity matrix.
                    * @param sm returns the result
              @@ -356,7 +356,7 @@ public class Matrix {
                   }
               
                   /**
              -     * Scales matrix  m by sx, sy, and sz, putting the result in sm
              +     * Scales matrix  m by x, y, and z, putting the result in sm
                    * @param sm returns the result
                    * @param smOffset index into sm where the result matrix starts
                    * @param m source matrix
              @@ -395,9 +395,9 @@ public class Matrix {
                           m[ 8 + mi] *= z;
                       }
                   }
              -    
              +
                   /**
              -     * Translates matrix m by sx, sy, and sz, putting the result in tm
              +     * Translates matrix m by x, y, and z, putting the result in tm
                    * @param tm returns the result
                    * @param tmOffset index into sm where the result matrix starts
                    * @param m source matrix
              @@ -409,6 +409,9 @@ public class Matrix {
                   public static void translateM(float[] tm, int tmOffset,
                           float[] m, int mOffset,
                           float x, float y, float z) {
              +        for (int i=0 ; i<12 ; i++) {
              +            tm[tmOffset + i] = m[mOffset + i];
              +        }
                       for (int i=0 ; i<4 ; i++) {
                           int tmi = tmOffset + i;
                           int mi = mOffset + i;
              @@ -416,9 +419,9 @@ public class Matrix {
                               m[12 + mi];
                       }
                   }
              - 
              +
                   /**
              -     * Translates matrix m by sx, sy, and sz in place.
              +     * Translates matrix m by x, y, and z in place.
                    * @param m matrix
                    * @param mOffset index into m where the matrix starts
                    * @param x translation factor x
              @@ -433,7 +436,7 @@ public class Matrix {
                           m[12 + mi] += m[mi] * x + m[4 + mi] * y + m[8 + mi] * z;
                       }
                   }
              -    
              +
                   /**
                    * Rotates matrix m by angle a (in degrees) around the axis (x, y, z)
                    * @param rm returns the result
              @@ -452,7 +455,7 @@ public class Matrix {
                       setRotateM(r, 0, a, x, y, z);
                       multiplyMM(rm, rmOffset, m, mOffset, r, 0);
                   }
              -    
              +
                   /**
                    * Rotates matrix m in place by angle a (in degrees)
                    * around the axis (x, y, z)
              @@ -470,7 +473,7 @@ public class Matrix {
                       multiplyMM(temp, 16, m, mOffset, temp, 0);
                       System.arraycopy(temp, 16, m, mOffset, 16);
                   }
              -    
              +
                   /**
                    * Rotates matrix m by angle a (in degrees) around the axis (x, y, z)
                    * @param rm returns the result
              @@ -524,7 +527,7 @@ public class Matrix {
                           float zx = z * x;
                           float xs = x * s;
                           float ys = y * s;
              -            float zs = z * s;       
              +            float zs = z * s;
                           rm[rmOffset +  0] = x*x*nc +  c;
                           rm[rmOffset +  4] =  xy*nc - zs;
                           rm[rmOffset +  8] =  zx*nc + ys;
              @@ -536,7 +539,7 @@ public class Matrix {
                           rm[rmOffset + 10] = z*z*nc +  c;
                       }
                   }
              -    
              +
                   /**
                    * Converts Euler angles to a rotation matrix
                    * @param rm returns the result
              @@ -558,7 +561,7 @@ public class Matrix {
                       float sz = (float) Math.sin(z);
                       float cxsy = cx * sy;
                       float sxsy = sx * sy;
              -        
              +
                       rm[rmOffset + 0]  =   cy * cz;
                       rm[rmOffset + 1]  =  -cy * sz;
                       rm[rmOffset + 2]  =   sy;
              diff --git a/opengl/java/android/opengl/Visibility.java b/opengl/java/android/opengl/Visibility.java
              index b8021604d13bf8dabc460e8d2995b2a2206dadcc..40e446f67dbbee3f67daf9b7743af14a8dbd8b55 100644
              --- a/opengl/java/android/opengl/Visibility.java
              +++ b/opengl/java/android/opengl/Visibility.java
              @@ -17,7 +17,6 @@
               package android.opengl;
               
               /**
              - * {@hide}
                * A collection of utility methods for computing the visibility of triangle
                * meshes.
                *
              diff --git a/opengl/libGLES_CM/Android.mk b/opengl/libGLES_CM/Android.mk
              deleted file mode 100644
              index e350e0225c434cfbd6dec2de2e14fb9426fce9ae..0000000000000000000000000000000000000000
              --- a/opengl/libGLES_CM/Android.mk
              +++ /dev/null
              @@ -1,24 +0,0 @@
              -LOCAL_PATH:= $(call my-dir)
              -
              -#
              -# Build the wrapper OpenGL ES library
              -#
              -
              -include $(CLEAR_VARS)
              -
              -LOCAL_SRC_FILES:= gl_wrapper.cpp.arm gl_logger.cpp
              -
              -LOCAL_SHARED_LIBRARIES += libcutils libutils libui
              -LOCAL_LDLIBS := -lpthread -ldl
              -LOCAL_MODULE:= libGLES_CM
              -
              -# needed on sim build because of weird logging issues
              -ifeq ($(TARGET_SIMULATOR),true)
              -else
              -    LOCAL_SHARED_LIBRARIES += libdl
              -    # we need to access the Bionic private header 
              -    LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../bionic/libc/private
              -endif
              -
              -include $(BUILD_SHARED_LIBRARY)
              -
              diff --git a/opengl/libagl/egl.cpp b/opengl/libagl/egl.cpp
              index 3e8dca958dc9230c1a1c1aab2d7f06fe1bc793ad..5b90bf03fd611bb35a95382e2127ec7de59b079e 100644
              --- a/opengl/libagl/egl.cpp
              +++ b/opengl/libagl/egl.cpp
              @@ -33,7 +33,10 @@
               
               #include 
               
              -#include 
              +#include 
              +#include 
              +#include 
              +#include 
               
               #include 
               #include 
              @@ -149,7 +152,6 @@ struct egl_surface_t
                   virtual     EGLint      getRefreshRate() const;
                   virtual     EGLint      getSwapBehavior() const;
                   virtual     EGLBoolean  swapBuffers();
              -    virtual     EGLBoolean  swapRectangle(EGLint l, EGLint t, EGLint w, EGLint h);
               protected:
                   GGLSurface              depth;
               };
              @@ -171,10 +173,6 @@ egl_surface_t::~egl_surface_t()
               EGLBoolean egl_surface_t::swapBuffers() {
                   return EGL_FALSE;
               }
              -EGLBoolean egl_surface_t::swapRectangle(
              -        EGLint l, EGLint t, EGLint w, EGLint h) {
              -    return EGL_FALSE;
              -}
               EGLint egl_surface_t::getHorizontalResolution() const {
                   return (0 * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
               }
              @@ -201,7 +199,6 @@ struct egl_window_surface_t : public egl_surface_t
               
                   virtual     bool        isValid() const { return nativeWindow->magic == 0x600913; }    
                   virtual     EGLBoolean  swapBuffers();
              -    virtual     EGLBoolean  swapRectangle(EGLint l, EGLint t, EGLint w, EGLint h);
                   virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
                   virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
                   virtual     EGLint      getWidth() const    { return nativeWindow->width;  }
              @@ -243,7 +240,6 @@ EGLBoolean egl_window_surface_t::swapBuffers()
                   if (flags & EGL_NATIVES_FLAG_SIZE_CHANGED) {
                       // TODO: we probably should reset the swap rect here
                       // if the window size has changed
              -        //    window->setSwapRectangle(Rect(info.w, info.h));
                       if (depth.data) {
                           free(depth.data);
                           depth.width   = nativeWindow->width;
              @@ -259,12 +255,6 @@ EGLBoolean egl_window_surface_t::swapBuffers()
                   return EGL_TRUE;
               }
               
              -EGLBoolean egl_window_surface_t::swapRectangle(
              -        EGLint l, EGLint t, EGLint w, EGLint h)
              -{
              -    nativeWindow->setSwapRectangle(nativeWindow, l, t, w, h);
              -    return EGL_TRUE;
              -}
               EGLBoolean egl_window_surface_t::bindDrawSurface(ogles_context_t* gl)
               {
                   GGLSurface buffer;
              @@ -473,24 +463,21 @@ struct config_management_t {
               
               // ----------------------------------------------------------------------------
               
              +#define VERSION_MAJOR 1
              +#define VERSION_MINOR 2
               static char const * const gVendorString     = "Google Inc.";
               static char const * const gVersionString    = "1.2 Android Driver";
               static char const * const gClientApiString  = "OpenGL ES";
              -static char const * const gExtensionsString =
              -    "EGL_ANDROID_swap_rectangle"                " "
              -    "EGL_ANDROID_copy_front_to_back"            " "
              -    "EGL_ANDROID_get_render_buffer_address"
              -    ;
              +static char const * const gExtensionsString = "";
               
               // ----------------------------------------------------------------------------
               
               struct extention_map_t {
                   const char * const name;
              -    void (*address)(void);
              +    __eglMustCastToProperFunctionPointerType address;
               };
               
               static const extention_map_t gExtentionMap[] = {
              -    { "eglSwapRectangleANDROID",    (void(*)())&eglSwapRectangleANDROID },
                   { "glDrawTexsOES",              (void(*)())&glDrawTexsOES },
                   { "glDrawTexiOES",              (void(*)())&glDrawTexiOES },
                   { "glDrawTexfOES",              (void(*)())&glDrawTexfOES },
              @@ -1017,8 +1004,8 @@ EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
                   }
               
                   if (res == EGL_TRUE) {
              -        if (major != NULL) *major = 1;
              -        if (minor != NULL) *minor = 2;
              +        if (major != NULL) *major = VERSION_MAJOR;
              +        if (minor != NULL) *minor = VERSION_MINOR;
                   }
                   return res;
               }
              @@ -1554,15 +1541,3 @@ void (*eglGetProcAddress (const char *procname))()
                   }
                   return NULL;
               }
              -
              -EGLBoolean eglSwapRectangleANDROID(
              -        EGLDisplay dpy, EGLSurface draw,
              -        EGLint l, EGLint t, EGLint w, EGLint h)
              -{    
              -    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
              -        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
              -    egl_surface_t* surface = (egl_surface_t*)draw;
              -    if (surface->dpy != dpy)
              -        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
              -    return surface->swapRectangle(l, t, w, h);
              -}
              diff --git a/opengl/libagl/state.cpp b/opengl/libagl/state.cpp
              index c2f9f12356ba12d4502d013cd3336237c6133f3f..5cbabea1f8a8e547fcd33272d02547c90c0ca840 100644
              --- a/opengl/libagl/state.cpp
              +++ b/opengl/libagl/state.cpp
              @@ -403,12 +403,6 @@ void glGetIntegerv(GLenum pname, GLint *params)
                   case GL_IMPLEMENTATION_COLOR_READ_TYPE_OES:
                       params[0] = GL_UNSIGNED_SHORT_5_6_5;
                       break;
              -    case GL_MAX_ELEMENTS_INDICES:
              -        params[0] = 65536;
              -        break;
              -    case GL_MAX_ELEMENTS_VERTICES:
              -        params[0] = 0x7FFFFFFF;
              -        break;
                   case GL_MAX_LIGHTS:
                       params[0] = OGLES_MAX_LIGHTS;
                       break;
              diff --git a/opengl/libagl/texture.cpp b/opengl/libagl/texture.cpp
              index 6b2640a720d358c1d01af0f05853b12bd8ebe099..b6f534b7ea5068ca28aa017bda2b9d568bb0b6b1 100644
              --- a/opengl/libagl/texture.cpp
              +++ b/opengl/libagl/texture.cpp
              @@ -526,7 +526,7 @@ void generateMipmap(ogles_context_t* c, GLint level)
               static void texParameterx(
                       GLenum target, GLenum pname, GLfixed param, ogles_context_t* c)
               {
              -    if (target != GGL_TEXTURE_2D) {
              +    if (target != GL_TEXTURE_2D) {
                       ogles_error(c, GL_INVALID_ENUM);
                       return;
                   }
              @@ -534,8 +534,7 @@ static void texParameterx(
                   EGLTextureObject* textureObject = c->textures.tmu[c->textures.active].texture;    
                   switch (pname) {
                   case GL_TEXTURE_WRAP_S:
              -        if ((param == GL_CLAMP) ||
              -            (param == GL_REPEAT) ||
              +        if ((param == GL_REPEAT) ||
                           (param == GL_CLAMP_TO_EDGE)) {
                           textureObject->wraps = param;
                       } else {
              @@ -543,9 +542,8 @@ static void texParameterx(
                       }
                       break;
                   case GL_TEXTURE_WRAP_T:
              -        if ((param == GGL_CLAMP) ||
              -            (param == GGL_REPEAT) ||
              -            (param == GGL_CLAMP_TO_EDGE)) {
              +        if ((param == GL_REPEAT) ||
              +            (param == GL_CLAMP_TO_EDGE)) {
                           textureObject->wrapt = param;
                       } else {
                           goto invalid_enum;
              @@ -1006,7 +1004,7 @@ void glCompressedTexImage2D(
               
               
               void glTexImage2D(
              -        GLenum target, GLint level, GLenum internalformat,
              +        GLenum target, GLint level, GLint internalformat,
                       GLsizei width, GLsizei height, GLint border,
                       GLenum format, GLenum type, const GLvoid *pixels)
               {
              diff --git a/opengl/libs/Android.mk b/opengl/libs/Android.mk
              new file mode 100644
              index 0000000000000000000000000000000000000000..2ecc7768cac25f4d7cfd08ec8b196d885f26e6ff
              --- /dev/null
              +++ b/opengl/libs/Android.mk
              @@ -0,0 +1,53 @@
              +LOCAL_PATH:= $(call my-dir)
              +
              +#
              +# Build META EGL library
              +#
              +
              +include $(CLEAR_VARS)
              +
              +LOCAL_SRC_FILES:= 	\
              +	EGL/egl.cpp 		\
              +	EGL/gpu.cpp			\
              +#
              +
              +LOCAL_SHARED_LIBRARIES += libcutils libutils libui
              +LOCAL_LDLIBS := -lpthread -ldl
              +LOCAL_MODULE:= libEGL
              +
              +# needed on sim build because of weird logging issues
              +ifeq ($(TARGET_SIMULATOR),true)
              +else
              +    LOCAL_SHARED_LIBRARIES += libdl
              +    # we need to access the Bionic private header 
              +    LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../bionic/libc/private
              +endif
              +
              +include $(BUILD_SHARED_LIBRARY)
              +
              +
              +
              +#
              +# Build the wrapper OpenGL ES library
              +#
              +
              +include $(CLEAR_VARS)
              +
              +LOCAL_SRC_FILES:= 	\
              +	GLES_CM/gl.cpp.arm 		\
              +	GLES_CM/gl_logger.cpp 	\
              +#
              +
              +LOCAL_SHARED_LIBRARIES += libcutils libutils libui libEGL
              +LOCAL_LDLIBS := -lpthread -ldl
              +LOCAL_MODULE:= libGLESv1_CM
              +
              +# needed on sim build because of weird logging issues
              +ifeq ($(TARGET_SIMULATOR),true)
              +else
              +    LOCAL_SHARED_LIBRARIES += libdl
              +    # we need to access the Bionic private header 
              +    LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../bionic/libc/private
              +endif
              +
              +include $(BUILD_SHARED_LIBRARY)
              diff --git a/opengl/libGLES_CM/gl_wrapper.cpp b/opengl/libs/EGL/egl.cpp
              similarity index 71%
              rename from opengl/libGLES_CM/gl_wrapper.cpp
              rename to opengl/libs/EGL/egl.cpp
              index 319753570d1a2469742332d5b8a75f19aed8caa7..687c8bc1f7a81e1458e50a1b510bc22a8904c548 100644
              --- a/opengl/libGLES_CM/gl_wrapper.cpp
              +++ b/opengl/libs/EGL/egl.cpp
              @@ -27,31 +27,22 @@
               #include 
               #endif
               
              -#include 
              +#include 
              +#include 
              +#include 
              +#include 
               
               #include 
               #include 
               #include 
               #include 
               
              -#include 
              -#include 
              -#include 
              -#include 
              -#include 
              -#include 
              +#include 
               
              -#include 
              -#include 
              +#include "hooks.h"
              +#include "egl_impl.h"
               
              -#include "gl_logger.h"
               
              -#undef NELEM
              -
              -#define GL_LOGGER                   0
              -#define USE_SLOW_BINDING            0
              -#define NELEM(x)                    (sizeof(x)/sizeof(*(x)))
              -#define MAX_NUMBER_OF_GL_EXTENSIONS 32
               #define MAKE_CONFIG(_impl, _index)  ((EGLConfig)(((_impl)<<24) | (_index)))
               #define setError(_e, _r) setErrorEtc(__FUNCTION__, __LINE__, _e, _r)
               
              @@ -59,26 +50,12 @@
               namespace android {
               // ----------------------------------------------------------------------------
               
              -//  EGLDisplay are global, not attached to a given thread
              -static const unsigned int NUM_DISPLAYS = 1;
              -static const unsigned int IMPL_HARDWARE                 = 0;
              -static const unsigned int IMPL_SOFTWARE                 = 1;
              -static const unsigned int IMPL_HARDWARE_CONTEXT_LOST    = 2;
              -static const unsigned int IMPL_SOFTWARE_CONTEXT_LOST    = 3;
              -static const unsigned int IMPL_NO_CONTEXT               = 4;
              -
              -// ----------------------------------------------------------------------------
              -
              -struct gl_hooks_t;
              -
              -struct egl_connection_t
              -{
              -    void volatile *     dso;
              -    gl_hooks_t *        hooks;
              -    EGLint              major;
              -    EGLint              minor;
              -    int                 unavailable;
              -};
              +#define VERSION_MAJOR 1
              +#define VERSION_MINOR 4
              +static char const * const gVendorString     = "Android";
              +static char const * const gVersionString    = "1.31 Android META-EGL";
              +static char const * const gClientApiString  = "OpenGL ES";
              +static char const * const gExtensionString  = "";
               
               template 
               struct egl_object_t
              @@ -103,7 +80,6 @@ struct egl_display_t : public egl_object_t<'_dpy'>
                       char const * version;
                       char const * clientApi;
                       char const * extensions;
              -        char const * extensions_config;
                   };
                   strings_t   queryString[2];
               };
              @@ -152,82 +128,45 @@ struct tls_t
                   EGLContext  ctx;
               };
               
              +static void gl_unimplemented() {
              +    LOGE("called unimplemented OpenGL ES API");
              +}
               
              +// ----------------------------------------------------------------------------
               // GL / EGL hooks
              +// ----------------------------------------------------------------------------
               
              -typedef void(*proc_t)();
              -
              -struct gl_hooks_t {
              -    struct gl_t {
              -        #define GL_ENTRY(_r, _api, ...) _r (*_api)(__VA_ARGS__);
              -        #include "gl_entries.cpp"
              -        #undef GL_ENTRY
              -    } gl;
              -    struct egl_t {
              -        #define EGL_ENTRY(_r, _api, ...) _r (*_api)(__VA_ARGS__);
              -        #include "egl_entries.cpp"
              -        #undef EGL_ENTRY
              -    } egl;
              -    struct gl_ext_t {
              -        void (*extensions[MAX_NUMBER_OF_GL_EXTENSIONS])(void);
              -    } ext;
              -};
              +#undef GL_ENTRY
              +#undef EGL_ENTRY
              +#define GL_ENTRY(_r, _api, ...) #_api,
              +#define EGL_ENTRY(_r, _api, ...) #_api,
               
               static char const * const gl_names[] = {
              -    #define GL_ENTRY(_r, _api, ...) #_api,
              -    #include "gl_entries.cpp"
              -    #undef GL_ENTRY
              +    #include "gl_entries.in"
                   NULL
               };
               
               static char const * const egl_names[] = {
              -    #define EGL_ENTRY(_r, _api, ...) #_api,
              -    #include "egl_entries.cpp"
              -    #undef EGL_ENTRY
              +    #include "egl_entries.in"
                   NULL
               };
               
              -static void gl_unimplemented() {
              -    LOGE("called unimplemented OpenGL ES API");
              -}
              +#undef GL_ENTRY
              +#undef EGL_ENTRY
               
               // ----------------------------------------------------------------------------
               
              -static egl_connection_t gEGLImpl[2];
              +egl_connection_t gEGLImpl[2];
               static egl_display_t gDisplay[NUM_DISPLAYS];
              -static gl_hooks_t gHooks[5];
               static pthread_mutex_t gThreadLocalStorageKeyMutex = PTHREAD_MUTEX_INITIALIZER;
               static pthread_key_t gEGLThreadLocalStorageKey = -1;
               
               // ----------------------------------------------------------------------------
               
              -#if defined(HAVE_ANDROID_OS) && !USE_SLOW_BINDING && !GL_LOGGER
              +gl_hooks_t gHooks[IMPL_NUM_IMPLEMENTATIONS];
              +pthread_key_t gGLWrapperKey = -1;
               
              -/* special private C library header */
              -#include 
              -// We have a dedicated TLS slot in bionic
              -static inline void setGlThreadSpecific(gl_hooks_t const *value) {
              -    ((uint32_t *)__get_tls())[TLS_SLOT_OPENGL_API] = (uint32_t)value;
              -}
              -static gl_hooks_t const* getGlThreadSpecific() {
              -    gl_hooks_t const* hooks = (gl_hooks_t const *)(((unsigned const *)__get_tls())[TLS_SLOT_OPENGL_API]);
              -    if (hooks) return hooks;
              -    return &gHooks[IMPL_NO_CONTEXT];
              -}
              -
              -#else
              -
              -static pthread_key_t gGLWrapperKey = -1;
              -static inline void setGlThreadSpecific(gl_hooks_t const *value) {
              -    pthread_setspecific(gGLWrapperKey, value);
              -}
              -static gl_hooks_t const* getGlThreadSpecific() {
              -    gl_hooks_t const* hooks =  static_cast(pthread_getspecific(gGLWrapperKey));
              -    if (hooks) return hooks;
              -    return &gHooks[IMPL_NO_CONTEXT];
              -}
              -
              -#endif
              +// ----------------------------------------------------------------------------
               
               static __attribute__((noinline))
               const char *egl_strerror(EGLint err)
              @@ -322,170 +261,14 @@ EGLContext getContext() {
                   return tls->ctx;
               }
               
              -/*****************************************************************************/
              -
              -/*
              - * we provide our own allocators for the GPU regions, these
              - * allocators go through surfaceflinger 
              - */
              -
              -static Mutex                            gRegionsLock;
              -static request_gpu_t                    gRegions;
              -static sp             gSurfaceManager;
              -ISurfaceComposer*                       GLES_localSurfaceManager = 0;
              -
              -const sp& getSurfaceFlinger()
              -{
              -    Mutex::Autolock _l(gRegionsLock);
              -
              -    /*
              -     * There is a little bit of voodoo magic here. We want to access
              -     * surfaceflinger for allocating GPU regions, however, when we are
              -     * running as part of surfaceflinger, we want to bypass the
              -     * service manager because surfaceflinger might not be registered yet.
              -     * SurfaceFlinger will populate "GLES_localSurfaceManager" with its
              -     * own address, so we can just use that.
              -     */
              -    if (gSurfaceManager == 0) {
              -        if (GLES_localSurfaceManager) {
              -            // we're running in SurfaceFlinger's context
              -            gSurfaceManager =  GLES_localSurfaceManager;
              -        } else {
              -            // we're a remote process or not part of surfaceflinger,
              -            // go through the service manager
              -            sp sm = defaultServiceManager();
              -            if (sm != NULL) {
              -                sp binder = sm->getService(String16("SurfaceFlinger"));
              -                gSurfaceManager = interface_cast(binder);
              -            }
              -        }
              -    }
              -    return gSurfaceManager;
              -}
              -
              -class GPURevokeRequester : public BnGPUCallback
              -{
              -public:
              -    virtual void gpuLost() {
              -        LOGD("CONTEXT_LOST: Releasing GPU upon request from SurfaceFlinger.");
              -        gEGLImpl[IMPL_HARDWARE].hooks = &gHooks[IMPL_HARDWARE_CONTEXT_LOST];
              -    }
              -};
              -
              -static sp gRevokerCallback;
              -
              -
              -static request_gpu_t* gpu_acquire(void* user)
              -{
              -    sp server( getSurfaceFlinger() );
              -
              -    Mutex::Autolock _l(gRegionsLock);
              -    if (server == NULL) {
              -        return 0;
              -    }
              -    
              -    ISurfaceComposer::gpu_info_t info;
              -    
              -    if (gRevokerCallback == 0)
              -        gRevokerCallback = new GPURevokeRequester();
              -
              -    status_t err = server->requestGPU(gRevokerCallback, &info);
              -    if (err != NO_ERROR) {
              -        LOGD("requestGPU returned %d", err);
              -        return 0;
              -    }
              -
              -    bool failed = false;
              -    request_gpu_t* gpu = &gRegions;
              -    memset(gpu, 0, sizeof(*gpu));
              -    
              -    if (info.regs != 0) {
              -        sp heap(info.regs->getMemory());
              -        if (heap != 0) {
              -            int fd = heap->heapID();
              -            gpu->regs.fd = fd;
              -            gpu->regs.base = info.regs->pointer(); 
              -            gpu->regs.size = info.regs->size(); 
              -            gpu->regs.user = info.regs.get();
              -#if HAVE_ANDROID_OS
              -            struct pmem_region region;
              -            if (ioctl(fd, PMEM_GET_PHYS, ®ion) >= 0)
              -                gpu->regs.phys = (void*)region.offset;
              -#endif
              -            info.regs->incStrong(gpu);
              -        } else {
              -            LOGE("GPU register handle %p is invalid!", info.regs.get());
              -            failed = true;
              -        }
              -    }
              -
              -    for (size_t i=0 ; i& region(info.regions[i].region);
              -        if (region != 0) {
              -            sp heap(region->getMemory());
              -            if (heap != 0) {
              -                const int fd = heap->heapID();
              -                gpu->gpu[i].fd = fd;
              -                gpu->gpu[i].base = region->pointer(); 
              -                gpu->gpu[i].size = region->size(); 
              -                gpu->gpu[i].user = region.get();
              -                gpu->gpu[i].offset = info.regions[i].reserved;
              -#if HAVE_ANDROID_OS
              -                struct pmem_region reg;
              -                if (ioctl(fd, PMEM_GET_PHYS, ®) >= 0)
              -                    gpu->gpu[i].phys = (void*)reg.offset;
              -#endif
              -                region->incStrong(gpu);
              -            } else {
              -                LOGE("GPU region handle [%d, %p] is invalid!", i, region.get());
              -                failed = true;
              -            }
              -        }
              -    }
              -    
              -    if (failed) {
              -        // something went wrong, clean up everything!
              -        if (gpu->regs.user) {
              -            static_cast(gpu->regs.user)->decStrong(gpu);
              -            for (size_t i=0 ; igpu[i].user) {
              -                    static_cast(gpu->gpu[i].user)->decStrong(gpu);
              -                }
              -            }
              -        }
              -    }
              -    
              -    gpu->count = info.count;
              -    return gpu;
              -}
              -
              -static int gpu_release(void*, request_gpu_t* gpu)
              -{
              -    sp regs;
              -
              -    { // scope for lock
              -        Mutex::Autolock _l(gRegionsLock);
              -        regs = static_cast(gpu->regs.user);   
              -        gpu->regs.user = 0;
              -        if (regs != 0) regs->decStrong(gpu);
              -        
              -        for (int i=0 ; icount ; i++) {
              -            sp r(static_cast(gpu->gpu[i].user));
              -            gpu->gpu[i].user = 0;
              -            if (r != 0) r->decStrong(gpu);
              -        }
              -    }
              -    
              -    // there is a special transaction to relinquish the GPU
              -    // (it will happen automatically anyway if we don't do this)
              -    Parcel data, reply;
              -    // NOTE: this transaction does not require an interface token
              -    regs->asBinder()->transact(1000, data, &reply);
              -    return 1;
              -}
               
               /*****************************************************************************/
               
              +class ISurfaceComposer;
              +const sp& getSurfaceFlinger();
              +request_gpu_t* gpu_acquire(void* user);
              +int gpu_release(void*, request_gpu_t* gpu);
              +
               static __attribute__((noinline))
               void *load_driver(const char* driver, gl_hooks_t* hooks)
               {
              @@ -576,18 +359,12 @@ static int cmp_configs(const void* a, const void *b)
                   return c0c1 ? 1 : 0);
               }
               
              -static char const * const gVendorString     = "Android";
              -static char const * const gVersionString    = "1.3 Android META-EGL";
              -static char const * const gClientApiString  = "OpenGL ES";
              -
               struct extention_map_t {
                   const char* name;
              -    void (*address)(void);
              +    __eglMustCastToProperFunctionPointerType address;
               };
               
               static const extention_map_t gExtentionMap[] = {
              -    { "eglSwapRectangleANDROID",         (void(*)())&eglSwapRectangleANDROID },
              -    { "eglQueryStringConfigANDROID",     (void(*)())&eglQueryStringConfigANDROID },
               };
               
               static extention_map_t gGLExtentionMap[MAX_NUMBER_OF_GL_EXTENSIONS];
              @@ -603,110 +380,19 @@ static void(*findProcAddress(const char* name,
                   return NULL;
               }
               
              -// ----------------------------------------------------------------------------
              -}; // namespace android
              -// ----------------------------------------------------------------------------
              -
              -using namespace android;
              -
              -
              -// ----------------------------------------------------------------------------
              -// extensions for the framework
              -// ----------------------------------------------------------------------------
              -
              -void glColorPointerBounds(GLint size, GLenum type, GLsizei stride,
              -        const GLvoid *ptr, GLsizei count) {
              -    glColorPointer(size, type, stride, ptr);
              -}
              -void glNormalPointerBounds(GLenum type, GLsizei stride,
              -        const GLvoid *pointer, GLsizei count) {
              -    glNormalPointer(type, stride, pointer);
              -}
              -void glTexCoordPointerBounds(GLint size, GLenum type,
              -        GLsizei stride, const GLvoid *pointer, GLsizei count) {
              -    glTexCoordPointer(size, type, stride, pointer);
              -}
              -void glVertexPointerBounds(GLint size, GLenum type,
              -        GLsizei stride, const GLvoid *pointer, GLsizei count) {
              -    glVertexPointer(size, type, stride, pointer);
              -}
              -
              -
              -// ----------------------------------------------------------------------------
              -// Actual GL wrappers
              -// ----------------------------------------------------------------------------
              -
              -#if __OPTIMIZE__ && defined(__arm__) && !defined(__thumb__) && !USE_SLOW_BINDING && !GL_LOGGER
              -
              -    #define API_ENTRY(_api) __attribute__((naked)) _api
              -    #define CALL_GL_API(_api, ...)                              \
              -         asm volatile(                                          \
              -            "mov   r12, #0xFFFF0FFF   \n"                       \
              -            "ldr   r12, [r12, #-15]   \n"                       \
              -            "ldr   r12, [r12, %[tls]] \n"                       \
              -            "cmp   r12, #0            \n"                       \
              -            "ldrne pc,  [r12, %[api]] \n"                       \
              -            "bx    lr                 \n"                       \
              -            :                                                   \
              -            : [tls] "J"(TLS_SLOT_OPENGL_API*4),                 \
              -              [api] "J"(__builtin_offsetof(gl_hooks_t, gl._api))    \
              -            :                                                   \
              -            );
              -    
              -    #define CALL_GL_API_RETURN(_api, ...) \
              -        CALL_GL_API(_api, __VA_ARGS__) \
              -        return 0; // placate gcc's warnings. never reached.
              -
              -#else
              -
              -    #define API_ENTRY(_api) _api
              -    #if GL_LOGGER
              -
              -        #define CALL_GL_API(_api, ...)          \
              -            gl_hooks_t::gl_t const * const _c = &getGlThreadSpecific()->gl; \
              -            log_##_api(__VA_ARGS__); \
              -            _c->_api(__VA_ARGS__);
              -        
              -        #define CALL_GL_API_RETURN(_api, ...)   \
              -            gl_hooks_t::gl_t const * const _c = &getGlThreadSpecific()->gl; \
              -            log_##_api(__VA_ARGS__); \
              -            return _c->_api(__VA_ARGS__)
              -
              -    #else
              -
              -        #define CALL_GL_API(_api, ...)          \
              -            gl_hooks_t::gl_t const * const _c = &getGlThreadSpecific()->gl; \
              -            _c->_api(__VA_ARGS__);
              -        
              -        #define CALL_GL_API_RETURN(_api, ...)   \
              -            gl_hooks_t::gl_t const * const _c = &getGlThreadSpecific()->gl; \
              -            return _c->_api(__VA_ARGS__)
              -
              -    #endif
              -
              -#endif
              -
              -#include "gl_api.cpp"
              -
              -#undef API_ENTRY
              -#undef CALL_GL_API
              -#undef CALL_GL_API_RETURN
              -
              -// ----------------------------------------------------------------------------
              -namespace android {
               // ----------------------------------------------------------------------------
               
               static int gl_context_lost() {
              -    setGlThreadSpecific(&gHooks[IMPL_HARDWARE_CONTEXT_LOST]);
              +    setGlThreadSpecific(&gHooks[IMPL_CONTEXT_LOST]);
                   return 0;
               }
               static int egl_context_lost() {
              -    setGlThreadSpecific(&gHooks[IMPL_HARDWARE_CONTEXT_LOST]);
              +    setGlThreadSpecific(&gHooks[IMPL_CONTEXT_LOST]);
                   return EGL_FALSE;
               }
               static EGLBoolean egl_context_lost_swap_buffers(void*, void*) {
                   usleep(100000); // don't use all the CPU
              -    setGlThreadSpecific(&gHooks[IMPL_HARDWARE_CONTEXT_LOST]);
              +    setGlThreadSpecific(&gHooks[IMPL_CONTEXT_LOST]);
                   return EGL_FALSE;
               }
               static GLint egl_context_lost_get_error() {
              @@ -721,11 +407,14 @@ static void gl_no_context() {
               }
               static void early_egl_init(void) 
               {
              -#if !defined(HAVE_ANDROID_OS) || USE_SLOW_BINDING || GL_LOGGER
              +#if !USE_FAST_TLS_KEY
                   pthread_key_create(&gGLWrapperKey, NULL);
               #endif
                   uint32_t addr = (uint32_t)((void*)gl_no_context);
              -    android_memset32((uint32_t*)(void*)&gHooks[IMPL_NO_CONTEXT], addr, sizeof(gHooks[IMPL_NO_CONTEXT]));
              +    android_memset32(
              +            (uint32_t*)(void*)&gHooks[IMPL_NO_CONTEXT], 
              +            addr, 
              +            sizeof(gHooks[IMPL_NO_CONTEXT]));
                   setGlThreadSpecific(&gHooks[IMPL_NO_CONTEXT]);
               }
               
              @@ -802,25 +491,12 @@ static EGLBoolean validate_display_surface(EGLDisplay dpy, EGLSurface surface)
                   return EGL_TRUE;
               }
               
              -static void add_extension(egl_display_t* dp, char const*& p, const char* ext)
              -{
              -    if (!strstr(p, ext)) {
              -        p = (char const*)realloc((void*)p, strlen(p) + 1 + strlen(ext) + 1);
              -        strcat((char*)p, " ");
              -        strcat((char*)p, ext);
              -    }
              -    if (!strstr(dp->extensionsString, ext)) {
              -        char const*& es = dp->extensionsString;
              -        es = (char const*)realloc((void*)es, strlen(es) + 1 + strlen(ext) + 1);
              -        strcat((char*)es, " ");
              -        strcat((char*)es, ext);
              -    }    
              -}
              -
               // ----------------------------------------------------------------------------
               }; // namespace android
               // ----------------------------------------------------------------------------
               
              +using namespace android;
              +
               EGLDisplay eglGetDisplay(NativeDisplayType display)
               {
                   if (sEarlyInitState) {
              @@ -854,38 +530,32 @@ EGLDisplay eglGetDisplay(NativeDisplayType display)
                       property_get("debug.egl.hw", value, "1");
                       if (atoi(value) != 0) {
                           cnx->hooks = &gHooks[IMPL_HARDWARE];
              -            property_get("debug.egl.profiler", value, "0");
              -            if (atoi(value) == 0) {
              -                cnx->dso = load_driver("libhgl.so", cnx->hooks);
              -            } else {
              -                LOGW("Using instrumented h/w OpenGL ES library");
              -                cnx->dso = load_driver("libhgld.so", cnx->hooks);
              -            }
              +            cnx->dso = load_driver("libhgl.so", cnx->hooks);
                       } else {
                           LOGD("3D hardware acceleration is disabled");
                       }
                   }
                   if (cnx->dso && d->dpys[IMPL_HARDWARE]==EGL_NO_DISPLAY) {
                       android_memset32(
              -                (uint32_t*)(void*)&gHooks[IMPL_HARDWARE_CONTEXT_LOST].gl,
              +                (uint32_t*)(void*)&gHooks[IMPL_CONTEXT_LOST].gl,
                               (uint32_t)((void*)gl_context_lost),
              -                sizeof(gHooks[IMPL_HARDWARE_CONTEXT_LOST].gl));
              +                sizeof(gHooks[IMPL_CONTEXT_LOST].gl));
                       android_memset32(
              -                (uint32_t*)(void*)&gHooks[IMPL_HARDWARE_CONTEXT_LOST].egl,
              +                (uint32_t*)(void*)&gHooks[IMPL_CONTEXT_LOST].egl,
                               (uint32_t)((void*)egl_context_lost),
              -                sizeof(gHooks[IMPL_HARDWARE_CONTEXT_LOST].egl));
              +                sizeof(gHooks[IMPL_CONTEXT_LOST].egl));
                       android_memset32(
              -                (uint32_t*)(void*)&gHooks[IMPL_HARDWARE_CONTEXT_LOST].ext,
              +                (uint32_t*)(void*)&gHooks[IMPL_CONTEXT_LOST].ext,
                               (uint32_t)((void*)ext_context_lost),
              -                sizeof(gHooks[IMPL_HARDWARE_CONTEXT_LOST].ext));
              +                sizeof(gHooks[IMPL_CONTEXT_LOST].ext));
               
              -        gHooks[IMPL_HARDWARE_CONTEXT_LOST].egl.eglSwapBuffers =
              +        gHooks[IMPL_CONTEXT_LOST].egl.eglSwapBuffers =
                               egl_context_lost_swap_buffers;
                       
              -        gHooks[IMPL_HARDWARE_CONTEXT_LOST].egl.eglGetError =
              +        gHooks[IMPL_CONTEXT_LOST].egl.eglGetError =
                               egl_context_lost_get_error;
               
              -        gHooks[IMPL_HARDWARE_CONTEXT_LOST].egl.eglTerminate =
              +        gHooks[IMPL_CONTEXT_LOST].egl.eglTerminate =
                               gHooks[IMPL_HARDWARE].egl.eglTerminate;
                       
                       d->dpys[IMPL_HARDWARE] = cnx->hooks->egl.eglGetDisplay(display);
              @@ -913,8 +583,8 @@ EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
                   if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
               
                   if (android_atomic_inc(&dp->refs) > 0) {
              -        if (major != NULL) *major = 1;
              -        if (minor != NULL) *minor = 2;
              +        if (major != NULL) *major = VERSION_MAJOR;
              +        if (minor != NULL) *minor = VERSION_MINOR;
                       return EGL_TRUE;
                   }
                   
              @@ -923,7 +593,7 @@ EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
                   // initialize each EGL and
                   // build our own extension string first, based on the extension we know
                   // and the extension supported by our client implementation
              -    dp->extensionsString = strdup("EGL_ANDROID_query_string_config");
              +    dp->extensionsString = strdup(gExtensionString);
                   for (int i=0 ; i<2 ; i++) {
                       egl_connection_t* const cnx = &gEGLImpl[i];
                       cnx->major = -1;
              @@ -947,54 +617,16 @@ EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
                           dp->queryString[i].clientApi =
                               cnx->hooks->egl.eglQueryString(dp->dpys[i], EGL_CLIENT_APIS);
               
              -            // Dynamically insert extensions we know about
              -            if (cnx->hooks->egl.eglSwapRectangleANDROID)
              -                add_extension(dp, dp->queryString[i].extensions,
              -                        "EGL_ANDROID_swap_rectangle");
              -
              -            if (cnx->hooks->egl.eglQueryStringConfigANDROID)
              -                add_extension(dp, dp->queryString[i].extensions,
              -                        "EGL_ANDROID_query_string_config");
                       } else {
                           LOGD("%d: eglInitialize() failed (%s)", 
                                   i, egl_strerror(cnx->hooks->egl.eglGetError()));
                       }
                   }
               
              -    // Build the extension list that depends on the current config.
              -    // It is the intersection of our extension list and the
              -    // underlying EGL's extensions list
                   EGLBoolean res = EGL_FALSE;
                   for (int i=0 ; i<2 ; i++) {
                       egl_connection_t* const cnx = &gEGLImpl[i];
                       if (cnx->dso && cnx->major>=0 && cnx->minor>=0) {
              -            char const* const their_extensions = dp->queryString[i].extensions;            
              -            char* our_extensions = strdup(dp->extensionsString);
              -            char* const our_extensions_org = our_extensions;
              -            char* extensions_config = (char*)calloc(strlen(our_extensions)+2, 1);
              -            char* p;
              -            do {
              -                p = strchr(our_extensions, ' ');
              -                if (p)  *p++ = 0;
              -                else    p = strchr(our_extensions, 0);
              -                if (strstr(their_extensions, our_extensions)) {
              -                    strcat(extensions_config, our_extensions);
              -                    strcat(extensions_config, " ");
              -                }
              -                our_extensions = p;
              -            } while (*p);
              -            free((void*)our_extensions_org);
              -
              -            // remove the trailing white space
              -            if (extensions_config[0] != 0) {
              -                size_t l = strlen(extensions_config) - 1; // new size
              -                extensions_config[l] = 0; // remove the trailing white space
              -                extensions_config = (char*)realloc(extensions_config, l+1);
              -            } else {
              -                extensions_config = (char*)realloc(extensions_config, 1);
              -            }
              -            dp->queryString[i].extensions_config = extensions_config;
              -
                           EGLint n;
                           if (cnx->hooks->egl.eglGetConfigs(dp->dpys[i], 0, 0, &n)) {
                               dp->configs[i] = (EGLConfig*)malloc(sizeof(EGLConfig)*n);
              @@ -1016,8 +648,8 @@ EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
                   }
               
                   if (res == EGL_TRUE) {
              -        if (major != NULL) *major = 1;
              -        if (minor != NULL) *minor = 2;
              +        if (major != NULL) *major = VERSION_MAJOR;
              +        if (minor != NULL) *minor = VERSION_MINOR;
                       return EGL_TRUE;
                   }
                   return setError(EGL_NOT_INITIALIZED, EGL_FALSE);
              @@ -1042,7 +674,6 @@ EGLBoolean eglTerminate(EGLDisplay dpy)
                            * threads around). */
                           
                           free(dp->configs[i]);
              -            free((void*)dp->queryString[i].extensions_config);
                           free((void*)dp->queryString[i].extensions);
                           dp->numConfigs[i] = 0;
                           dp->dpys[i] = EGL_NO_DISPLAY;
              @@ -1486,7 +1117,7 @@ EGLint eglGetError(void)
               
               void (*eglGetProcAddress(const char *procname))()
               {
              -    void (*addr)();
              +    __eglMustCastToProperFunctionPointerType addr;
                   addr = findProcAddress(procname, gExtentionMap, NELEM(gExtentionMap));
                   if (addr) return addr;
               
              @@ -1570,7 +1201,7 @@ const char* eglQueryString(EGLDisplay dpy, EGLint name)
                       case EGL_VERSION:
                           return gVersionString;
                       case EGL_EXTENSIONS:
              -            return dp->extensionsString;
              +            return gExtensionString;
                       case EGL_CLIENT_APIS:
                           return gClientApiString;
                   }
              @@ -1730,34 +1361,3 @@ EGLSurface eglCreatePbufferFromClientBuffer(
                   }
                   return setError(EGL_BAD_CONFIG, EGL_NO_SURFACE);
               }
              -
              -// ----------------------------------------------------------------------------
              -// Android extentions
              -// ----------------------------------------------------------------------------
              -
              -EGLBoolean eglSwapRectangleANDROID(
              -        EGLDisplay dpy, EGLSurface draw,
              -        EGLint l, EGLint t, EGLint w, EGLint h)
              -{    
              -    if (!validate_display_surface(dpy, draw))
              -        return EGL_FALSE;    
              -    egl_display_t const * const dp = get_display(dpy);
              -    egl_surface_t const * const s = get_surface(draw);
              -    if (s->cnx->hooks->egl.eglSwapRectangleANDROID) {
              -        return s->cnx->hooks->egl.eglSwapRectangleANDROID(
              -                dp->dpys[s->impl], s->surface, l, t, w, h);
              -    }
              -    return setError(EGL_BAD_SURFACE, EGL_FALSE);
              -}
              -
              -const char* eglQueryStringConfigANDROID(
              -        EGLDisplay dpy, EGLConfig config, EGLint name)
              -{
              -    egl_display_t const* dp = 0;
              -    int i=0, index=0;
              -    egl_connection_t* cnx = validate_display_config(dpy, config, dp, i, index);
              -    if (cnx) {
              -        return dp->queryString[i].extensions_config;
              -    }
              -    return setError(EGL_BAD_PARAMETER, (const char *)0);
              -}
              diff --git a/opengl/libs/EGL/gpu.cpp b/opengl/libs/EGL/gpu.cpp
              new file mode 100644
              index 0000000000000000000000000000000000000000..3f9fd63405871a5b5ed453385f854d60891e877c
              --- /dev/null
              +++ b/opengl/libs/EGL/gpu.cpp
              @@ -0,0 +1,212 @@
              +/* 
              + ** Copyright 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.
              + */
              +
              +#define LOG_TAG "EGL"
              +
              +#include 
              +#include 
              +#include 
              +
              +#include 
              +
              +#if HAVE_ANDROID_OS
              +#include 
              +#endif
              +
              +#include 
              +#include 
              +
              +#include 
              +#include 
              +#include 
              +#include 
              +#include 
              +
              +#include 
              +#include 
              +
              +#include "hooks.h"
              +#include "egl_impl.h"
              +
              +// ----------------------------------------------------------------------------
              +namespace android {
              +// ----------------------------------------------------------------------------
              +
              +/*
              + * we provide our own allocators for the GPU regions, these
              + * allocators go through surfaceflinger 
              + */
              +
              +static Mutex                            gRegionsLock;
              +static request_gpu_t                    gRegions;
              +static sp             gSurfaceManager;
              +ISurfaceComposer*                       GLES_localSurfaceManager = 0;
              +
              +extern egl_connection_t gEGLImpl[2];
              +
              +const sp& getSurfaceFlinger()
              +{
              +    Mutex::Autolock _l(gRegionsLock);
              +
              +    /*
              +     * There is a little bit of voodoo magic here. We want to access
              +     * surfaceflinger for allocating GPU regions, however, when we are
              +     * running as part of surfaceflinger, we want to bypass the
              +     * service manager because surfaceflinger might not be registered yet.
              +     * SurfaceFlinger will populate "GLES_localSurfaceManager" with its
              +     * own address, so we can just use that.
              +     */
              +    if (gSurfaceManager == 0) {
              +        if (GLES_localSurfaceManager) {
              +            // we're running in SurfaceFlinger's context
              +            gSurfaceManager =  GLES_localSurfaceManager;
              +        } else {
              +            // we're a remote process or not part of surfaceflinger,
              +            // go through the service manager
              +            sp sm = defaultServiceManager();
              +            if (sm != NULL) {
              +                sp binder = sm->getService(String16("SurfaceFlinger"));
              +                gSurfaceManager = interface_cast(binder);
              +            }
              +        }
              +    }
              +    return gSurfaceManager;
              +}
              +
              +class GPURevokeRequester : public BnGPUCallback
              +{
              +public:
              +    virtual void gpuLost() {
              +        LOGD("CONTEXT_LOST: Releasing GPU upon request from SurfaceFlinger.");
              +        gEGLImpl[IMPL_HARDWARE].hooks = &gHooks[IMPL_CONTEXT_LOST];
              +    }
              +};
              +
              +static sp gRevokerCallback;
              +
              +
              +request_gpu_t* gpu_acquire(void* user)
              +{
              +    sp server( getSurfaceFlinger() );
              +
              +    Mutex::Autolock _l(gRegionsLock);
              +    if (server == NULL) {
              +        return 0;
              +    }
              +    
              +    ISurfaceComposer::gpu_info_t info;
              +    
              +    if (gRevokerCallback == 0)
              +        gRevokerCallback = new GPURevokeRequester();
              +
              +    status_t err = server->requestGPU(gRevokerCallback, &info);
              +    if (err != NO_ERROR) {
              +        LOGD("requestGPU returned %d", err);
              +        return 0;
              +    }
              +
              +    bool failed = false;
              +    request_gpu_t* gpu = &gRegions;
              +    memset(gpu, 0, sizeof(*gpu));
              +    
              +    if (info.regs != 0) {
              +        sp heap(info.regs->getMemory());
              +        if (heap != 0) {
              +            int fd = heap->heapID();
              +            gpu->regs.fd = fd;
              +            gpu->regs.base = info.regs->pointer(); 
              +            gpu->regs.size = info.regs->size(); 
              +            gpu->regs.user = info.regs.get();
              +#if HAVE_ANDROID_OS
              +            struct pmem_region region;
              +            if (ioctl(fd, PMEM_GET_PHYS, ®ion) >= 0)
              +                gpu->regs.phys = (void*)region.offset;
              +#endif
              +            info.regs->incStrong(gpu);
              +        } else {
              +            LOGE("GPU register handle %p is invalid!", info.regs.get());
              +            failed = true;
              +        }
              +    }
              +
              +    for (size_t i=0 ; i& region(info.regions[i].region);
              +        if (region != 0) {
              +            sp heap(region->getMemory());
              +            if (heap != 0) {
              +                const int fd = heap->heapID();
              +                gpu->gpu[i].fd = fd;
              +                gpu->gpu[i].base = region->pointer(); 
              +                gpu->gpu[i].size = region->size(); 
              +                gpu->gpu[i].user = region.get();
              +                gpu->gpu[i].offset = info.regions[i].reserved;
              +#if HAVE_ANDROID_OS
              +                struct pmem_region reg;
              +                if (ioctl(fd, PMEM_GET_PHYS, ®) >= 0)
              +                    gpu->gpu[i].phys = (void*)reg.offset;
              +#endif
              +                region->incStrong(gpu);
              +            } else {
              +                LOGE("GPU region handle [%d, %p] is invalid!", i, region.get());
              +                failed = true;
              +            }
              +        }
              +    }
              +    
              +    if (failed) {
              +        // something went wrong, clean up everything!
              +        if (gpu->regs.user) {
              +            static_cast(gpu->regs.user)->decStrong(gpu);
              +            for (size_t i=0 ; igpu[i].user) {
              +                    static_cast(gpu->gpu[i].user)->decStrong(gpu);
              +                }
              +            }
              +        }
              +    }
              +    
              +    gpu->count = info.count;
              +    return gpu;
              +}
              +
              +int gpu_release(void*, request_gpu_t* gpu)
              +{
              +    sp regs;
              +
              +    { // scope for lock
              +        Mutex::Autolock _l(gRegionsLock);
              +        regs = static_cast(gpu->regs.user);   
              +        gpu->regs.user = 0;
              +        if (regs != 0) regs->decStrong(gpu);
              +        
              +        for (int i=0 ; icount ; i++) {
              +            sp r(static_cast(gpu->gpu[i].user));
              +            gpu->gpu[i].user = 0;
              +            if (r != 0) r->decStrong(gpu);
              +        }
              +    }
              +    
              +    // there is a special transaction to relinquish the GPU
              +    // (it will happen automatically anyway if we don't do this)
              +    Parcel data, reply;
              +    // NOTE: this transaction does not require an interface token
              +    regs->asBinder()->transact(1000, data, &reply);
              +    return 1;
              +}
              +
              +// ----------------------------------------------------------------------------
              +}; // namespace android
              +// ----------------------------------------------------------------------------
              diff --git a/opengl/libs/GLES_CM/gl.cpp b/opengl/libs/GLES_CM/gl.cpp
              new file mode 100644
              index 0000000000000000000000000000000000000000..865cf44362f0a8264919c1740747dd8d26ece908
              --- /dev/null
              +++ b/opengl/libs/GLES_CM/gl.cpp
              @@ -0,0 +1,116 @@
              +/* 
              + ** Copyright 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.
              + */
              +
              +#define LOG_TAG "GLES_CM"
              +
              +#include 
              +#include 
              +#include 
              +
              +#include 
              +
              +#include 
              +#include 
              +
              +#include 
              +#include 
              +
              +#include "hooks.h"
              +
              +using namespace android;
              +
              +// ----------------------------------------------------------------------------
              +// extensions for the framework
              +// ----------------------------------------------------------------------------
              +
              +void glColorPointerBounds(GLint size, GLenum type, GLsizei stride,
              +        const GLvoid *ptr, GLsizei count) {
              +    glColorPointer(size, type, stride, ptr);
              +}
              +void glNormalPointerBounds(GLenum type, GLsizei stride,
              +        const GLvoid *pointer, GLsizei count) {
              +    glNormalPointer(type, stride, pointer);
              +}
              +void glTexCoordPointerBounds(GLint size, GLenum type,
              +        GLsizei stride, const GLvoid *pointer, GLsizei count) {
              +    glTexCoordPointer(size, type, stride, pointer);
              +}
              +void glVertexPointerBounds(GLint size, GLenum type,
              +        GLsizei stride, const GLvoid *pointer, GLsizei count) {
              +    glVertexPointer(size, type, stride, pointer);
              +}
              +
              +// ----------------------------------------------------------------------------
              +// Actual GL entry-points
              +// ----------------------------------------------------------------------------
              +
              +#if GL_LOGGER
              +#   include "gl_logger.h"
              +#   define GL_LOGGER_IMPL(_x) _x
              +#else
              +#   define GL_LOGGER_IMPL(_x)
              +#endif
              +
              +#undef API_ENTRY
              +#undef CALL_GL_API
              +#undef CALL_GL_API_RETURN
              +
              +#if USE_FAST_TLS_KEY
              +
              +    #define API_ENTRY(_api) __attribute__((naked)) _api
              +
              +    #define CALL_GL_API(_api, ...)                              \
              +         asm volatile(                                          \
              +            "mov   r12, #0xFFFF0FFF   \n"                       \
              +            "ldr   r12, [r12, #-15]   \n"                       \
              +            "ldr   r12, [r12, %[tls]] \n"                       \
              +            "cmp   r12, #0            \n"                       \
              +            "ldrne pc,  [r12, %[api]] \n"                       \
              +            "bx    lr                 \n"                       \
              +            :                                                   \
              +            : [tls] "J"(TLS_SLOT_OPENGL_API*4),                 \
              +              [api] "J"(__builtin_offsetof(gl_hooks_t, gl._api))    \
              +            :                                                   \
              +            );
              +    
              +    #define CALL_GL_API_RETURN(_api, ...) \
              +        CALL_GL_API(_api, __VA_ARGS__) \
              +        return 0; // placate gcc's warnings. never reached.
              +
              +#else
              +
              +    #define API_ENTRY(_api) _api
              +
              +    #define CALL_GL_API(_api, ...)                                      \
              +        gl_hooks_t::gl_t const * const _c = &getGlThreadSpecific()->gl; \
              +        GL_LOGGER_IMPL( log_##_api(__VA_ARGS__); )                      \
              +        _c->_api(__VA_ARGS__)
              +    
              +    #define CALL_GL_API_RETURN(_api, ...)                               \
              +        gl_hooks_t::gl_t const * const _c = &getGlThreadSpecific()->gl; \
              +        GL_LOGGER_IMPL( log_##_api(__VA_ARGS__); )                      \
              +        return _c->_api(__VA_ARGS__)
              +
              +#endif
              +
              +extern "C" {
              +#include "gl_api.in"
              +}
              +
              +#undef API_ENTRY
              +#undef CALL_GL_API
              +#undef CALL_GL_API_RETURN
              +
              diff --git a/opengl/libGLES_CM/gl_api.cpp b/opengl/libs/GLES_CM/gl_api.in
              similarity index 99%
              rename from opengl/libGLES_CM/gl_api.cpp
              rename to opengl/libs/GLES_CM/gl_api.in
              index ed3bdaa8388bd38eceaf23eb01ef328c4024c92d..9234ef27387fb38f21d37b0ecbe83ecd7c4ef745 100644
              --- a/opengl/libGLES_CM/gl_api.cpp
              +++ b/opengl/libs/GLES_CM/gl_api.in
              @@ -415,7 +415,7 @@ void API_ENTRY(glTexEnvxv)(GLenum target, GLenum pname, const GLfixed *params) {
                   CALL_GL_API(glTexEnvxv, target, pname, params);
               }
               
              -void API_ENTRY(glTexImage2D)(  GLenum target, GLint level, GLenum internalformat,
              +void API_ENTRY(glTexImage2D)(  GLenum target, GLint level, GLint internalformat,
                                   GLsizei width, GLsizei height, GLint border, GLenum format,
                                   GLenum type, const GLvoid *pixels) {
                   CALL_GL_API(glTexImage2D, target, level, internalformat, width, height,
              diff --git a/opengl/libGLES_CM/gl_logger.cpp b/opengl/libs/GLES_CM/gl_logger.cpp
              similarity index 99%
              rename from opengl/libGLES_CM/gl_logger.cpp
              rename to opengl/libs/GLES_CM/gl_logger.cpp
              index 14b5a399e2937f4822bfd5364dfcae427f6e9998..27be5c9bac88f4ba51f8973cca6117253dfe210c 100644
              --- a/opengl/libGLES_CM/gl_logger.cpp
              +++ b/opengl/libs/GLES_CM/gl_logger.cpp
              @@ -23,7 +23,10 @@
               
               #include 
               
              -#include 
              +#include 
              +#include 
              +#include 
              +#include 
               
               #include 
               #include 
              @@ -33,13 +36,13 @@
               
               #include "gl_logger.h"
               
              +#undef NELEM
              +#define NELEM(x) (sizeof(x)/sizeof(*(x)))
              +
               // ----------------------------------------------------------------------------
               namespace android {
               // ----------------------------------------------------------------------------
               
              -#undef NELEM
              -#define NELEM(x) (sizeof(x)/sizeof(*(x)))
              -
               template
               static int binarySearch(T const sortedArray[], int first, int last, EGLint key)
               {
              @@ -226,12 +229,6 @@ private:
                   int mNumParams;
               };
               
              -// ----------------------------------------------------------------------------
              -}; // namespace android
              -// ----------------------------------------------------------------------------
              -
              -using namespace android;
              -
               #define API_ENTRY(api)                      log_##api
               #define CALL_GL_API(_x, ...)
               #define CALL_GL_API_RETURN(_x, ...)         return(0);
              @@ -785,7 +782,7 @@ void API_ENTRY(glTexEnvxv)(GLenum target, GLenum pname, const GLfixed *params) {
                   GLLog("glTexEnvxv") << GLLogEnum(target) << GLLogEnum(pname) << GLLogBuffer(params);
               }
               
              -void API_ENTRY(glTexImage2D)(  GLenum target, GLint level, GLenum internalformat,
              +void API_ENTRY(glTexImage2D)(  GLenum target, GLint level, GLint internalformat,
                                   GLsizei width, GLsizei height, GLint border, GLenum format,
                                   GLenum type, const GLvoid *pixels) {
                   CALL_GL_API(glTexImage2D, target, level, internalformat, width, height,
              @@ -1057,3 +1054,7 @@ GLbitfield API_ENTRY(glQueryMatrixxOES)(GLfixed* mantissa, GLint* exponent) {
                   GLLog("glQueryMatrixxOES") << GLLogBuffer(mantissa, 16) << GLLogBuffer(exponent, 16);
                   CALL_GL_API_RETURN(glQueryMatrixxOES, mantissa, exponent);
               }
              +
              +// ----------------------------------------------------------------------------
              +}; // namespace android
              +// ----------------------------------------------------------------------------
              diff --git a/opengl/libGLES_CM/egl_entries.cpp b/opengl/libs/egl_entries.in
              similarity index 89%
              rename from opengl/libGLES_CM/egl_entries.cpp
              rename to opengl/libs/egl_entries.in
              index ba46f40647a2cbbb1d62ab352528383284d776a4..33b4c654d207fc476455fd02dde2a32238f79293 100644
              --- a/opengl/libGLES_CM/egl_entries.cpp
              +++ b/opengl/libs/egl_entries.in
              @@ -23,7 +23,7 @@ EGL_ENTRY(EGLBoolean, eglSwapBuffers, EGLDisplay, EGLSurface)
               EGL_ENTRY(EGLBoolean, eglCopyBuffers, EGLDisplay, EGLSurface, NativePixmapType)
               EGL_ENTRY(EGLint, eglGetError, void)
               EGL_ENTRY(const char*, eglQueryString, EGLDisplay, EGLint)
              -EGL_ENTRY(proc_t, eglGetProcAddress, const char *)
              +EGL_ENTRY(__eglMustCastToProperFunctionPointerType, eglGetProcAddress, const char *)
               
               /* EGL 1.1 */
               
              @@ -40,7 +40,6 @@ EGL_ENTRY(EGLBoolean, eglWaitClient, void)
               EGL_ENTRY(EGLBoolean, eglReleaseThread, void)
               EGL_ENTRY(EGLSurface, eglCreatePbufferFromClientBuffer, EGLDisplay, EGLenum, EGLClientBuffer, EGLConfig, const EGLint *)
               
              -/* Android extentions */
              +/* EGL 1.3 */
               
              -EGL_ENTRY(EGLBoolean, eglSwapRectangleANDROID, EGLDisplay, EGLSurface , EGLint, EGLint, EGLint, EGLint)
              -EGL_ENTRY(const char*, eglQueryStringConfigANDROID, EGLDisplay, EGLConfig, EGLint)
              +/* EGL 1.4 */
              diff --git a/opengl/libs/egl_impl.h b/opengl/libs/egl_impl.h
              new file mode 100644
              index 0000000000000000000000000000000000000000..62ce3fce17009b9d97562f1b684fdc8ab1f3256b
              --- /dev/null
              +++ b/opengl/libs/egl_impl.h
              @@ -0,0 +1,43 @@
              +/* 
              + ** Copyright 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.
              + */
              +
              +#ifndef ANDROID_EGL_IMPL_H
              +#define ANDROID_EGL_IMPL_H
              +
              +#include 
              +
              +#include 
              +
              +// ----------------------------------------------------------------------------
              +namespace android {
              +// ----------------------------------------------------------------------------
              +
              +struct gl_hooks_t;
              +
              +struct egl_connection_t
              +{
              +    void volatile *     dso;
              +    gl_hooks_t *        hooks;
              +    EGLint              major;
              +    EGLint              minor;
              +    int                 unavailable;
              +};
              +
              +// ----------------------------------------------------------------------------
              +}; // namespace android
              +// ----------------------------------------------------------------------------
              +
              +#endif /* ANDROID_EGL_IMPL_H */
              diff --git a/opengl/libGLES_CM/gl_entries.cpp b/opengl/libs/gl_entries.in
              similarity index 98%
              rename from opengl/libGLES_CM/gl_entries.cpp
              rename to opengl/libs/gl_entries.in
              index 3279322961b696d81932a3e9aebdc0c3422f2190..b97e8fe3c479db8a6b6822f7ce382f40f2bd30da 100644
              --- a/opengl/libGLES_CM/gl_entries.cpp
              +++ b/opengl/libs/gl_entries.in
              @@ -101,7 +101,7 @@ GL_ENTRY(void, glCompressedTexImage2D,    GLenum, GLint, GLenum, GLsizei, GLsize
               GL_ENTRY(void, glCompressedTexSubImage2D, GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*)
               GL_ENTRY(void, glCopyTexImage2D, GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint)
               GL_ENTRY(void, glCopyTexSubImage2D, GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei)
              -GL_ENTRY(void, glTexImage2D, GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*)
              +GL_ENTRY(void, glTexImage2D, GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*)
               GL_ENTRY(void, glTexSubImage2D, GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*)
               GL_ENTRY(void, glReadPixels, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, GLvoid *)
               
              diff --git a/opengl/libGLES_CM/gl_enums.in b/opengl/libs/gl_enums.in
              similarity index 100%
              rename from opengl/libGLES_CM/gl_enums.in
              rename to opengl/libs/gl_enums.in
              diff --git a/opengl/libGLES_CM/gl_logger.h b/opengl/libs/gl_logger.h
              similarity index 92%
              rename from opengl/libGLES_CM/gl_logger.h
              rename to opengl/libs/gl_logger.h
              index 59e31c7ecea616de0e2f8538d84c423bf90b239c..ce85dd1ad0d74b4649c07799b55d523ab714ca90 100644
              --- a/opengl/libGLES_CM/gl_logger.h
              +++ b/opengl/libs/gl_logger.h
              @@ -17,10 +17,10 @@
               #ifndef ANDROID_GL_LOGGER_H
               #define ANDROID_GL_LOGGER_H
               
              -extern "C" {
              +namespace android {
               #define GL_ENTRY(r, api, ...) r log_##api(__VA_ARGS__);
              -#include "gl_entries.cpp"
              +#include "gl_entries.in"
               #undef GL_ENTRY
              -};
              +}; // namespace android
               
               #endif /* ANDROID_GL_LOGGER_H */
              diff --git a/opengl/libs/hooks.h b/opengl/libs/hooks.h
              new file mode 100644
              index 0000000000000000000000000000000000000000..63fb017675bf1200474f841e3866190bb6ee8e5e
              --- /dev/null
              +++ b/opengl/libs/hooks.h
              @@ -0,0 +1,134 @@
              +/* 
              + ** Copyright 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.
              + */
              +
              +#ifndef ANDROID_GLES_CM_HOOKS_H
              +#define ANDROID_GLES_CM_HOOKS_H
              +
              +#include 
              +#include 
              +#include 
              +
              +#include 
              +#include 
              +
              +#define GL_LOGGER                   0
              +#if !defined(__arm__)
              +#define USE_SLOW_BINDING            1
              +#else
              +#define USE_SLOW_BINDING            0
              +#endif
              +#undef NELEM
              +#define NELEM(x)                    (sizeof(x)/sizeof(*(x)))
              +#define MAX_NUMBER_OF_GL_EXTENSIONS 32
              +
              +
              +#if defined(HAVE_ANDROID_OS) && !USE_SLOW_BINDING && !GL_LOGGER && __OPTIMIZE__
              +#define USE_FAST_TLS_KEY            1
              +#else
              +#define USE_FAST_TLS_KEY            0
              +#endif
              +
              +#if USE_FAST_TLS_KEY
              +#   include   /* special private C library header */
              +#endif
              +
              +// ----------------------------------------------------------------------------
              +namespace android {
              +// ----------------------------------------------------------------------------
              +
              +//  EGLDisplay are global, not attached to a given thread
              +const unsigned int NUM_DISPLAYS = 1;
              +
              +enum {
              +    IMPL_HARDWARE = 0,
              +    IMPL_SOFTWARE,
              +    IMPL_CONTEXT_LOST,
              +    IMPL_NO_CONTEXT,
              +    
              +    IMPL_NUM_IMPLEMENTATIONS
              +};
              +
              +// ----------------------------------------------------------------------------
              +
              +// GL / EGL hooks
              +
              +#undef GL_ENTRY
              +#undef EGL_ENTRY
              +#define GL_ENTRY(_r, _api, ...) _r (*_api)(__VA_ARGS__);
              +#define EGL_ENTRY(_r, _api, ...) _r (*_api)(__VA_ARGS__);
              +
              +struct gl_hooks_t {
              +    struct gl_t {
              +        #include "gl_entries.in"
              +    } gl;
              +    struct egl_t {
              +        #include "egl_entries.in"
              +    } egl;
              +    struct gl_ext_t {
              +        void (*extensions[MAX_NUMBER_OF_GL_EXTENSIONS])(void);
              +    } ext;
              +};
              +#undef GL_ENTRY
              +#undef EGL_ENTRY
              +
              +
              +// ----------------------------------------------------------------------------
              +
              +extern gl_hooks_t gHooks[IMPL_NUM_IMPLEMENTATIONS];
              +extern pthread_key_t gGLWrapperKey;
              +
              +#if USE_FAST_TLS_KEY
              +
              +// We have a dedicated TLS slot in bionic
              +static inline gl_hooks_t const * volatile * get_tls_hooks() {
              +    volatile void *tls_base = __get_tls();
              +    gl_hooks_t const * volatile * tls_hooks = 
              +            reinterpret_cast(tls_base);
              +    return tls_hooks;
              +}
              +
              +static inline void setGlThreadSpecific(gl_hooks_t const *value) {
              +    gl_hooks_t const * volatile * tls_hooks = get_tls_hooks();
              +    tls_hooks[TLS_SLOT_OPENGL_API] = value;
              +}
              +
              +static gl_hooks_t const* getGlThreadSpecific() {
              +    gl_hooks_t const * volatile * tls_hooks = get_tls_hooks();
              +    gl_hooks_t const* hooks = tls_hooks[TLS_SLOT_OPENGL_API];
              +    if (hooks) return hooks;
              +    return &gHooks[IMPL_NO_CONTEXT];
              +}
              +
              +#else
              +
              +static inline void setGlThreadSpecific(gl_hooks_t const *value) {
              +    pthread_setspecific(gGLWrapperKey, value);
              +}
              +
              +static gl_hooks_t const* getGlThreadSpecific() {
              +    gl_hooks_t const* hooks =  static_cast(pthread_getspecific(gGLWrapperKey));
              +    if (hooks) return hooks;
              +    return &gHooks[IMPL_NO_CONTEXT];
              +}
              +
              +#endif
              +
              +
              +// ----------------------------------------------------------------------------
              +}; // namespace android
              +// ----------------------------------------------------------------------------
              +
              +#endif /* ANDROID_GLES_CM_HOOKS_H */
              diff --git a/opengl/libGLES_CM/enumextract.sh b/opengl/libs/tools/enumextract.sh
              similarity index 100%
              rename from opengl/libGLES_CM/enumextract.sh
              rename to opengl/libs/tools/enumextract.sh
              diff --git a/opengl/tests/angeles/Android.mk b/opengl/tests/angeles/Android.mk
              index 41673cbe41b7dc532cbe3a80e319ae951d1a8eff..46958d3c3c55237fdc52fc1a40f7d90311f764d8 100644
              --- a/opengl/tests/angeles/Android.mk
              +++ b/opengl/tests/angeles/Android.mk
              @@ -3,7 +3,7 @@
               LOCAL_PATH:= $(call my-dir)
               include $(CLEAR_VARS)
               LOCAL_SRC_FILES:= app-linux.c demo.c.arm
              -LOCAL_SHARED_LIBRARIES := libGLES_CM libui
              +LOCAL_SHARED_LIBRARIES := libEGL libGLESv1_CM libui
               LOCAL_MODULE:= angeles
               LOCAL_MODULE_TAGS := tests
               include $(BUILD_EXECUTABLE)
              @@ -11,7 +11,7 @@ include $(BUILD_EXECUTABLE)
               
               include $(CLEAR_VARS)
               LOCAL_SRC_FILES:= gpustate.c
              -LOCAL_SHARED_LIBRARIES := libGLES_CM
              +LOCAL_SHARED_LIBRARIES := libEGL libGLESv1_CM
               LOCAL_MODULE:= gpustate
               LOCAL_MODULE_TAGS := tests
               include $(BUILD_EXECUTABLE)
              diff --git a/opengl/tests/angeles/app-linux.c b/opengl/tests/angeles/app-linux.c
              index d439eb2fbfb74a9d8a55dd21c1434f483ee7b897..7d0d320a3241637d173cbc2c485229a9ed40a018 100644
              --- a/opengl/tests/angeles/app-linux.c
              +++ b/opengl/tests/angeles/app-linux.c
              @@ -49,7 +49,8 @@
               #include 
               #include 
               
              -#include 
              +#include 
              +#include 
               
               #include "app.h"
               
              diff --git a/opengl/tests/filter/Android.mk b/opengl/tests/filter/Android.mk
              index 1c4253c2c0cc2c68543a7ea827e6a2c273a054d7..a448f0d46161186eb18729c14cde9a2abcad2796 100644
              --- a/opengl/tests/filter/Android.mk
              +++ b/opengl/tests/filter/Android.mk
              @@ -6,7 +6,8 @@ LOCAL_SRC_FILES:= \
               
               LOCAL_SHARED_LIBRARIES := \
               	libcutils \
              -    libGLES_CM \
              +    libEGL \
              +    libGLESv1_CM \
                   libui
               
               LOCAL_MODULE:= test-opengl-filter
              diff --git a/opengl/tests/filter/filter.c b/opengl/tests/filter/filter.c
              index c8bac06cd56218a54cf8e94e12b9c1efbfabd2e5..de9711963e65454c7db8fd493052a2f8b975469f 100644
              --- a/opengl/tests/filter/filter.c
              +++ b/opengl/tests/filter/filter.c
              @@ -1,7 +1,9 @@
               #include 
               #include 
               
              -#include 
              +#include 
              +#include 
              +#include 
               
               int main(int argc, char** argv)
               {
              @@ -40,6 +42,9 @@ int main(int argc, char** argv)
                        printf("using pbuffer\n");
                        EGLint attribs[] = { EGL_WIDTH, 320, EGL_HEIGHT, 480, EGL_NONE };
                        surface = eglCreatePbufferSurface(dpy, config, attribs);
              +         if (surface == EGL_NO_SURFACE) {
              +             printf("eglCreatePbufferSurface error %x\n", eglGetError());
              +         }
                    }
                    context = eglCreateContext(dpy, config, NULL, NULL);
                    eglMakeCurrent(dpy, surface, surface, context);   
              diff --git a/opengl/tests/finish/Android.mk b/opengl/tests/finish/Android.mk
              index f7b95edccb9143e28ed67a711dfa12b55812872a..26836c1caf4cb4a7b024d918390cbec5d568a54a 100644
              --- a/opengl/tests/finish/Android.mk
              +++ b/opengl/tests/finish/Android.mk
              @@ -6,7 +6,8 @@ LOCAL_SRC_FILES:= \
               
               LOCAL_SHARED_LIBRARIES := \
               	libcutils \
              -    libGLES_CM \
              +    libEGL \
              +    libGLESv1_CM \
                   libui
               
               LOCAL_MODULE:= test-opengl-finish
              diff --git a/opengl/tests/finish/finish.c b/opengl/tests/finish/finish.c
              index 3afe227681bc3bc7b6160dfb0ac1a3e7c689959b..45fc7587befb09235d6815e6713aab7f4448310f 100644
              --- a/opengl/tests/finish/finish.c
              +++ b/opengl/tests/finish/finish.c
              @@ -20,7 +20,10 @@
               #include 
               #include 
               
              -#include 
              +#include 
              +#include 
              +#include 
              +
               
               long long systemTime()
               {
              diff --git a/opengl/tests/sfsim/Android.mk b/opengl/tests/sfsim/Android.mk
              deleted file mode 100644
              index 8a1a03cc42c1c0858657ed1eb9f73bb75903bfec..0000000000000000000000000000000000000000
              --- a/opengl/tests/sfsim/Android.mk
              +++ /dev/null
              @@ -1,15 +0,0 @@
              -LOCAL_PATH:= $(call my-dir)
              -include $(CLEAR_VARS)
              -
              -LOCAL_SRC_FILES:= \
              -	egl_surface.cpp \
              -	sfsim.c
              -
              -LOCAL_SHARED_LIBRARIES := \
              -    libGLES_CM
              -
              -LOCAL_MODULE:= test-opengl-sfsim
              -
              -LOCAL_MODULE_TAGS := tests
              -
              -include $(BUILD_EXECUTABLE)
              diff --git a/opengl/tests/sfsim/egl_surface.cpp b/opengl/tests/sfsim/egl_surface.cpp
              deleted file mode 100644
              index b0777f8c1c02e3bb5ad59d2e0a29642a72dd2781..0000000000000000000000000000000000000000
              --- a/opengl/tests/sfsim/egl_surface.cpp
              +++ /dev/null
              @@ -1,346 +0,0 @@
              -/* 
              - **
              - ** Copyright 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.
              - */
              -
              -#include 
              -#include 
              -#include 
              -#include 
              -#include 
              -#include 
              -#include 
              -#include 
              -#include 
              -
              -#include 
              -
              -#include "egl_surface.h"
              -
              -#define LOGI(x...) do { printf("INFO: " x); } while (0)
              -#define LOGW(x...) do { printf("WARN: " x); } while (0)
              -#define LOGE(x...) do { printf("ERR: " x); } while (0)
              -
              -// ----------------------------------------------------------------------------
              -
              -egl_native_window_t* android_createDisplaySurface()
              -{
              -    egl_native_window_t* s = new android::EGLDisplaySurface();
              -    s->memory_type = NATIVE_MEMORY_TYPE_GPU;
              -    return s;
              -}
              -
              -#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
              -#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
              -
              -// ----------------------------------------------------------------------------
              -namespace android {
              -// ----------------------------------------------------------------------------
              -
              -EGLDisplaySurface::EGLDisplaySurface()
              -    : EGLNativeSurface()
              -{
              -    egl_native_window_t::version = sizeof(egl_native_window_t);
              -    egl_native_window_t::ident = 0;
              -    egl_native_window_t::incRef = &EGLDisplaySurface::hook_incRef;
              -    egl_native_window_t::decRef = &EGLDisplaySurface::hook_decRef;
              -    egl_native_window_t::swapBuffers = &EGLDisplaySurface::hook_swapBuffers;
              -    egl_native_window_t::setSwapRectangle = &EGLDisplaySurface::hook_setSwapRectangle;
              -    egl_native_window_t::nextBuffer = &EGLDisplaySurface::hook_nextBuffer;
              -    egl_native_window_t::connect = 0;
              -    egl_native_window_t::disconnect = 0;
              -
              -    mFb[0].data = 0;
              -    mFb[1].data = 0;
              -    egl_native_window_t::fd = mapFrameBuffer();
              -    if (egl_native_window_t::fd >= 0) {
              -        const float in2mm = 25.4f;
              -        float refreshRate = 1000000000000000LLU / (
              -                float( mInfo.upper_margin + mInfo.lower_margin + mInfo.yres ) 
              -                * ( mInfo.left_margin  + mInfo.right_margin + mInfo.xres )
              -                * mInfo.pixclock);
              -
              -        const GGLSurface& buffer = mFb[1 - mIndex];
              -        egl_native_window_t::width  = buffer.width;
              -        egl_native_window_t::height = buffer.height;
              -        egl_native_window_t::stride = buffer.stride;
              -        egl_native_window_t::format = buffer.format;
              -        egl_native_window_t::base   = intptr_t(mFb[0].data);
              -        egl_native_window_t::offset =
              -            intptr_t(buffer.data) - egl_native_window_t::base;
              -        egl_native_window_t::flags  = 0;
              -        egl_native_window_t::xdpi = (mInfo.xres * in2mm) / mInfo.width;
              -        egl_native_window_t::ydpi = (mInfo.yres * in2mm) / mInfo.height;
              -        egl_native_window_t::fps  = refreshRate;
              -        egl_native_window_t::memory_type = NATIVE_MEMORY_TYPE_FB;
              -        // no error, set the magic word
              -        egl_native_window_t::magic = 0x600913;
              -    }
              -    mSwapCount = -1;
              -    mPageFlipCount = 0;
              -}
              -
              -EGLDisplaySurface::~EGLDisplaySurface()
              -{
              -    magic = 0;
              -    close(egl_native_window_t::fd);
              -    munmap(mFb[0].data, mSize);
              -    if (!(mFlags & PAGE_FLIP))
              -        free((void*)mFb[1].data);
              -}
              -
              -void EGLDisplaySurface::hook_incRef(NativeWindowType window) {
              -    EGLDisplaySurface* that = static_cast(window);
              -    that->incStrong(that);
              -}
              -void EGLDisplaySurface::hook_decRef(NativeWindowType window) {
              -    EGLDisplaySurface* that = static_cast(window);
              -    that->decStrong(that);
              -}
              -uint32_t EGLDisplaySurface::hook_swapBuffers(NativeWindowType window) {
              -    EGLDisplaySurface* that = static_cast(window);
              -    return that->swapBuffers();
              -}
              -uint32_t EGLDisplaySurface::hook_nextBuffer(NativeWindowType window) {
              -    EGLDisplaySurface* that = static_cast(window);
              -    return that->nextBuffer();
              -}
              -void EGLDisplaySurface::hook_setSwapRectangle(NativeWindowType window,
              -        int l, int t, int w, int h) {
              -    EGLDisplaySurface* that = static_cast(window);
              -    that->setSwapRectangle(l, t, w, h);
              -}
              -
              -void EGLDisplaySurface::setSwapRectangle(int l, int t, int w, int h)
              -{
              -    mInfo.reserved[0] = 0x54445055; // "UPDT";
              -    mInfo.reserved[1] = (uint16_t)l | ((uint32_t)t << 16);
              -    mInfo.reserved[2] = (uint16_t)(l+w) | ((uint32_t)(t+h) << 16);
              -}
              -
              -uint32_t EGLDisplaySurface::swapBuffers()
              -{
              -    if (!(mFlags & PAGE_FLIP))
              -        return 0;
              -
              -    // do the actual flip
              -    mIndex = 1 - mIndex;
              -    mInfo.activate = FB_ACTIVATE_VBL;
              -    mInfo.yoffset = mIndex ? mInfo.yres : 0;
              -    if (ioctl(egl_native_window_t::fd, FBIOPUT_VSCREENINFO, &mInfo) == -1) {
              -        LOGE("FBIOPUT_VSCREENINFO failed");
              -        return 0;
              -    }
              -
              -    /*
              -     * this is a monstruous hack: Because the h/w accelerator is not able
              -     * to render directly into the framebuffer, we need to copy its
              -     * internal framebuffer out to the fb. the base address of the internal fb
              -     * is given in oem[0]. 
              -     * All this is needed only in standalone mode, in SurfaceFlinger mode
              -     * we control where the GPU renders.
              -     */
              -    if (egl_native_window_t::memory_type == NATIVE_MEMORY_TYPE_GPU && oem[0]) {
              -        // could use MDP here, but that's tricky because we need
              -        // /dev/pmem_gpu* filedescriptor
              -        const GGLSurface& buffer = mFb[mIndex];
              -        memcpy( buffer.data,
              -                (void*)(oem[0] + egl_native_window_t::offset),
              -                buffer.stride*buffer.height*2);
              -    }
              -
              -    // update the address of the buffer to draw to next
              -    const GGLSurface& buffer = mFb[1 - mIndex];
              -    egl_native_window_t::offset =
              -        intptr_t(buffer.data) - egl_native_window_t::base;
              -
              -    mPageFlipCount++;
              -
              -    // We don't support screen-size changes for now
              -    return 0;
              -}
              -
              -int32_t EGLDisplaySurface::getPageFlipCount() const
              -{
              -    return mPageFlipCount;
              -}
              -
              -uint32_t EGLDisplaySurface::nextBuffer()
              -{
              -    // update the address of the buffer to draw to next
              -    const GGLSurface& buffer = mFb[mIndex];
              -    egl_native_window_t::offset =
              -        intptr_t(buffer.data) - egl_native_window_t::base;
              -    return 0;
              -}
              -
              -int EGLDisplaySurface::mapFrameBuffer()
              -{
              -    char const * const device_template[] = {
              -            "/dev/graphics/fb%u",
              -            "/dev/fb%u",
              -            0 };
              -    int fd = -1;
              -    int i=0;
              -    char name[64];
              -    while ((fd==-1) && device_template[i]) {
              -        snprintf(name, 64, device_template[i], 0);
              -        fd = open(name, O_RDWR, 0);
              -        i++;
              -    }
              -    if (fd < 0)
              -        return -errno;
              -
              -    struct fb_fix_screeninfo finfo;
              -    if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1)
              -        return -errno;
              -
              -    struct fb_var_screeninfo info;
              -    if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1)
              -        return -errno;
              -
              -    info.reserved[0] = 0;
              -    info.reserved[1] = 0;
              -    info.reserved[2] = 0;
              -    info.xoffset = 0;
              -    info.yoffset = 0;
              -    info.yres_virtual = info.yres * 2;
              -    info.bits_per_pixel = 16;
              -    info.activate = FB_ACTIVATE_NOW;
              -
              -    uint32_t flags = PAGE_FLIP;
              -    if (ioctl(fd, FBIOPUT_VSCREENINFO, &info) == -1) {
              -        info.yres_virtual = info.yres;
              -        flags &= ~PAGE_FLIP;
              -        LOGW("FBIOPUT_VSCREENINFO failed, page flipping not supported");
              -    }
              -
              -    if (info.yres_virtual < info.yres * 2) {
              -        info.yres_virtual = info.yres;
              -        flags &= ~PAGE_FLIP;
              -        LOGW("page flipping not supported (yres_virtual=%d, requested=%d)",
              -                info.yres_virtual, info.yres*2);
              -    }
              -
              -    if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1)
              -        return -errno;    
              -
              -    int refreshRate = 1000000000000000LLU / 
              -    (
              -            uint64_t( info.upper_margin + info.lower_margin + info.yres ) 
              -            * ( info.left_margin  + info.right_margin + info.xres )
              -            * info.pixclock
              -    );
              -
              -    if (refreshRate == 0) {
              -        // bleagh, bad info from the driver
              -        refreshRate = 60*1000;  // 60 Hz
              -    }
              -
              -    if (int(info.width) <= 0 || int(info.height) <= 0) {
              -        // stupid driver, doesn't return that information
              -        // default to Sooner's screen size (160 dpi)
              -        info.width  = 51;
              -        info.height = 38;
              -    }
              -
              -    float xdpi = (info.xres * 25.4f) / info.width; 
              -    float ydpi = (info.yres * 25.4f) / info.height;
              -    float fps  = refreshRate / 1000.0f; 
              -
              -    LOGI(   "using (fd=%d)\n"
              -            "id           = %s\n"
              -            "xres         = %d px\n"
              -            "yres         = %d px\n"
              -            "xres_virtual = %d px\n"
              -            "yres_virtual = %d px\n"
              -            "bpp          = %d\n"
              -            "r            = %2u:%u\n"
              -            "g            = %2u:%u\n"
              -            "b            = %2u:%u\n",
              -            fd,
              -            finfo.id,
              -            info.xres,
              -            info.yres,
              -            info.xres_virtual,
              -            info.yres_virtual,
              -            info.bits_per_pixel,
              -            info.red.offset, info.red.length,
              -            info.green.offset, info.green.length,
              -            info.blue.offset, info.blue.length
              -    );
              -
              -    LOGI(   "width        = %d mm (%f dpi)\n"
              -            "height       = %d mm (%f dpi)\n"
              -            "refresh rate = %.2f Hz\n",
              -            info.width,  xdpi,
              -            info.height, ydpi,
              -            fps
              -    );
              -
              -    
              -    if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1)
              -        return -errno;
              -
              -    if (finfo.smem_len <= 0)
              -        return -errno;
              -
              -    /*
              -     * Open and map the display.
              -     */
              -
              -    void* buffer  = (uint16_t*) mmap(
              -            0, finfo.smem_len,
              -            PROT_READ | PROT_WRITE,
              -            MAP_SHARED,
              -            fd, 0);
              -
              -    if (buffer == MAP_FAILED)
              -        return -errno;
              -
              -    // at least for now, always clear the fb
              -    memset(buffer, 0, finfo.smem_len);
              -
              -    uint8_t* offscreen[2];
              -    offscreen[0] = (uint8_t*)buffer;
              -    if (flags & PAGE_FLIP) {
              -        offscreen[1] = (uint8_t*)buffer + finfo.line_length*info.yres;
              -    } else {
              -        offscreen[1] = (uint8_t*)malloc(finfo.smem_len);
              -        if (offscreen[1] == 0) {
              -            munmap(buffer, finfo.smem_len);
              -            return -ENOMEM;
              -        }
              -    }
              -
              -    mFlags = flags;
              -    mInfo = info;
              -    mFinfo = finfo;
              -    mSize = finfo.smem_len;
              -    mIndex = 0;
              -    for (int i=0 ; i<2 ; i++) {
              -        mFb[i].version = sizeof(GGLSurface);
              -        mFb[i].width   = info.xres;
              -        mFb[i].height  = info.yres;
              -        mFb[i].stride  = finfo.line_length / (info.bits_per_pixel >> 3);
              -        mFb[i].data    = (uint8_t*)(offscreen[i]);
              -        mFb[i].format  = NATIVE_PIXEL_FORMAT_RGB_565;
              -    }
              -    return fd;
              -}
              -
              -// ----------------------------------------------------------------------------
              -}; // namespace android
              -// ----------------------------------------------------------------------------
              diff --git a/opengl/tests/sfsim/egl_surface.h b/opengl/tests/sfsim/egl_surface.h
              deleted file mode 100644
              index 70a94fcab994055cfd10d52bdc1beb6ac2c6d52b..0000000000000000000000000000000000000000
              --- a/opengl/tests/sfsim/egl_surface.h
              +++ /dev/null
              @@ -1,113 +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 ANDROID_SIM_EGL_SURFACE_H
              -#define ANDROID_SIM_EGL_SURFACE_H
              -
              -#include 
              -#include 
              -#include 
              -
              -#include 
              -
              -#include 
              -
              -typedef struct {
              -    ssize_t    version;    // always set to sizeof(GGLSurface)
              -    uint32_t   width;      // width in pixels
              -    uint32_t   height;     // height in pixels
              -    int32_t    stride;     // stride in pixels
              -    uint8_t*   data;       // pointer to the bits
              -    uint8_t    format;     // pixel format
              -    uint8_t    rfu[3];     // must be zero
              -    void*      reserved;
              -} GGLSurface;
              -
              -// ---------------------------------------------------------------------------
              -namespace android {
              -// ---------------------------------------------------------------------------
              -
              -template 
              -class EGLNativeSurface : public egl_native_window_t
              -{
              -public:
              -    EGLNativeSurface() : mCount(0) { 
              -        memset(egl_native_window_t::reserved, 0, 
              -                sizeof(egl_native_window_t::reserved));
              -        memset(egl_native_window_t::reserved_proc, 0, 
              -                sizeof(egl_native_window_t::reserved_proc));
              -        memset(egl_native_window_t::oem, 0, 
              -                sizeof(egl_native_window_t::oem));
              -    }
              -    inline void incStrong(void*) const {
              -        /* in a real implementation, the inc must be atomic */
              -        mCount++;
              -    }
              -    inline void decStrong(void*) const {
              -        /* in a real implementation, the dec must be atomic */
              -        if (--mCount == 1) {
              -             delete static_cast(this);
              -         }
              -    }
              -protected:
              -    EGLNativeSurface& operator = (const EGLNativeSurface& rhs);
              -    EGLNativeSurface(const EGLNativeSurface& rhs);
              -    inline ~EGLNativeSurface() { };
              -    mutable volatile int32_t mCount;
              -};
              -
              -
              -class EGLDisplaySurface : public EGLNativeSurface
              -{
              -public:
              -    EGLDisplaySurface();
              -    ~EGLDisplaySurface();
              -
              -    int32_t getPageFlipCount() const;
              -
              -private:
              -    static void         hook_incRef(NativeWindowType window);
              -    static void         hook_decRef(NativeWindowType window);
              -    static uint32_t     hook_swapBuffers(NativeWindowType window);
              -    static void         hook_setSwapRectangle(NativeWindowType window, int l, int t, int w, int h);
              -    static uint32_t     hook_nextBuffer(NativeWindowType window);
              -
              -    uint32_t    swapBuffers();
              -    uint32_t    nextBuffer();
              -    void        setSwapRectangle(int l, int t, int w, int h);
              -
              -    int    mapFrameBuffer();
              -
              -    enum {
              -        PAGE_FLIP = 0x00000001
              -    };
              -    GGLSurface          mFb[2];
              -    int                 mIndex;
              -    uint32_t            mFlags;
              -    size_t              mSize;
              -    fb_var_screeninfo   mInfo;
              -    fb_fix_screeninfo   mFinfo;
              -    int32_t             mPageFlipCount;
              -    int32_t             mSwapCount;
              -    uint32_t            mFeatureFlags;
              -};
              -
              -// ---------------------------------------------------------------------------
              -}; // namespace android
              -// ---------------------------------------------------------------------------
              -
              -#endif // ANDROID_SIM_EGL_SURFACE_H
              -
              diff --git a/opengl/tests/sfsim/sfsim.c b/opengl/tests/sfsim/sfsim.c
              deleted file mode 100644
              index 14ba490d70501dfa013de1ee84513c90c2c02cdd..0000000000000000000000000000000000000000
              --- a/opengl/tests/sfsim/sfsim.c
              +++ /dev/null
              @@ -1,112 +0,0 @@
              -#include 
              -#include 
              -
              -#include 
              -
              -int main(int argc, char** argv)
              -{
              -    if (argc != 2) {
              -        printf("usage: %s <0-6>\n", argv[0]);
              -        return 0;
              -    }
              -    
              -    const int test = atoi(argv[1]);
              -
              -    EGLint s_configAttribs[] = {
              -         EGL_RED_SIZE,       5,
              -         EGL_GREEN_SIZE,     6,
              -         EGL_BLUE_SIZE,      5,
              -         EGL_NONE
              -     };
              -     
              -     EGLint numConfigs = -1;
              -     EGLint majorVersion;
              -     EGLint minorVersion;
              -     EGLConfig config;
              -     EGLContext context;
              -     EGLSurface surface;
              -     EGLint w, h;
              -     
              -     EGLDisplay dpy;
              -
              -     dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
              -     eglInitialize(dpy, &majorVersion, &minorVersion);
              -     eglChooseConfig(dpy, s_configAttribs, &config, 1, &numConfigs);
              -     surface = eglCreateWindowSurface(dpy, config,
              -             android_createDisplaySurface(), NULL);
              -     context = eglCreateContext(dpy, config, NULL, NULL);
              -     eglMakeCurrent(dpy, surface, surface, context);   
              -     eglQuerySurface(dpy, surface, EGL_WIDTH, &w);
              -     eglQuerySurface(dpy, surface, EGL_HEIGHT, &h);
              -     GLint dim = w
               #include 
               
              -#include 
              +#include 
              +#include 
              +#include 
               
               int main(int argc, char** argv)
               {
              diff --git a/opengl/tests/tritex/Android.mk b/opengl/tests/tritex/Android.mk
              index 4edac4cb4f96c8cc3df2c60f8065801f83d0d898..5cd1f048a309eb9e55b24b226217f2d1c6409b2a 100644
              --- a/opengl/tests/tritex/Android.mk
              +++ b/opengl/tests/tritex/Android.mk
              @@ -6,7 +6,8 @@ LOCAL_SRC_FILES:= \
               
               LOCAL_SHARED_LIBRARIES := \
               	libcutils \
              -    libGLES_CM \
              +    libEGL \
              +    libGLESv1_CM \
                   libui
               
               LOCAL_MODULE:= test-opengl-tritex
              diff --git a/opengl/tests/tritex/tritex.c b/opengl/tests/tritex/tritex.c
              index 8ebe7d4d72cfad6c1fbb6437a42897cd86963d23..60a7feb9b8404b146b68923689a09ee5cfd32d9f 100644
              --- a/opengl/tests/tritex/tritex.c
              +++ b/opengl/tests/tritex/tritex.c
              @@ -4,7 +4,9 @@
               //
               // Ported from a Java version by Google.
               
              -#include 
              +#include 
              +#include 
              +
               #include 
               #include 
               #include 
              diff --git a/packages/SettingsProvider/Android.mk b/packages/SettingsProvider/Android.mk
              index 330a673dbaa905ef1107ea0377832b04f09f714e..724e988f737a5b5248a0225741a967c8936b531d 100644
              --- a/packages/SettingsProvider/Android.mk
              +++ b/packages/SettingsProvider/Android.mk
              @@ -1,7 +1,7 @@
               LOCAL_PATH:= $(call my-dir)
               include $(CLEAR_VARS)
               
              -LOCAL_MODULE_TAGS := user development
              +LOCAL_MODULE_TAGS := user
               
               LOCAL_SRC_FILES := $(call all-subdir-java-files)
               
              diff --git a/packages/SettingsProvider/etc/Android.mk b/packages/SettingsProvider/etc/Android.mk
              index e3f958cfb0c97eb2bedf001054562504eb23bdd8..d73175f3d09552b10e4484707260967e72435af9 100644
              --- a/packages/SettingsProvider/etc/Android.mk
              +++ b/packages/SettingsProvider/etc/Android.mk
              @@ -21,7 +21,7 @@ include $(CLEAR_VARS)
               
               LOCAL_MODULE := bookmarks.xml
               
              -LOCAL_MODULE_TAGS := user development
              +LOCAL_MODULE_TAGS := user
               
               # This will install the file in /system/etc
               #
              @@ -36,7 +36,7 @@ include $(CLEAR_VARS)
               
               LOCAL_MODULE := favorites.xml
               
              -LOCAL_MODULE_TAGS := user development
              +LOCAL_MODULE_TAGS := user
               
               # This will install the file in /system/etc
               #
              diff --git a/packages/SettingsProvider/etc/bookmarks.xml b/packages/SettingsProvider/etc/bookmarks.xml
              index 235e2edf600019da719156363e39c0ce02d33813..5fb6608be40033b5acaf95031736d5b4bee93a79 100644
              --- a/packages/SettingsProvider/etc/bookmarks.xml
              +++ b/packages/SettingsProvider/etc/bookmarks.xml
              @@ -15,14 +15,44 @@
               -->
               
               
              -    
              -    
              -    
              -    
              -    
              -    
              -    
              -    
              -    
              -    
              -
              +    
              +    
              +    
              +    
              +    
              +    
              +    
              +    
              +    
              +    
              +
              \ No newline at end of file
              diff --git a/packages/SettingsProvider/etc/favorites.xml b/packages/SettingsProvider/etc/favorites.xml
              index 0ecf8a6b9bad5b44aa22cad3aa8fe85b4ffb3395..ae74b8ee4750d61e40490282ab9a3abbb55265c1 100644
              --- a/packages/SettingsProvider/etc/favorites.xml
              +++ b/packages/SettingsProvider/etc/favorites.xml
              @@ -1,5 +1,5 @@
               
              -
              +
              +    true
              +    60000
              +    false
              +    
              +    cell,bluetooth,wifi
              +    true
              +    true
              +    
              +    102
              +    100%
              +    0%
              +    
              +    false
              +    false
              +    
              +    network
              +    
              +    1
              +    true
              +    false
              +    true
              +
              diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
              index 218227149aaf22bc8857a6d790e8f2943988dff8..c6f54a3f8da3e06ab0aa6c7a3a9ed5d88722f276 100644
              --- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
              +++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
              @@ -22,11 +22,11 @@ import android.content.Context;
               import android.content.Intent;
               import android.content.pm.ActivityInfo;
               import android.content.pm.PackageManager;
              +import android.content.res.Resources;
               import android.database.Cursor;
               import android.database.sqlite.SQLiteDatabase;
               import android.database.sqlite.SQLiteOpenHelper;
               import android.database.sqlite.SQLiteStatement;
              -import android.location.LocationManager;
               import android.media.AudioManager;
               import android.media.AudioService;
               import android.net.ConnectivityManager;
              @@ -63,7 +63,7 @@ public class DatabaseHelper extends SQLiteOpenHelper {
               
                   private static final String TAG = "SettingsProvider";
                   private static final String DATABASE_NAME = "settings.db";
              -    private static final int DATABASE_VERSION = 31;
              +    private static final int DATABASE_VERSION = 34;
                   
                   private Context mContext;
               
              @@ -332,6 +332,58 @@ public class DatabaseHelper extends SQLiteOpenHelper {
                           upgradeVersion = 31;
                       }
               
              +        if (upgradeVersion == 31) {
              +            /*
              +             * Animations are now managed in preferences, and may be
              +             * enabled or disabled based on product resources.
              +             */
              +            db.beginTransaction();
              +            try {
              +                db.execSQL("DELETE FROM system WHERE name='"
              +                        + Settings.System.WINDOW_ANIMATION_SCALE + "'");
              +                db.execSQL("DELETE FROM system WHERE name='"
              +                        + Settings.System.TRANSITION_ANIMATION_SCALE + "'");
              +                SQLiteStatement stmt = db.compileStatement("INSERT INTO system(name,value)"
              +                        + " VALUES(?,?);");
              +                loadDefaultAnimationSettings(stmt);
              +                stmt.close();
              +                db.setTransactionSuccessful();
              +            } finally {
              +                db.endTransaction();
              +            }
              +            upgradeVersion = 32;
              +        }
              +
              +        if (upgradeVersion == 32) {
              +            // The Wi-Fi watchdog SSID list is now seeded with the value of
              +            // the property ro.com.android.wifi-watchlist
              +            String wifiWatchList = SystemProperties.get("ro.com.android.wifi-watchlist");
              +            if (!TextUtils.isEmpty(wifiWatchList)) {
              +                db.beginTransaction();
              +                try {
              +                    db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
              +                            Settings.Secure.WIFI_WATCHDOG_WATCH_LIST + "','" +
              +                            wifiWatchList + "');");
              +                    db.setTransactionSuccessful();
              +                } finally {
              +                    db.endTransaction();
              +                }
              +            }
              +            upgradeVersion = 33;
              +        }
              +        
              +        if (upgradeVersion == 33) {
              +            // Set the default zoom controls to: tap-twice to bring up +/-
              +            db.beginTransaction();
              +            try {
              +                db.execSQL("INSERT INTO system(name,value) values('zoom','2');");
              +                db.setTransactionSuccessful();
              +            } finally {
              +                db.endTransaction();
              +            }
              +            upgradeVersion = 34;
              +        }
              +
                       if (upgradeVersion != currentVersion) {
                           Log.w(TAG, "Got stuck trying to upgrade from version " + upgradeVersion
                                   + ", must wipe the settings provider");
              @@ -529,28 +581,31 @@ public class DatabaseHelper extends SQLiteOpenHelper {
                       SQLiteStatement stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
                               + " VALUES(?,?);");
                       
              -        loadSetting(stmt, Settings.System.DIM_SCREEN, 1);
              +        Resources r = mContext.getResources();
              +        loadBooleanSetting(stmt, Settings.System.DIM_SCREEN,
              +                R.bool.def_dim_screen);
                       loadSetting(stmt, Settings.System.STAY_ON_WHILE_PLUGGED_IN, 
                               "1".equals(SystemProperties.get("ro.kernel.qemu")) ? 1 : 0);
              -        loadSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT, 60000);
              -        // Allow airplane mode to turn off cell radio
              -        loadSetting(stmt, Settings.System.AIRPLANE_MODE_RADIOS, 
              -                Settings.System.RADIO_CELL + ","
              -                + Settings.System.RADIO_BLUETOOTH + "," + Settings.System.RADIO_WIFI);
              +        loadIntegerSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
              +                R.integer.def_screen_off_timeout);
              +        
              +        loadBooleanSetting(stmt, Settings.System.AIRPLANE_MODE_ON,
              +                R.bool.def_airplane_mode_on);
                       
              -        loadSetting(stmt, Settings.System.AIRPLANE_MODE_ON, 0);
              +        loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_RADIOS,
              +                R.string.def_airplane_mode_radios);
                       
              -        loadSetting(stmt, Settings.System.AUTO_TIME, 1); // Sync time to NITZ
              +        loadBooleanSetting(stmt, Settings.System.AUTO_TIME,
              +                R.bool.def_auto_time); // Sync time to NITZ
                       
              -        // Set default brightness to 40%
              -        loadSetting(stmt, Settings.System.SCREEN_BRIGHTNESS, 
              -                (int) (android.os.Power.BRIGHTNESS_ON * 0.4f));
              +        loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS,
              +                R.integer.def_screen_brightness);
                       
              -        // Enable normal window animations (menus, toasts); disable
              -        // activity transition animations.
              -        loadSetting(stmt, Settings.System.WINDOW_ANIMATION_SCALE, "1");
              -        loadSetting(stmt, Settings.System.TRANSITION_ANIMATION_SCALE, "1");
              +        loadDefaultAnimationSettings(stmt);
               
              +        loadBooleanSetting(stmt, Settings.System.ACCELEROMETER_ROTATION,
              +                R.bool.def_accelerometer_rotation);
              +        
                       // Default date format based on build
                       loadSetting(stmt, Settings.System.DATE_FORMAT,
                               SystemProperties.get("ro.com.android.dateformat", 
              @@ -558,12 +613,19 @@ public class DatabaseHelper extends SQLiteOpenHelper {
                       stmt.close();
                   }
                   
              +    private void loadDefaultAnimationSettings(SQLiteStatement stmt) {
              +        loadFractionSetting(stmt, Settings.System.WINDOW_ANIMATION_SCALE,
              +                R.fraction.def_window_animation_scale, 1);
              +        loadFractionSetting(stmt, Settings.System.TRANSITION_ANIMATION_SCALE,
              +                R.fraction.def_window_transition_scale, 1);
              +    }
              +    
                   private void loadSecureSettings(SQLiteDatabase db) {
                       SQLiteStatement stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
                               + " VALUES(?,?);");
                       
              -        // Bluetooth off
              -        loadSetting(stmt, Settings.Secure.BLUETOOTH_ON, 0);
              +        loadBooleanSetting(stmt, Settings.Secure.BLUETOOTH_ON,
              +                R.bool.def_bluetooth_on);
                       
                       // Data roaming default, based on build
                       loadSetting(stmt, Settings.Secure.DATA_ROAMING, 
              @@ -571,27 +633,36 @@ public class DatabaseHelper extends SQLiteOpenHelper {
                                       SystemProperties.get("ro.com.android.dataroaming", 
                                               "false")) ? 1 : 0);        
                       
              -        // Don't allow non-market apps to be installed
              -        loadSetting(stmt, Settings.Secure.INSTALL_NON_MARKET_APPS, 0);
              +        loadBooleanSetting(stmt, Settings.Secure.INSTALL_NON_MARKET_APPS,
              +                R.bool.def_install_non_market_apps);
                       
              -        // Set the default location providers to network based (cell-id)
              -        loadSetting(stmt, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, 
              -                LocationManager.NETWORK_PROVIDER);
              +        loadStringSetting(stmt, Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
              +                R.string.def_location_providers_allowed);
                       
              -        loadSetting(stmt, Settings.Secure.NETWORK_PREFERENCE,
              -            ConnectivityManager.DEFAULT_NETWORK_PREFERENCE);
              -
              -        // USB mass storage on by default
              -        loadSetting(stmt, Settings.Secure.USB_MASS_STORAGE_ENABLED, 1);
              +        loadIntegerSetting(stmt, Settings.Secure.NETWORK_PREFERENCE,
              +                R.integer.def_network_preference);
                       
              -        // WIFI on, notify about available networks
              -        loadSetting(stmt, Settings.Secure.WIFI_ON, 0);
              -        loadSetting(stmt, Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1);
              +        loadBooleanSetting(stmt, Settings.Secure.USB_MASS_STORAGE_ENABLED,
              +                R.bool.def_usb_mass_storage_enabled);
                       
              +        loadBooleanSetting(stmt, Settings.Secure.WIFI_ON,
              +                R.bool.def_wifi_on);
              +        loadBooleanSetting(stmt, Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
              +                R.bool.def_networks_available_notification_on);
              +
              +        String wifiWatchList = SystemProperties.get("ro.com.android.wifi-watchlist");
              +        if (!TextUtils.isEmpty(wifiWatchList)) {
              +            loadSetting(stmt, Settings.Secure.WIFI_WATCHDOG_WATCH_LIST, wifiWatchList);
              +        }
              +
                       // Don't do this.  The SystemServer will initialize ADB_ENABLED from a
                       // persistent system property instead.
                       //loadSetting(stmt, Settings.Secure.ADB_ENABLED, 0);
                       
              +        // Allow mock locations default, based on build
              +        loadSetting(stmt, Settings.Secure.ALLOW_MOCK_LOCATION, 
              +                "1".equals(SystemProperties.get("ro.allow.mock.location")) ? 1 : 0);
              +        
                       stmt.close();
                   }
               
              @@ -600,4 +671,23 @@ public class DatabaseHelper extends SQLiteOpenHelper {
                       stmt.bindString(2, value.toString());
                       stmt.execute();
                   }
              +    
              +    private void loadStringSetting(SQLiteStatement stmt, String key, int resid) {
              +        loadSetting(stmt, key, mContext.getResources().getString(resid));
              +    }
              +    
              +    private void loadBooleanSetting(SQLiteStatement stmt, String key, int resid) {
              +        loadSetting(stmt, key,
              +                mContext.getResources().getBoolean(resid) ? "1" : "0");
              +    }
              +    
              +    private void loadIntegerSetting(SQLiteStatement stmt, String key, int resid) {
              +        loadSetting(stmt, key,
              +                Integer.toString(mContext.getResources().getInteger(resid)));
              +    }
              +    
              +    private void loadFractionSetting(SQLiteStatement stmt, String key, int resid, int base) {
              +        loadSetting(stmt, key,
              +                Float.toString(mContext.getResources().getFraction(resid, base, base)));
              +    }
               }
              diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
              index 0101ece6d428353a3a1666fbc71cdd5d85d3d630..8d52070ebf23b5db4b025d257f9b344e866e50f9 100644
              --- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
              +++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
              @@ -40,6 +40,9 @@ public class SettingsProvider extends ContentProvider {
                   private static final String TAG = "SettingsProvider";
                   private static final boolean LOCAL_LOGV = false;
               
              +    private static final String TABLE_FAVORITES = "favorites";
              +    private static final String TABLE_OLD_FAVORITES = "old_favorites";
              +
                   protected DatabaseHelper mOpenHelper;
               
                   /**
              @@ -47,7 +50,7 @@ public class SettingsProvider extends ContentProvider {
                    * used to access the corresponding database rows.
                    */
                   private static class SqlArguments {
              -        public final String table;
              +        public String table;
                       public final String where;
                       public final String[] args;
               
              @@ -175,17 +178,30 @@ public class SettingsProvider extends ContentProvider {
                   @Override
                   public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
                       SqlArguments args = new SqlArguments(url, where, whereArgs);
              +        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
              +
                       // The favorites table was moved from this provider to a provider inside Home
                       // Home still need to query this table to upgrade from pre-cupcake builds
                       // However, a cupcake+ build with no data does not contain this table which will
                       // cause an exception in the SQL stack. The following line is a special case to
                       // let the caller of the query have a chance to recover and avoid the exception
              -        if ("favorites".equals(args.table)) return null;
              +        if (TABLE_FAVORITES.equals(args.table)) {
              +            return null;
              +        } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
              +            args.table = TABLE_FAVORITES;
              +            Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
              +            if (cursor != null) {
              +                boolean exists = cursor.getCount() > 0;
              +                cursor.close();
              +                if (!exists) return null;
              +            } else {
              +                return null;
              +            }
              +        }
               
                       SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
                       qb.setTables(args.table);
               
              -        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
                       Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
                       ret.setNotificationUri(getContext().getContentResolver(), url);
                       return ret;
              @@ -206,6 +222,9 @@ public class SettingsProvider extends ContentProvider {
                   @Override
                   public int bulkInsert(Uri uri, ContentValues[] values) {
                       SqlArguments args = new SqlArguments(uri);
              +        if (TABLE_FAVORITES.equals(args.table)) {
              +            return 0;
              +        }
                       checkWritePermissions(args);
               
                       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
              @@ -228,6 +247,9 @@ public class SettingsProvider extends ContentProvider {
                   @Override
                   public Uri insert(Uri url, ContentValues initialValues) {
                       SqlArguments args = new SqlArguments(url);
              +        if (TABLE_FAVORITES.equals(args.table)) {
              +            return null;
              +        }
                       checkWritePermissions(args);
               
                       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
              @@ -243,6 +265,11 @@ public class SettingsProvider extends ContentProvider {
                   @Override
                   public int delete(Uri url, String where, String[] whereArgs) {
                       SqlArguments args = new SqlArguments(url, where, whereArgs);
              +        if (TABLE_FAVORITES.equals(args.table)) {
              +            return 0;
              +        } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
              +            args.table = TABLE_FAVORITES;
              +        }
                       checkWritePermissions(args);
               
                       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
              @@ -255,6 +282,9 @@ public class SettingsProvider extends ContentProvider {
                   @Override
                   public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
                       SqlArguments args = new SqlArguments(url, where, whereArgs);
              +        if (TABLE_FAVORITES.equals(args.table)) {
              +            return 0;
              +        }
                       checkWritePermissions(args);
               
                       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
              diff --git a/packages/SubscribedFeedsProvider/AndroidManifest.xml b/packages/SubscribedFeedsProvider/AndroidManifest.xml
              index 94c4be5fd02e48fa64cb55675ab491a2a307858d..6ecda48a7cb545ac2a895e6d72cfb5b50bbd6ac7 100644
              --- a/packages/SubscribedFeedsProvider/AndroidManifest.xml
              +++ b/packages/SubscribedFeedsProvider/AndroidManifest.xml
              @@ -6,7 +6,7 @@
                   
                   
                   
              -        
              +
                   
              -        
              +        
                           
                               
                               
              @@ -29,5 +29,6 @@
                               
                           
                       
              +        
                   
               
              diff --git a/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsBroadcastReceiver.java b/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsBroadcastReceiver.java
              new file mode 100644
              index 0000000000000000000000000000000000000000..35132156667af739d34b28df738bce9b106798b1
              --- /dev/null
              +++ b/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsBroadcastReceiver.java
              @@ -0,0 +1,41 @@
              +/*
              +** Copyright 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.
              +*/
              +
              +package com.android.providers.subscribedfeeds;
              +
              +import android.content.BroadcastReceiver;
              +import android.content.Context;
              +import android.content.Intent;
              +import android.util.Log;
              +
              +/**
              + * Handles the XMPP_CONNECTED_ACTION intent by updating all the
              + * subscribed feeds with the new jabber id and initiating a sync
              + * for all subscriptions.
              + *
              + * Handles the TICKLE_ACTION intent by finding the matching
              + * subscribed feed and intiating a sync for it.
              + */
              +public class SubscribedFeedsBroadcastReceiver extends BroadcastReceiver {
              +
              +    private static final String TAG = "Sync";
              +
              +    public void onReceive(Context context, Intent intent) {
              +        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "Received intent " + intent);
              +            intent.setClass(context, SubscribedFeedsIntentService.class);
              +        context.startService(intent);
              +    }
              +}
              diff --git a/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsService.java b/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsIntentService.java
              similarity index 72%
              rename from packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsService.java
              rename to packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsIntentService.java
              index 4a1de596f4e920015144e96f57e24a57a27640e8..df599c7cfa1d3965545b6e60f743aa7eef2cb8f7 100644
              --- a/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsService.java
              +++ b/packages/SubscribedFeedsProvider/src/com/android/providers/subscribedfeeds/SubscribedFeedsIntentService.java
              @@ -1,61 +1,35 @@
              -/*
              -** Copyright 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.
              -*/
              -
               package com.android.providers.subscribedfeeds;
               
              -import android.app.AlarmManager;
              -import android.app.PendingIntent;
              -import android.content.BroadcastReceiver;
              +import android.content.Intent;
              +import android.content.Context;
               import android.content.ContentResolver;
               import android.content.ContentValues;
              -import android.content.Context;
              -import android.content.Intent;
               import android.content.SharedPreferences;
              -import android.database.Cursor;
              -import android.net.Uri;
              -import android.os.Bundle;
              -import android.provider.SubscribedFeeds;
              +import android.util.Log;
              +import android.util.Config;
              +import android.util.EventLog;
              +import android.app.IntentService;
               import android.provider.Sync;
              +import android.provider.SubscribedFeeds;
               import android.provider.SyncConstValue;
              +import android.database.Cursor;
              +import android.database.sqlite.SQLiteFullException;
              +import android.app.AlarmManager;
              +import android.app.PendingIntent;
              +import android.os.Bundle;
              +import android.os.Debug;
               import android.text.TextUtils;
              -import android.util.Config;
              -import android.util.EventLog;
              -import android.util.Log;
              +import android.net.Uri;
               
               import java.util.ArrayList;
               import java.util.Calendar;
               
               /**
              - * Handles the XMPP_CONNECTED_ACTION intent by updating all the
              - * subscribed feeds with the new jabber id and initiating a sync
              - * for all subscriptions.
              - *
              - * Handles the TICKLE_ACTION intent by finding the matching
              - * subscribed feed and intiating a sync for it.
              + * A service to handle various intents asynchronously.
                */
              -public class SubscribedFeedsService extends BroadcastReceiver {
              -
              +public class SubscribedFeedsIntentService extends IntentService {
                   private static final String TAG = "Sync";
               
              -    private static final String SUBSCRIBED_FEEDS_REFRESH_ACTION =
              -            "com.android.subscribedfeeds.action.REFRESH";
              -
              -    private static final Intent sSubscribedFeedsRefreshIntent =
              -            new Intent(SUBSCRIBED_FEEDS_REFRESH_ACTION);
              -
                   private static final String[] sAccountProjection =
                           new String[] {SubscribedFeeds.Accounts._SYNC_ACCOUNT};
               
              @@ -66,11 +40,20 @@ public class SubscribedFeedsService extends BroadcastReceiver {
               
                   private static final String sSubscribedFeedsPrefs = "subscribedFeeds";
               
              -    static final int LOG_TICKLE = 2742;
              +    private static final String GTALK_DATA_MESSAGE_RECEIVED =
              +            "android.intent.action.GTALK_DATA_MESSAGE_RECEIVED";
               
              -    public void onReceive(Context context, Intent intent) {
              -        if ("android.intent.action.GTALK_DATA_MESSAGE_RECEIVED".equals(
              -                intent.getAction())) {
              +    private static final String SUBSCRIBED_FEEDS_REFRESH_ACTION =
              +            "com.android.subscribedfeeds.action.REFRESH";
              +
              +    private static final int LOG_TICKLE = 2742;
              +
              +    public SubscribedFeedsIntentService() {
              +        super("SubscribedFeedsIntentService");
              +    }
              +
              +    protected void onHandleIntent(Intent intent) {
              +        if (GTALK_DATA_MESSAGE_RECEIVED.equals(intent.getAction())) {
                           boolean fromTrustedServer = intent.getBooleanExtra("from_trusted_server", false);
                           if (fromTrustedServer) {
                               String account = intent.getStringExtra("account");
              @@ -88,7 +71,7 @@ public class SubscribedFeedsService extends BroadcastReceiver {
                                           + account + " - " + token);
                               }
               
              -                handleTickle(context, account, token);
              +                handleTickle(this, account, token);
                           } else {
                               if (Log.isLoggable(TAG, Log.VERBOSE)) {
                                   Log.v(TAG, "Ignoring tickle -- not from trusted server.");
              @@ -101,25 +84,23 @@ public class SubscribedFeedsService extends BroadcastReceiver {
                               Log.d(TAG, "Received boot completed action");
                           }
                           // load the time from the shared preferences and schedule an alarm
              -            long refreshTime = context.getSharedPreferences(
              +            long refreshTime = getSharedPreferences(
                                   sSubscribedFeedsPrefs,
                                   Context.MODE_WORLD_READABLE).getLong(sRefreshTime, 0);
              -            scheduleRefresh(context, refreshTime);
              -        } else if (sSubscribedFeedsRefreshIntent.getAction().equals(
              -                intent.getAction())) {
              +            scheduleRefresh(this, refreshTime);
              +        } else if (SUBSCRIBED_FEEDS_REFRESH_ACTION.equals(intent.getAction())) {
                           if (Config.LOGD) {
                               Log.d(TAG, "Received sSubscribedFeedsRefreshIntent");
                           }
              -            handleRefreshAlarm(context);
              +            handleRefreshAlarm(this);
                       }
                   }
              -
                   private void scheduleRefresh(Context context, long when) {
                       AlarmManager alarmManager = (AlarmManager) context.getSystemService(
                               Context.ALARM_SERVICE);
              -        PendingIntent sender = PendingIntent.getBroadcast(context,
              -                0, sSubscribedFeedsRefreshIntent, 0);
              -        alarmManager.set(AlarmManager.RTC, when, sender);
              +        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
              +                0, new Intent(SUBSCRIBED_FEEDS_REFRESH_ACTION), 0);
              +        alarmManager.set(AlarmManager.RTC, when, pendingIntent);
                   }
               
                   private void handleTickle(Context context, String account, String feed) {
              @@ -189,20 +170,22 @@ public class SubscribedFeedsService extends BroadcastReceiver {
               
                       // mark the feeds dirty, by setting the accounts to the same value,
                       //  which will trigger a sync.
              -        ContentValues values = new ContentValues();
              -        for (String account : accounts) {
              -            values.put(SyncConstValue._SYNC_ACCOUNT, account);
              -            contentResolver.update(SubscribedFeeds.Feeds.CONTENT_URI, values,
              -                    SubscribedFeeds.Feeds._SYNC_ACCOUNT + "=?", new String[] {account});
              +        try {
              +            ContentValues values = new ContentValues();
              +            for (String account : accounts) {
              +                values.put(SyncConstValue._SYNC_ACCOUNT, account);
              +                contentResolver.update(SubscribedFeeds.Feeds.CONTENT_URI, values,
              +                        SubscribedFeeds.Feeds._SYNC_ACCOUNT + "=?", new String[] {account});
              +            }
              +        } catch (SQLiteFullException e) {
              +            Log.w(TAG, "disk full while trying to mark the feeds as dirty, skipping");
                       }
               
                       // Schedule a refresh.
                       long refreshTime = Calendar.getInstance().getTimeInMillis() + SUBSCRIPTION_REFRESH_INTERVAL;
                       scheduleRefresh(context, refreshTime);
              -        SharedPreferences preferences = context
              -                .getSharedPreferences(sSubscribedFeedsPrefs,
              -                        Context.MODE_WORLD_READABLE);
              -        SharedPreferences.Editor editor = preferences.edit();
              +        SharedPreferences.Editor editor = context.getSharedPreferences(sSubscribedFeedsPrefs,
              +                Context.MODE_WORLD_READABLE).edit();
                       editor.putLong(sRefreshTime, refreshTime);
                       editor.commit();
                   }
              diff --git a/preloaded-classes b/preloaded-classes
              index 160ebef826d2b80423f067d97f120c7f6dad49b7..b91f41b46d702fa0b9394fc9827544e6ce9f080f 100644
              --- a/preloaded-classes
              +++ b/preloaded-classes
              @@ -160,7 +160,7 @@ android.graphics.drawable.DrawableContainer
               android.graphics.drawable.GradientDrawable
               android.graphics.drawable.LayerDrawable
               android.graphics.drawable.LayerDrawable$LayerState
              -android.graphics.drawable.LayerDrawable$Rec
              +android.graphics.drawable.LayerDrawable$ChildDrawable
               android.graphics.drawable.NinePatchDrawable
               android.graphics.drawable.NinePatchDrawable$NinePatchState
               android.graphics.drawable.PaintDrawable
              @@ -340,7 +340,7 @@ android.view.TouchDelegate
               android.view.VelocityTracker
               android.view.View
               android.view.View$AttachInfo
              -android.view.View$AttachInfo$SoundEffectPlayer
              +android.view.View$AttachInfo$Callbacks
               android.view.View$BaseSavedState$1
               android.view.View$MeasureSpec
               android.view.View$ScrollabilityCache
              @@ -366,7 +366,6 @@ android.view.animation.Transformation
               android.view.inputmethod.BaseInputConnection
               android.view.inputmethod.CompletionInfo$1
               android.view.inputmethod.CompletionInfo
              -android.view.inputmethod.DefaultInputMethod
               android.view.inputmethod.EditorInfo$1
               android.view.inputmethod.EditorInfo
               android.view.inputmethod.ExtractedText$1
              @@ -376,23 +375,16 @@ android.view.inputmethod.ExtractedTextRequest
               android.view.inputmethod.InputBinding$1
               android.view.inputmethod.InputBinding
               android.view.inputmethod.InputConnection
              -android.view.inputmethod.InputConnectionWrapper
               android.view.inputmethod.InputMethod$SessionCallback
               android.view.inputmethod.InputMethod
               android.view.inputmethod.InputMethodInfo$1
               android.view.inputmethod.InputMethodInfo
               android.view.inputmethod.InputMethodManager$1
               android.view.inputmethod.InputMethodManager$2
              -android.view.inputmethod.InputMethodManager$3
              -android.view.inputmethod.InputMethodManager$NoOpInputConnection
              +android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper
               android.view.inputmethod.InputMethodManager
               android.view.inputmethod.InputMethodSession$EventCallback
               android.view.inputmethod.InputMethodSession
              -android.view.inputmethod.MutableInputConnectionWrapper
              -android.view.inputmethod.SimpleInputMethod$InputMethodSessionCallbackWrapper
              -android.view.inputmethod.SimpleInputMethod$Session$InputMethodEventCallbackWrapper
              -android.view.inputmethod.SimpleInputMethod$Session
              -android.view.inputmethod.SimpleInputMethod
               android.webkit.BrowserFrame
               android.webkit.CacheManager
               android.webkit.CallbackProxy
              @@ -507,8 +499,6 @@ com.android.internal.logging.AndroidConfig
               com.android.internal.logging.AndroidHandler
               com.android.internal.os.AndroidPrintStream
               com.android.internal.os.BinderInternal$GcWatcher
              -com.android.internal.os.HandlerHelper
              -com.android.internal.os.HandlerThread
               com.android.internal.os.LoggingPrintStream
               com.android.internal.os.LoggingPrintStream$1
               com.android.internal.os.RuntimeInit
              @@ -793,7 +783,7 @@ org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl
               org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLInputStream
               org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLOutputStream
               org.apache.harmony.xnet.provider.jsse.SSLParameters
              -org.apache.harmony.xnet.provider.jsse.SSLSessionContextImpl$1
              +org.apache.harmony.xnet.provider.jsse.ClientSessionContext
               org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl
               org.apache.harmony.xnet.provider.jsse.TrustManagerImpl
               org.apache.http.HttpHost
              diff --git a/services/Android.mk b/services/java/Android.mk
              similarity index 100%
              rename from services/Android.mk
              rename to services/java/Android.mk
              diff --git a/services/java/com/android/server/AlarmManagerService.java b/services/java/com/android/server/AlarmManagerService.java
              index 162585395d2e5d82a1c016f2f2332900d2925fd1..d66c6e5e120450883bd6d7fa6205d6707265d90e 100644
              --- a/services/java/com/android/server/AlarmManagerService.java
              +++ b/services/java/com/android/server/AlarmManagerService.java
              @@ -34,21 +34,26 @@ import android.os.PowerManager;
               import android.os.SystemClock;
               import android.os.SystemProperties;
               import android.text.TextUtils;
              -import android.util.Config;
              +import android.text.format.Time;
              +import android.util.EventLog;
               import android.util.Log;
               
               import java.io.FileDescriptor;
              -import java.io.IOException;
               import java.io.PrintWriter;
               import java.util.ArrayList;
               import java.util.Calendar;
               import java.util.Collections;
              +import java.util.Comparator;
               import java.util.HashMap;
               import java.util.Iterator;
               import java.util.Map;
               import java.util.TimeZone;
               
               class AlarmManagerService extends IAlarmManager.Stub {
              +    // The threshold for how long an alarm can be late before we print a
              +    // warning message.  The time duration is in milliseconds.
              +    private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
              +    
                   private static final int RTC_WAKEUP_MASK = 1 << AlarmManager.RTC_WAKEUP;
                   private static final int RTC_MASK = 1 << AlarmManager.RTC;
                   private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << AlarmManager.ELAPSED_REALTIME_WAKEUP; 
              @@ -72,6 +77,7 @@ class AlarmManagerService extends IAlarmManager.Stub {
                   private final ArrayList mRtcAlarms = new ArrayList();
                   private final ArrayList mElapsedRealtimeWakeupAlarms = new ArrayList();
                   private final ArrayList mElapsedRealtimeAlarms = new ArrayList();
              +    private final IncreasingTimeOrder mIncreasingTimeOrder = new IncreasingTimeOrder();
                   
                   // slots corresponding with the inexact-repeat interval buckets,
                   // ordered from shortest to longest
              @@ -250,12 +256,12 @@ class AlarmManagerService extends IAlarmManager.Stub {
                               if (localLOGV) Log.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
                               timeZoneWasChanged = true; 
                               SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
              -                
              -                // Update the kernel timezone information
              -                // Kernel tracks time offsets as 'minutes west of GMT'
              -                int gmtOffset = (zone.getRawOffset() + zone.getDSTSavings()) / 60000;
              -                setKernelTimezone(mDescriptor, -(gmtOffset));
                           }
              +            
              +            // Update the kernel timezone information
              +            // Kernel tracks time offsets as 'minutes west of GMT'
              +            int gmtOffset = (zone.getRawOffset() + zone.getDSTSavings()) / 60000;
              +            setKernelTimezone(mDescriptor, -(gmtOffset));
                       }
               
                       TimeZone.setDefault(null);
              @@ -338,11 +344,26 @@ class AlarmManagerService extends IAlarmManager.Stub {
                   private int addAlarmLocked(Alarm alarm) {
                       ArrayList alarmList = getAlarmList(alarm.type);
                       
              -        int index = Collections.binarySearch(alarmList, alarm);
              -        index = (index < 0) ? ((index + 1) * -1) : index;
              -        if (localLOGV) Log.v(
              -            TAG, "Adding alarm " + alarm + " at " + index);
              +        int index = Collections.binarySearch(alarmList, alarm, mIncreasingTimeOrder);
              +        if (index < 0) {
              +            index = 0 - index - 1;
              +        }
              +        if (localLOGV) Log.v(TAG, "Adding alarm " + alarm + " at " + index);
                       alarmList.add(index, alarm);
              +
              +        if (localLOGV) {
              +            // Display the list of alarms for this alarm type
              +            Log.v(TAG, "alarms: " + alarmList.size() + " type: " + alarm.type);
              +            int position = 0;
              +            for (Alarm a : alarmList) {
              +                Time time = new Time();
              +                time.set(a.when);
              +                String timeStr = time.format("%b %d %I:%M:%S %p");
              +                Log.v(TAG, position + ": " + timeStr
              +                        + " " + a.operation.getTargetPackage());
              +                position += 1;
              +            }
              +        }
                       
                       return index;
                   }
              @@ -382,7 +403,7 @@ class AlarmManagerService extends IAlarmManager.Stub {
                   
                   @Override
                   protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
              -        if (mContext.checkCallingPermission("android.permission.DUMP")
              +        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
                               != PackageManager.PERMISSION_GRANTED) {
                           pw.println("Permission Denial: can't dump AlarmManager from from pid="
                                   + Binder.getCallingPid()
              @@ -459,14 +480,22 @@ class AlarmManagerService extends IAlarmManager.Stub {
               
                           if (localLOGV) Log.v(TAG, "Checking active alarm when=" + alarm.when + " " + alarm);
               
              -            if (alarm.when > now)
              -            {
              +            if (alarm.when > now) {
                               // don't fire alarms in the future
                               break;
                           }
              +            
              +            // If the alarm is late, then print a warning message.
              +            // Note that this can happen if the user creates a new event on
              +            // the Calendar app with a reminder that is in the past. In that
              +            // case, the reminder alarm will fire immediately.
              +            if (localLOGV && now - alarm.when > LATE_ALARM_THRESHOLD) {
              +                Log.v(TAG, "alarm is late! alarm time: " + alarm.when
              +                        + " now: " + now + " delay (in seconds): "
              +                        + (now - alarm.when) / 1000);
              +            }
               
              -            // add it to the trigger list so we can trigger it without the lock held.
              -            // recurring alarms may have passed several alarm intervals while the
              +            // Recurring alarms may have passed several alarm intervals while the
                           // phone was asleep or off, so pass a trigger count when sending them.
                           if (localLOGV) Log.v(TAG, "Alarm triggering: " + alarm);
                           alarm.count = 1;
              @@ -481,28 +510,42 @@ class AlarmManagerService extends IAlarmManager.Stub {
                           it.remove();
                           
                           // if it repeats queue it up to be read-added to the list
              -            if (alarm.repeatInterval > 0)
              -            {
              +            if (alarm.repeatInterval > 0) {
                               repeats.add(alarm);
                           }
                       }
               
                       // reset any repeating alarms.
                       it = repeats.iterator();
              -        while (it.hasNext())
              -        {
              +        while (it.hasNext()) {
                           Alarm alarm = it.next();
                           alarm.when += alarm.count * alarm.repeatInterval;
                           addAlarmLocked(alarm);
                       }
                       
              -        if (alarmList.size() > 0)
              -        {
              +        if (alarmList.size() > 0) {
                           setLocked(alarmList.get(0));
                       }
                   }
                   
              -    private class Alarm implements Comparable {
              +    /**
              +     * This Comparator sorts Alarms into increasing time order.
              +     */
              +    public static class IncreasingTimeOrder implements Comparator {
              +        public int compare(Alarm a1, Alarm a2) {
              +            long when1 = a1.when;
              +            long when2 = a2.when;
              +            if (when1 - when2 > 0) {
              +                return 1;
              +            }
              +            if (when1 - when2 < 0) {
              +                return -1;
              +            }
              +            return 0;
              +        }
              +    }
              +    
              +    private static class Alarm {
                       public int type;
                       public int count;
                       public long when;
              @@ -515,15 +558,7 @@ class AlarmManagerService extends IAlarmManager.Stub {
                           operation = null;
                       }
                       
              -        public int compareTo(Alarm obj)
              -        {
              -            if (obj.when > this.when) return -1;
              -            if (obj.when < this.when) return 1;
              -            if (obj.operation.equals(this.operation)
              -                    && obj.repeatInterval == this.repeatInterval) return 0;
              -            return -1;
              -        }
              -        
              +        @Override
                       public String toString()
                       {
                           return "Alarm{"
              @@ -701,11 +736,11 @@ class AlarmManagerService extends IAlarmManager.Stub {
                       public void scheduleDateChangedEvent() {
                           Calendar calendar = Calendar.getInstance();
                           calendar.setTimeInMillis(System.currentTimeMillis());
              -            calendar.add(Calendar.DAY_OF_MONTH, 1);
                           calendar.set(Calendar.HOUR, 0);
                           calendar.set(Calendar.MINUTE, 0);
                           calendar.set(Calendar.SECOND, 0);
                           calendar.set(Calendar.MILLISECOND, 0);
              +            calendar.add(Calendar.DAY_OF_MONTH, 1);
                     
                           set(AlarmManager.RTC, calendar.getTimeInMillis(), mDateChangeSender);
                       }
              diff --git a/services/java/com/android/server/AppWidgetService.java b/services/java/com/android/server/AppWidgetService.java
              new file mode 100644
              index 0000000000000000000000000000000000000000..de5d0acf7482f110a0695d860a09ec829b6362de
              --- /dev/null
              +++ b/services/java/com/android/server/AppWidgetService.java
              @@ -0,0 +1,1148 @@
              +/*
              + * 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.
              + */
              +
              +package com.android.server;
              +
              +import android.app.AlarmManager;
              +import android.app.PendingIntent;
              +import android.appwidget.AppWidgetManager;
              +import android.appwidget.AppWidgetProviderInfo;
              +import android.content.BroadcastReceiver;
              +import android.content.ComponentName;
              +import android.content.Context;
              +import android.content.Intent;
              +import android.content.IntentFilter;
              +import android.content.pm.ActivityInfo;
              +import android.content.pm.PackageManager;
              +import android.content.pm.PackageInfo;
              +import android.content.pm.ResolveInfo;
              +import android.content.pm.PackageItemInfo;
              +import android.content.res.TypedArray;
              +import android.content.res.XmlResourceParser;
              +import android.net.Uri;
              +import android.os.Binder;
              +import android.os.Bundle;
              +import android.os.RemoteException;
              +import android.os.SystemClock;
              +import android.util.AttributeSet;
              +import android.util.Log;
              +import android.util.Xml;
              +import android.widget.RemoteViews;
              +
              +import java.io.IOException;
              +import java.io.File;
              +import java.io.FileDescriptor;
              +import java.io.FileInputStream;
              +import java.io.FileOutputStream;
              +import java.io.PrintWriter;
              +import java.util.ArrayList;
              +import java.util.List;
              +import java.util.HashMap;
              +import java.util.HashSet;
              +
              +import com.android.internal.appwidget.IAppWidgetService;
              +import com.android.internal.appwidget.IAppWidgetHost;
              +import com.android.internal.util.XmlUtils;
              +import com.android.internal.util.FastXmlSerializer;
              +
              +import org.xmlpull.v1.XmlPullParser;
              +import org.xmlpull.v1.XmlPullParserException;
              +import org.xmlpull.v1.XmlSerializer;
              +
              +class AppWidgetService extends IAppWidgetService.Stub
              +{
              +    private static final String TAG = "AppWidgetService";
              +
              +    private static final String SETTINGS_FILENAME = "appwidgets.xml";
              +    private static final String SETTINGS_TMP_FILENAME = SETTINGS_FILENAME + ".tmp";
              +
              +    /*
              +     * When identifying a Host or Provider based on the calling process, use the uid field.
              +     * When identifying a Host or Provider based on a package manager broadcast, use the
              +     * package given.
              +     */
              +
              +    static class Provider {
              +        int uid;
              +        AppWidgetProviderInfo info;
              +        ArrayList instances = new ArrayList();
              +        PendingIntent broadcast;
              +        boolean zombie; // if we're in safe mode, don't prune this just because nobody references it
              +        
              +        int tag;    // for use while saving state (the index)
              +    }
              +
              +    static class Host {
              +        int uid;
              +        int hostId;
              +        String packageName;
              +        ArrayList instances = new ArrayList();
              +        IAppWidgetHost callbacks;
              +        boolean zombie; // if we're in safe mode, don't prune this just because nobody references it
              +        
              +        int tag;    // for use while saving state (the index)
              +    }
              +
              +    static class AppWidgetId {
              +        int appWidgetId;
              +        Provider provider;
              +        RemoteViews views;
              +        Host host;
              +    }
              +
              +    Context mContext;
              +    PackageManager mPackageManager;
              +    AlarmManager mAlarmManager;
              +    ArrayList mInstalledProviders = new ArrayList();
              +    int mNextAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID + 1;
              +    ArrayList mAppWidgetIds = new ArrayList();
              +    ArrayList mHosts = new ArrayList();
              +    boolean mSafeMode;
              +
              +    AppWidgetService(Context context) {
              +        mContext = context;
              +        mPackageManager = context.getPackageManager();
              +        mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
              +    }
              +
              +    public void systemReady(boolean safeMode) {
              +        mSafeMode = safeMode;
              +
              +        loadAppWidgetList();
              +        loadStateLocked();
              +
              +        // Register for the boot completed broadcast, so we can send the
              +        // ENABLE broacasts.  If we try to send them now, they time out,
              +        // because the system isn't ready to handle them yet.
              +        mContext.registerReceiver(mBroadcastReceiver,
              +                new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
              +
              +        // Register for broadcasts about package install, etc., so we can
              +        // update the provider list.
              +        IntentFilter filter = new IntentFilter();
              +        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
              +        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
              +        filter.addDataScheme("package");
              +        mContext.registerReceiver(mBroadcastReceiver, filter);
              +    }
              +
              +    @Override
              +    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
              +        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
              +                != PackageManager.PERMISSION_GRANTED) {
              +            pw.println("Permission Denial: can't dump from from pid="
              +                    + Binder.getCallingPid()
              +                    + ", uid=" + Binder.getCallingUid());
              +            return;
              +        }
              +
              +        synchronized (mAppWidgetIds) {
              +            int N = mInstalledProviders.size();
              +            pw.println("Providers: (size=" + N + ")");
              +            for (int i=0; i getInstalledProviders() {
              +        synchronized (mAppWidgetIds) {
              +            final int N = mInstalledProviders.size();
              +            ArrayList result = new ArrayList(N);
              +            for (int i=0; i instances = p.instances;
              +            final int N = instances.size();
              +            for (int i=0; i updatedViews) {
              +        int callingUid = enforceCallingUid(packageName);
              +        synchronized (mAppWidgetIds) {
              +            Host host = lookupOrAddHostLocked(callingUid, packageName, hostId);
              +            host.callbacks = callbacks;
              +
              +            updatedViews.clear();
              +
              +            ArrayList instances = host.instances;
              +            int N = instances.size();
              +            int[] updatedIds = new int[N];
              +            for (int i=0; i broadcastReceivers = pm.queryBroadcastReceivers(intent,
              +                PackageManager.GET_META_DATA);
              +
              +        final int N = broadcastReceivers.size();
              +        for (int i=0; i 0) {
              +            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
              +            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
              +            intent.setComponent(p.info.provider);
              +            mContext.sendBroadcast(intent);
              +        }
              +    }
              +
              +    void registerForBroadcastsLocked(Provider p, int[] appWidgetIds) {
              +        if (p.info.updatePeriodMillis > 0) {
              +            // if this is the first instance, set the alarm.  otherwise,
              +            // rely on the fact that we've already set it and that
              +            // PendingIntent.getBroadcast will update the extras.
              +            boolean alreadyRegistered = p.broadcast != null;
              +            int instancesSize = p.instances.size();
              +            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
              +            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
              +            intent.setComponent(p.info.provider);
              +            long token = Binder.clearCallingIdentity();
              +            try {
              +                p.broadcast = PendingIntent.getBroadcast(mContext, 1, intent,
              +                        PendingIntent.FLAG_UPDATE_CURRENT);
              +            } finally {
              +                Binder.restoreCallingIdentity(token);
              +            }
              +            if (!alreadyRegistered) {
              +                mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
              +                        SystemClock.elapsedRealtime() + p.info.updatePeriodMillis,
              +                        p.info.updatePeriodMillis, p.broadcast);
              +            }
              +        }
              +    }
              +    
              +    static int[] getAppWidgetIds(Provider p) {
              +        int instancesSize = p.instances.size();
              +        int appWidgetIds[] = new int[instancesSize];
              +        for (int i=0; i 0) {
              +                    out.startTag(null, "p");
              +                    out.attribute(null, "pkg", p.info.provider.getPackageName());
              +                    out.attribute(null, "cl", p.info.provider.getClassName());
              +                    out.endTag(null, "h");
              +                    p.tag = providerIndex;
              +                    providerIndex++;
              +                }
              +            }
              +
              +            N = mHosts.size();
              +            for (int i=0; i loadedProviders = new HashMap();
              +            do {
              +                type = parser.next();
              +                if (type == XmlPullParser.START_TAG) {
              +                    String tag = parser.getName();
              +                    if ("p".equals(tag)) {
              +                        // TODO: do we need to check that this package has the same signature
              +                        // as before?
              +                        String pkg = parser.getAttributeValue(null, "pkg");
              +                        String cl = parser.getAttributeValue(null, "cl");
              +                        Provider p = lookupProviderLocked(new ComponentName(pkg, cl));
              +                        if (p == null && mSafeMode) {
              +                            // if we're in safe mode, make a temporary one
              +                            p = new Provider();
              +                            p.info = new AppWidgetProviderInfo();
              +                            p.info.provider = new ComponentName(pkg, cl);
              +                            p.zombie = true;
              +                            mInstalledProviders.add(p);
              +                        }
              +                        if (p != null) {
              +                            // if it wasn't uninstalled or something
              +                            loadedProviders.put(providerIndex, p);
              +                        }
              +                        providerIndex++;
              +                    }
              +                    else if ("h".equals(tag)) {
              +                        Host host = new Host();
              +
              +                        // TODO: do we need to check that this package has the same signature
              +                        // as before?
              +                        host.packageName = parser.getAttributeValue(null, "pkg");
              +                        try {
              +                            host.uid = getUidForPackage(host.packageName);
              +                        } catch (PackageManager.NameNotFoundException ex) {
              +                            host.zombie = true;
              +                        }
              +                        if (!host.zombie || mSafeMode) {
              +                            // In safe mode, we don't discard the hosts we don't recognize
              +                            // so that they're not pruned from our list.  Otherwise, we do.
              +                            host.hostId = Integer.parseInt(
              +                                    parser.getAttributeValue(null, "id"), 16);
              +                            mHosts.add(host);
              +                        }
              +                    }
              +                    else if ("g".equals(tag)) {
              +                        AppWidgetId id = new AppWidgetId();
              +                        id.appWidgetId = Integer.parseInt(parser.getAttributeValue(null, "id"), 16);
              +                        if (id.appWidgetId >= mNextAppWidgetId) {
              +                            mNextAppWidgetId = id.appWidgetId + 1;
              +                        }
              +
              +                        String providerString = parser.getAttributeValue(null, "p");
              +                        if (providerString != null) {
              +                            // there's no provider if it hasn't been bound yet.
              +                            // maybe we don't have to save this, but it brings the system
              +                            // to the state it was in.
              +                            int pIndex = Integer.parseInt(providerString, 16);
              +                            id.provider = loadedProviders.get(pIndex);
              +                            if (false) {
              +                                Log.d(TAG, "bound appWidgetId=" + id.appWidgetId + " to provider "
              +                                        + pIndex + " which is " + id.provider);
              +                            }
              +                            if (id.provider == null) {
              +                                // This provider is gone.  We just let the host figure out
              +                                // that this happened when it fails to load it.
              +                                continue;
              +                            }
              +                        }
              +
              +                        int hIndex = Integer.parseInt(parser.getAttributeValue(null, "h"), 16);
              +                        id.host = mHosts.get(hIndex);
              +                        if (id.host == null) {
              +                            // This host is gone.
              +                            continue;
              +                        }
              +
              +                        if (id.provider != null) {
              +                            id.provider.instances.add(id);
              +                        }
              +                        id.host.instances.add(id);
              +                        mAppWidgetIds.add(id);
              +                    }
              +                }
              +            } while (type != XmlPullParser.END_DOCUMENT);
              +            success = true;
              +        } catch (NullPointerException e) {
              +            Log.w(TAG, "failed parsing " + file, e);
              +        } catch (NumberFormatException e) {
              +            Log.w(TAG, "failed parsing " + file, e);
              +        } catch (XmlPullParserException e) {
              +            Log.w(TAG, "failed parsing " + file, e);
              +        } catch (IOException e) {
              +            Log.w(TAG, "failed parsing " + file, e);
              +        } catch (IndexOutOfBoundsException e) {
              +            Log.w(TAG, "failed parsing " + file, e);
              +        }
              +        try {
              +            if (stream != null) {
              +                stream.close();
              +            }
              +        } catch (IOException e) {
              +        }
              +
              +        if (success) {
              +            // delete any hosts that didn't manage to get connected (should happen)
              +            // if it matters, they'll be reconnected.
              +            final int N = mHosts.size();
              +            for (int i=0; i broadcastReceivers = mPackageManager.queryBroadcastReceivers(intent,
              +                PackageManager.GET_META_DATA);
              +
              +        final int N = broadcastReceivers.size();
              +        for (int i=0; i keep = new HashSet();
              +        Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
              +        List broadcastReceivers = mPackageManager.queryBroadcastReceivers(intent,
              +                PackageManager.GET_META_DATA);
              +
              +        // add the missing ones and collect which ones to keep
              +        int N = broadcastReceivers.size();
              +        for (int i=0; i 0) {
              +                            int[] appWidgetIds = getAppWidgetIds(p);
              +                            // Reschedule for the new updatePeriodMillis (don't worry about handling
              +                            // it specially if updatePeriodMillis didn't change because we just sent
              +                            // an update, and the next one will be updatePeriodMillis from now).
              +                            cancelBroadcasts(p);
              +                            registerForBroadcastsLocked(p, appWidgetIds);
              +                            // If it's currently showing, call back with the new AppWidgetProviderInfo.
              +                            for (int j=0; j=0; i--) {
              +            Provider p = mInstalledProviders.get(i);
              +            if (pkgName.equals(p.info.provider.getPackageName())
              +                    && !keep.contains(p.info.provider.getClassName())) {
              +                removeProviderLocked(i, p);
              +            }
              +        }
              +    }
              +
              +    void removeProvidersForPackageLocked(String pkgName) {
              +        int N = mInstalledProviders.size();
              +        for (int i=N-1; i>=0; i--) {
              +            Provider p = mInstalledProviders.get(i);
              +            if (pkgName.equals(p.info.provider.getPackageName())) {
              +                removeProviderLocked(i, p);
              +            }
              +        }
              +
              +        // Delete the hosts for this package too
              +        //
              +        // By now, we have removed any AppWidgets that were in any hosts here,
              +        // so we don't need to worry about sending DISABLE broadcasts to them.
              +        N = mHosts.size();
              +        for (int i=N-1; i>=0; i--) {
              +            Host host = mHosts.get(i);
              +            if (pkgName.equals(host.packageName)) {
              +                deleteHostLocked(host);
              +            }
              +        }
              +    }
              +}
              +
              diff --git a/services/java/com/android/server/BatteryService.java b/services/java/com/android/server/BatteryService.java
              index ed53272b2856dae9b232e5b61dc472184d298cb4..618b317cb336bdedd12d27e2cc4be5de3876228c 100644
              --- a/services/java/com/android/server/BatteryService.java
              +++ b/services/java/com/android/server/BatteryService.java
              @@ -20,19 +20,31 @@ import com.android.internal.app.IBatteryStats;
               import com.android.server.am.BatteryStatsService;
               
               import android.app.ActivityManagerNative;
              +import android.content.ContentResolver;
               import android.content.Context;
               import android.content.Intent;
               import android.content.pm.PackageManager;
               import android.os.BatteryManager;
               import android.os.Binder;
              +import android.os.Debug;
              +import android.os.IBinder;
               import android.os.RemoteException;
              +import android.os.ServiceManager;
              +import android.os.SystemClock;
               import android.os.UEventObserver;
              +import android.provider.Checkin;
              +import android.provider.Settings;
               import android.util.EventLog;
               import android.util.Log;
               
              +import java.io.File;
               import java.io.FileDescriptor;
              +import java.io.FileInputStream;
              +import java.io.FileOutputStream;
              +import java.io.IOException;
               import java.io.PrintWriter;
              -import java.lang.String;
              +
              +
               
               /**
                * 

              BatteryService monitors the charging status, and charge level of the device @@ -59,11 +71,27 @@ import java.lang.String; class BatteryService extends Binder { private static final String TAG = BatteryService.class.getSimpleName(); + private static final boolean LOCAL_LOGV = false; + static final int LOG_BATTERY_LEVEL = 2722; static final int LOG_BATTERY_STATUS = 2723; + static final int LOG_BATTERY_DISCHARGE_STATUS = 2730; static final int BATTERY_SCALE = 100; // battery capacity is a percentage + // Used locally for determining when to make a last ditch effort to log + // discharge stats before the device dies. + private static final int CRITICAL_BATTERY_LEVEL = 4; + + private static final int DUMP_MAX_LENGTH = 24 * 1024; + private static final String[] DUMPSYS_ARGS = new String[] { "-c", "-u" }; + private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo"; + + private static final String DUMPSYS_DATA_PATH = "/data/system/"; + + // This should probably be exposed in the API, though it's not critical + private static final int BATTERY_PLUGGED_NONE = 0; + private final Context mContext; private final IBatteryStats mBatteryStats; @@ -76,6 +104,7 @@ class BatteryService extends Binder { private int mBatteryVoltage; private int mBatteryTemperature; private String mBatteryTechnology; + private boolean mBatteryLevelCritical; private int mLastBatteryStatus; private int mLastBatteryHealth; @@ -83,9 +112,14 @@ class BatteryService extends Binder { private int mLastBatteryLevel; private int mLastBatteryVoltage; private int mLastBatteryTemperature; + private boolean mLastBatteryLevelCritical; private int mPlugType; - private int mLastPlugType; + private int mLastPlugType = -1; // Extra state so we can detect first run + + private long mDischargeStartTime; + private int mDischargeStartLevel; + public BatteryService(Context context) { mContext = context; @@ -113,9 +147,10 @@ class BatteryService extends Binder { } int plugTypeBit = 0; if (mAcOnline) { - plugTypeBit = BatteryManager.BATTERY_PLUGGED_AC; - } else if (mUsbOnline) { - plugTypeBit = BatteryManager.BATTERY_PLUGGED_USB; + plugTypeBit |= BatteryManager.BATTERY_PLUGGED_AC; + } + if (mUsbOnline) { + plugTypeBit |= BatteryManager.BATTERY_PLUGGED_USB; } return (plugTypeSet & plugTypeBit) != 0; } @@ -140,12 +175,14 @@ class BatteryService extends Binder { private synchronized final void update() { native_update(); + + mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL; if (mAcOnline) { mPlugType = BatteryManager.BATTERY_PLUGGED_AC; } else if (mUsbOnline) { mPlugType = BatteryManager.BATTERY_PLUGGED_USB; } else { - mPlugType = 0; + mPlugType = BATTERY_PLUGGED_NONE; } if (mBatteryStatus != mLastBatteryStatus || mBatteryHealth != mLastBatteryHealth || @@ -155,6 +192,27 @@ class BatteryService extends Binder { mBatteryVoltage != mLastBatteryVoltage || mBatteryTemperature != mLastBatteryTemperature) { + if (mPlugType != mLastPlugType) { + if (mLastPlugType == BATTERY_PLUGGED_NONE) { + // discharging -> charging + + // There's no value in this data unless we've discharged at least once and the + // battery level has changed; so don't log until it does. + if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) { + long duration = SystemClock.elapsedRealtime() - mDischargeStartTime; + EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, duration, + mDischargeStartLevel, mBatteryLevel); + // make sure we see a discharge event before logging again + mDischargeStartTime = 0; + + logOutlier(duration); + } + } else if (mPlugType == BATTERY_PLUGGED_NONE) { + // charging -> discharging or we just powered up + mDischargeStartTime = SystemClock.elapsedRealtime(); + mDischargeStartLevel = mBatteryLevel; + } + } if (mBatteryStatus != mLastBatteryStatus || mBatteryHealth != mLastBatteryHealth || mBatteryPresent != mLastBatteryPresent || @@ -169,6 +227,12 @@ class BatteryService extends Binder { EventLog.writeEvent(LOG_BATTERY_LEVEL, mBatteryLevel, mBatteryVoltage, mBatteryTemperature); } + if (mBatteryLevelCritical && !mLastBatteryLevelCritical && + mPlugType == BATTERY_PLUGGED_NONE) { + // We want to make sure we log discharge cycle outliers + // if the battery is about to die. + logOutlier(SystemClock.elapsedRealtime() - mDischargeStartTime); + } // Separate broadcast is sent for power connected / not connected // since the standard intent will not wake any applications and some @@ -187,6 +251,7 @@ class BatteryService extends Binder { mLastPlugType = mPlugType; mLastBatteryVoltage = mBatteryVoltage; mLastBatteryTemperature = mBatteryTemperature; + mLastBatteryLevelCritical = mBatteryLevelCritical; sendIntent(); } @@ -197,7 +262,7 @@ class BatteryService extends Binder { Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); try { - mBatteryStats.setOnBattery(mPlugType == 0); + mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE); } catch (RemoteException e) { // Should never happen. } @@ -229,6 +294,83 @@ class BatteryService extends Binder { ActivityManagerNative.broadcastStickyIntent(intent, null); } + private final void logBatteryStats() { + + IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME); + if (batteryInfoService != null) { + byte[] buffer = new byte[DUMP_MAX_LENGTH]; + File dumpFile = null; + FileOutputStream dumpStream = null; + try { + // dump the service to a file + dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump"); + dumpStream = new FileOutputStream(dumpFile); + batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS); + dumpStream.getFD().sync(); + + // read dumped file above into buffer truncated to DUMP_MAX_LENGTH + // and insert into events table. + int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH); + FileInputStream fileInputStream = new FileInputStream(dumpFile); + int nread = fileInputStream.read(buffer, 0, length); + if (nread > 0) { + Checkin.logEvent(mContext.getContentResolver(), + Checkin.Events.Tag.BATTERY_DISCHARGE_INFO, + new String(buffer, 0, nread)); + if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " + + batteryInfoService + "to log"); + if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread)); + } + } catch (RemoteException e) { + Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME + + "':" + e); + } catch (IOException e) { + Log.e(TAG, "failed to write dumpsys file: " + e); + } finally { + // make sure we clean up + if (dumpStream != null) { + try { + dumpStream.close(); + } catch (IOException e) { + Log.e(TAG, "failed to close dumpsys output stream"); + } + } + if (dumpFile != null && !dumpFile.delete()) { + Log.e(TAG, "failed to delete temporary dumpsys file: " + + dumpFile.getAbsolutePath()); + } + } + } + } + + private final void logOutlier(long duration) { + ContentResolver cr = mContext.getContentResolver(); + String dischargeThresholdString = Settings.Gservices.getString(cr, + Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD); + String durationThresholdString = Settings.Gservices.getString(cr, + Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD); + + if (dischargeThresholdString != null && durationThresholdString != null) { + try { + long durationThreshold = Long.parseLong(durationThresholdString); + int dischargeThreshold = Integer.parseInt(dischargeThresholdString); + if (duration <= durationThreshold && + mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) { + // If the discharge cycle is bad enough we want to know about it. + logBatteryStats(); + } + if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold + + " discharge threshold: " + dischargeThreshold); + if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " + + (mDischargeStartLevel - mBatteryLevel)); + } catch (NumberFormatException e) { + Log.e(TAG, "Invalid DischargeThresholds GService string: " + + durationThresholdString + " or " + dischargeThresholdString); + return; + } + } + } + private final int getIcon(int level) { if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) { return com.android.internal.R.drawable.stat_sys_battery_charge; @@ -243,7 +385,7 @@ class BatteryService extends Binder { @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission("android.permission.DUMP") + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump Battery service from from pid=" diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java index 65e36509a9c51759982dabb70df29e4588ae8d18..760988d9f382faca2f28e65f37ef3c6090ce3b28 100644 --- a/services/java/com/android/server/ConnectivityService.java +++ b/services/java/com/android/server/ConnectivityService.java @@ -35,6 +35,7 @@ import android.os.Message; import android.os.ServiceManager; import android.os.SystemProperties; import android.provider.Settings; +import android.provider.Sync; import android.util.EventLog; import android.util.Log; @@ -333,6 +334,32 @@ public class ConnectivityService extends IConnectivityManager.Stub { } } + /** + * @see ConnectivityManager#getBackgroundDataSetting() + */ + public boolean getBackgroundDataSetting() { + return Settings.Secure.getInt(mContext.getContentResolver(), + Settings.Secure.BACKGROUND_DATA, 1) == 1; + } + + /** + * @see ConnectivityManager#setBackgroundDataSetting(boolean) + */ + public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) { + mContext.enforceCallingOrSelfPermission( + android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING, + "ConnectivityService"); + + if (getBackgroundDataSetting() == allowBackgroundDataUsage) return; + + Settings.Secure.putInt(mContext.getContentResolver(), + Settings.Secure.BACKGROUND_DATA, allowBackgroundDataUsage ? 1 : 0); + + Intent broadcast = new Intent( + ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED); + mContext.sendBroadcast(broadcast); + } + private int getNumConnectedNetworks() { int numConnectedNets = 0; @@ -632,7 +659,7 @@ public class ConnectivityService extends IConnectivityManager.Stub { @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission(android.Manifest.permission.DUMP) + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump ConnectivityService from from pid=" + Binder.getCallingPid() diff --git a/services/java/com/android/server/DeviceStorageMonitorService.java b/services/java/com/android/server/DeviceStorageMonitorService.java index 44f70f0d801741e095a70dae7ecbd59289c43bd5..85861bbfe81a70d2e3efbcf3863a65e0549d78da 100644 --- a/services/java/com/android/server/DeviceStorageMonitorService.java +++ b/services/java/com/android/server/DeviceStorageMonitorService.java @@ -67,6 +67,7 @@ class DeviceStorageMonitorService extends Binder { private static final int EVENT_LOG_LOW_STORAGE_NOTIFICATION = 2745; private static final int EVENT_LOG_FREE_STORAGE_LEFT = 2746; private static final long DEFAULT_DISK_FREE_CHANGE_REPORTING_THRESHOLD = 2 * 1024 * 1024; // 2MB + private static final long DEFAULT_CHECK_INTERVAL = MONITOR_INTERVAL*60*1000; private long mFreeMem; private long mLastReportedFreeMem; private long mLastReportedFreeMemTime; @@ -82,6 +83,9 @@ class DeviceStorageMonitorService extends Binder { boolean mClearingCache; private Intent mStorageLowIntent; private Intent mStorageOkIntent; + private CachePackageDataObserver mClearCacheObserver; + private static final int _TRUE = 1; + private static final int _FALSE = 0; /** * This string is used for ServiceManager access to this class. @@ -100,7 +104,7 @@ class DeviceStorageMonitorService extends Binder { Log.e(TAG, "Will not process invalid message"); return; } - checkMemory(); + checkMemory(msg.arg1 == _TRUE); } }; @@ -109,7 +113,8 @@ class DeviceStorageMonitorService extends Binder { mClearSucceeded = succeeded; mClearingCache = false; if(localLOGV) Log.i(TAG, " Clear succeeded:"+mClearSucceeded - +", mClearingCache:"+mClearingCache); + +", mClearingCache:"+mClearingCache+" Forcing memory check"); + postCheckMemoryMsg(false, 0); } } @@ -145,11 +150,15 @@ class DeviceStorageMonitorService extends Binder { } private final void clearCache() { - CachePackageDataObserver observer = new CachePackageDataObserver(); + if (mClearCacheObserver == null) { + // Lazy instantiation + mClearCacheObserver = new CachePackageDataObserver(); + } mClearingCache = true; try { + if (localLOGV) Log.i(TAG, "Clearing cache"); IPackageManager.Stub.asInterface(ServiceManager.getService("package")). - freeStorageAndNotify(getMemThreshold(), observer); + freeStorageAndNotify(getMemThreshold(), mClearCacheObserver); } catch (RemoteException e) { Log.w(TAG, "Failed to get handle for PackageManger Exception: "+e); mClearingCache = false; @@ -157,7 +166,7 @@ class DeviceStorageMonitorService extends Binder { } } - private final void checkMemory() { + private final void checkMemory(boolean checkCache) { //if the thread that was started to clear cache is still running do nothing till its //finished clearing cache. Ideally this flag could be modified by clearCache // and should be accessed via a lock but even if it does this test will fail now and @@ -172,16 +181,23 @@ class DeviceStorageMonitorService extends Binder { } else { restatDataDir(); if (localLOGV) Log.v(TAG, "freeMemory="+mFreeMem); + //post intent to NotificationManager to display icon if necessary long memThreshold = getMemThreshold(); if (mFreeMem < memThreshold) { if (!mLowMemFlag) { - //see if clearing cache helps - mThreadStartTime = System.currentTimeMillis(); - clearCache(); - Log.i(TAG, "Running low on memory. Sending notification"); - sendNotification(); - mLowMemFlag = true; + if (checkCache) { + // See if clearing cache helps + // Note that clearing cache is asynchronous and so we do a + // memory check again once the cache has been cleared. + mThreadStartTime = System.currentTimeMillis(); + mClearSucceeded = false; + clearCache(); + } else { + Log.i(TAG, "Running low on memory. Sending notification"); + sendNotification(); + mLowMemFlag = true; + } } else { if (localLOGV) Log.v(TAG, "Running low on memory " + "notification already sent. do nothing"); @@ -196,8 +212,15 @@ class DeviceStorageMonitorService extends Binder { } if(localLOGV) Log.i(TAG, "Posting Message again"); //keep posting messages to itself periodically - mHandler.sendMessageDelayed(mHandler.obtainMessage(DEVICE_MEMORY_WHAT), - MONITOR_INTERVAL*60*1000); + postCheckMemoryMsg(true, DEFAULT_CHECK_INTERVAL); + } + + private void postCheckMemoryMsg(boolean clearCache, long delay) { + // Remove queued messages + mHandler.removeMessages(DEVICE_MEMORY_WHAT); + mHandler.sendMessageDelayed(mHandler.obtainMessage(DEVICE_MEMORY_WHAT, + clearCache ?_TRUE : _FALSE, 0), + delay); } /* @@ -231,7 +254,7 @@ class DeviceStorageMonitorService extends Binder { mTotalMemory = (mFileStats.getBlockCount()*mBlkSize)/100; mStorageLowIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_LOW); mStorageOkIntent = new Intent(Intent.ACTION_DEVICE_STORAGE_OK); - checkMemory(); + checkMemory(true); } @@ -281,14 +304,11 @@ class DeviceStorageMonitorService extends Binder { } public void updateMemory() { - ActivityManagerService ams = (ActivityManagerService)ServiceManager.getService("activity"); int callingUid = getCallingUid(); if(callingUid != Process.SYSTEM_UID) { return; } - //remove queued messages - mHandler.removeMessages(DEVICE_MEMORY_WHAT); - //force an early check - checkMemory(); + // force an early check + postCheckMemoryMsg(true, 0); } } diff --git a/services/java/com/android/server/FallbackCheckinService.java b/services/java/com/android/server/FallbackCheckinService.java new file mode 100644 index 0000000000000000000000000000000000000000..cf224466e7650e34bb78235fe431b699c61874ff --- /dev/null +++ b/services/java/com/android/server/FallbackCheckinService.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package com.android.server; + +import android.content.Context; +import android.content.pm.PackageManager; +import android.os.Binder; +import android.os.ICheckinService; +import android.os.IParentalControlCallback; +import android.util.Log; + +import java.io.IOException; + +import com.android.internal.os.RecoverySystem; +import com.google.android.net.ParentalControlState; + +/** + * @hide + */ +public final class FallbackCheckinService extends ICheckinService.Stub { + static final String TAG = "FallbackCheckinService"; + final Context mContext; + + public FallbackCheckinService(Context context) { + mContext = context; + } + + public boolean checkin() { + return false; // failure, because not implemented + } + + public void reportCrashSync(byte[] crashData) { + } + + public void reportCrashAsync(byte[] crashData) { + } + + public void masterClear() { + if (mContext.checkCallingOrSelfPermission("android.permission.MASTER_CLEAR") != + PackageManager.PERMISSION_GRANTED) { + Log.e(TAG, "Permission Denial: can't invoke masterClear from " + + "pid=" + Binder.getCallingPid() + ", " + + "uid=" + Binder.getCallingUid()); + return; + } + + // Save the android ID so the new system can get it erased. + try { + RecoverySystem.rebootAndWipe(); + } catch (IOException e) { + Log.e(TAG, "Reboot for masterClear() failed", e); + } + } + + public void getParentalControlState(IParentalControlCallback p, String requestingApp) + throws android.os.RemoteException { + ParentalControlState state = new ParentalControlState(); + state.isEnabled = false; + p.onResult(state); + } +} diff --git a/services/java/com/android/server/GadgetService.java b/services/java/com/android/server/GadgetService.java deleted file mode 100644 index 4be9ed557e6e34ff0b6e3ac0ba44e925885cd416..0000000000000000000000000000000000000000 --- a/services/java/com/android/server/GadgetService.java +++ /dev/null @@ -1,292 +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. - */ - -package com.android.server; - -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.pm.ActivityInfo; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.content.pm.PackageItemInfo; -import android.content.res.TypedArray; -import android.content.res.XmlResourceParser; -import android.gadget.GadgetManager; -import android.gadget.GadgetInfo; -import android.os.Binder; -import android.util.AttributeSet; -import android.util.Log; -import android.util.Xml; - -import java.io.FileDescriptor; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; - -import com.android.internal.gadget.IGadgetService; - -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; - -class GadgetService extends IGadgetService.Stub -{ - private static final String TAG = "GadgetService"; - - static class GadgetId { - int gadgetId; - String hostPackage; - GadgetInfo info; - } - - Context mContext; - PackageManager mPackageManager; - ArrayList mInstalledProviders; - int mNextGadgetId = 1; - ArrayList mGadgetIds = new ArrayList(); - - GadgetService(Context context) { - mContext = context; - mPackageManager = context.getPackageManager(); - mInstalledProviders = getGadgetList(); - } - - @Override - public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission(android.Manifest.permission.DUMP) - != PackageManager.PERMISSION_GRANTED) { - pw.println("Permission Denial: can't dump from from pid=" - + Binder.getCallingPid() - + ", uid=" + Binder.getCallingUid()); - return; - } - - synchronized (mGadgetIds) { - int N = mInstalledProviders.size(); - pw.println("Providers: (size=" + N + ")"); - for (int i=0; i getInstalledProviders() { - synchronized (mGadgetIds) { - return new ArrayList(mInstalledProviders); - } - } - - boolean canAccessGadgetId(GadgetId id, String callingPackage) { - if (id.hostPackage.equals(callingPackage)) { - return true; - } - if (id.info != null && id.info.provider.getPackageName().equals(callingPackage)) { - return true; - } - // TODO: Check for the pick permission - //if (has permission) { - // return true; - //} - //return false; - return true; - } - - private GadgetId lookupGadgetIdLocked(int gadgetId) { - String callingPackage = getCallingPackage(); - final int N = mGadgetIds.size(); - for (int i=0; i getGadgetList() { - PackageManager pm = mPackageManager; - - // TODO: We have these as different actions. I wonder if it makes more sense to - // have like a GADGET_ACTION, and then subcommands. It's kind of arbitrary that - // we look for GADGET_UPDATE_ACTION and not any of the other gadget actions. - Intent intent = new Intent(GadgetManager.GADGET_UPDATE_ACTION); - List broadcastReceivers = pm.queryBroadcastReceivers(intent, - PackageManager.GET_META_DATA); - - ArrayList result = new ArrayList(); - - final int N = broadcastReceivers.size(); - for (int i=0; i 0) { + long bedtime = SystemClock.uptimeMillis(); + do { + try { + this.wait(duration); + } + catch (InterruptedException e) { + } + if (mDone) { + break; + } + duration = duration + - SystemClock.uptimeMillis() - bedtime; + } while (duration > 0); + } + } + public void run() { + Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_DISPLAY); synchronized (this) { int index = 0; - boolean nextState = false; long[] pattern = mPattern; - if (pattern[0] == 0) { - index++; - nextState = true; - } int len = pattern.length; - long start = SystemClock.uptimeMillis(); + long duration = 0; while (!mDone) { - if (nextState) { - HardwareService.this.on(); - } else { - HardwareService.this.off(); + // add off-time duration to any accumulated on-time duration + if (index < len) { + duration += pattern[index++]; } - nextState = !nextState; - long bedtime = SystemClock.uptimeMillis(); - long duration = pattern[index]; - do { - try { - this.wait(duration); - } - catch (InterruptedException e) { - } - if (mDone) { - break; + + // sleep until it is time to start the vibrator + delay(duration); + if (mDone) { + break; + } + + if (index < len) { + // read on-time duration and start the vibrator + // duration is saved for delay() at top of loop + duration = pattern[index++]; + if (duration > 0) { + HardwareService.this.vibratorOn(duration); } - duration = duration - - SystemClock.uptimeMillis() - bedtime; - } while (duration > 0); - index++; - if (index >= len) { + } else { if (mRepeat < 0) { - HardwareService.this.off(); break; } else { index = mRepeat; + duration = 0; } } } + if (mDone) { + // make sure vibrator is off if we were cancelled. + // otherwise, it will turn off automatically + // when the last timeout expires. + HardwareService.this.vibratorOff(); + } mWakeLock.release(); } synchronized (HardwareService.this) { @@ -301,6 +323,6 @@ public class HardwareService extends IHardwareService.Stub { volatile Death mDeath; volatile IBinder mToken; - native static void on(); - native static void off(); + native static void vibratorOn(long milliseconds); + native static void vibratorOff(); } diff --git a/services/java/com/android/server/HeadsetObserver.java b/services/java/com/android/server/HeadsetObserver.java index 2bea7312fc53624f6d0f4f818bc94bc531d999fa..855734dcb80e571a52a4cd7eb01232092773f27e 100644 --- a/services/java/com/android/server/HeadsetObserver.java +++ b/services/java/com/android/server/HeadsetObserver.java @@ -19,6 +19,8 @@ package com.android.server; import android.app.ActivityManagerNative; import android.content.Context; import android.content.Intent; +import android.os.Handler; +import android.os.Message; import android.os.UEventObserver; import android.util.Log; import android.media.AudioManager; @@ -40,6 +42,8 @@ class HeadsetObserver extends UEventObserver { private int mHeadsetState; private String mHeadsetName; + private boolean mAudioRouteNeedsUpdate; + private AudioManager mAudioManager; public HeadsetObserver(Context context) { mContext = context; @@ -60,7 +64,7 @@ class HeadsetObserver extends UEventObserver { } } - private final void init() { + private synchronized final void init() { char[] buffer = new char[1024]; String newName = mHeadsetName; @@ -80,21 +84,33 @@ class HeadsetObserver extends UEventObserver { Log.e(TAG, "" , e); } + mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); update(newName, newState); } private synchronized final void update(String newName, int newState) { if (newName != mHeadsetName || newState != mHeadsetState) { + boolean isUnplug = (newState == 0 && mHeadsetState == 1); mHeadsetName = newName; mHeadsetState = newState; - AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); - - audioManager.setWiredHeadsetOn(mHeadsetState == 1); - sendIntent(); + mAudioRouteNeedsUpdate = true; + + sendIntent(isUnplug); + + if (isUnplug) { + // It often takes >200ms to flush the audio pipeline after apps + // pause audio playback, but audio route changes are immediate, + // so delay the route change by 400ms. + // This could be improved once the audio sub-system provides an + // interface to clear the audio pipeline. + mHandler.sendEmptyMessageDelayed(0, 400); + } else { + updateAudioRoute(); + } } } - private synchronized final void sendIntent() { + private synchronized final void sendIntent(boolean isUnplug) { // Pack up the values and broadcast them to everyone Intent intent = new Intent(Intent.ACTION_HEADSET_PLUG); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); @@ -104,5 +120,25 @@ class HeadsetObserver extends UEventObserver { // TODO: Should we require a permission? ActivityManagerNative.broadcastStickyIntent(intent, null); + + if (isUnplug) { + intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY); + mContext.sendBroadcast(intent); + } } + + private synchronized final void updateAudioRoute() { + if (mAudioRouteNeedsUpdate) { + mAudioManager.setWiredHeadsetOn(mHeadsetState == 1); + mAudioRouteNeedsUpdate = false; + } + } + + private final Handler mHandler = new Handler() { + @Override + public void handleMessage(Message msg) { + updateAudioRoute(); + } + }; + } diff --git a/services/java/com/android/server/InputMethodManagerService.java b/services/java/com/android/server/InputMethodManagerService.java index 139aaa3aaa3f0dba23c5d01715fdcec3edd70ed1..994832244f19571990a1781572df978395eb32cb 100644 --- a/services/java/com/android/server/InputMethodManagerService.java +++ b/services/java/com/android/server/InputMethodManagerService.java @@ -30,6 +30,7 @@ import com.android.server.status.StatusBarService; import org.xmlpull.v1.XmlPullParserException; +import android.app.ActivityManagerNative; import android.app.AlertDialog; import android.content.ComponentName; import android.content.ContentResolver; @@ -53,15 +54,17 @@ import android.os.IInterface; import android.os.Message; import android.os.Parcel; import android.os.RemoteException; +import android.os.ResultReceiver; import android.os.ServiceManager; +import android.os.SystemClock; import android.provider.Settings; import android.text.TextUtils; +import android.util.EventLog; import android.util.Log; import android.util.PrintWriterPrinter; import android.util.Printer; import android.view.IWindowManager; import android.view.WindowManager; -import android.view.inputmethod.DefaultInputMethod; import android.view.inputmethod.InputBinding; import android.view.inputmethod.InputMethod; import android.view.inputmethod.InputMethodInfo; @@ -98,6 +101,10 @@ public class InputMethodManagerService extends IInputMethodManager.Stub static final int MSG_UNBIND_METHOD = 3000; static final int MSG_BIND_METHOD = 3010; + static final long TIME_TO_RECONNECT = 10*1000; + + static final int LOG_IMF_FORCE_RECONNECT_IME = 32000; + final Context mContext; final Handler mHandler; final SettingsObserver mSettingsObserver; @@ -188,6 +195,16 @@ public class InputMethodManagerService extends IInputMethodManager.Stub */ ClientState mCurClient; + /** + * The last window token that gained focus. + */ + IBinder mCurFocusedWindow; + + /** + * The input context last provided by the current client. + */ + IInputContext mCurInputContext; + /** * The attributes last provided by the current client. */ @@ -215,6 +232,11 @@ public class InputMethodManagerService extends IInputMethodManager.Stub */ boolean mShowExplicitlyRequested; + /** + * Set if we were forced to be shown. + */ + boolean mShowForced; + /** * Set if we last told the input method to show itself. */ @@ -237,6 +259,12 @@ public class InputMethodManagerService extends IInputMethodManager.Stub */ IInputMethod mCurMethod; + /** + * Time that we last initiated a bind to the input method, to determine + * if we should try to disconnect and reconnect to it. + */ + long mLastBindTime; + /** * Have we called mCurMethod.bindInput()? */ @@ -281,7 +309,7 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { mScreenOn = false; } else { - Log.e(TAG, "Unexpected intent " + intent); + Log.w(TAG, "Unexpected intent " + intent); } // Inform the current client of the change in active status @@ -290,7 +318,8 @@ public class InputMethodManagerService extends IInputMethodManager.Stub mCurClient.client.setActive(mScreenOn); } } catch (RemoteException e) { - Log.e(TAG, "Got RemoteException sending 'screen on/off' notification", e); + Log.w(TAG, "Got RemoteException sending 'screen on/off' notification to pid " + + mCurClient.pid + " uid " + mCurClient.uid); } } } @@ -475,7 +504,6 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } public void systemReady() { - } public List getInputMethodList() { @@ -534,7 +562,7 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } } - void unbindCurrentInputLocked() { + void unbindCurrentClientLocked() { if (mCurClient != null) { if (DEBUG) Log.v(TAG, "unbindCurrentInputLocked: client = " + mCurClient.client.asBinder()); @@ -553,12 +581,34 @@ public class InputMethodManagerService extends IInputMethodManager.Stub try { mCurClient.client.setActive(false); } catch (RemoteException e) { - Log.e(TAG, "Got RemoteException sending setActive(false) notification", e); + Log.w(TAG, "Got RemoteException sending setActive(false) notification to pid " + + mCurClient.pid + " uid " + mCurClient.uid); } mCurClient = null; } } + private int getImeShowFlags() { + int flags = 0; + if (mShowForced) { + flags |= InputMethod.SHOW_FORCED + | InputMethod.SHOW_EXPLICIT; + } else if (mShowExplicitlyRequested) { + flags |= InputMethod.SHOW_EXPLICIT; + } + return flags; + } + + private int getAppShowFlags() { + int flags = 0; + if (mShowForced) { + flags |= InputMethodManager.SHOW_FORCED; + } else if (!mShowExplicitlyRequested) { + flags |= InputMethodManager.SHOW_IMPLICIT; + } + return flags; + } + InputBindResult attachNewInputLocked(boolean initial, boolean needResult) { if (!mBoundToMethod) { executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO( @@ -567,16 +617,15 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } final SessionState session = mCurClient.curSession; if (initial) { - executeOrSendMessage(session.method, mCaller.obtainMessageOO( - MSG_START_INPUT, session, mCurAttribute)); + executeOrSendMessage(session.method, mCaller.obtainMessageOOO( + MSG_START_INPUT, session, mCurInputContext, mCurAttribute)); } else { - executeOrSendMessage(session.method, mCaller.obtainMessageOO( - MSG_RESTART_INPUT, session, mCurAttribute)); + executeOrSendMessage(session.method, mCaller.obtainMessageOOO( + MSG_RESTART_INPUT, session, mCurInputContext, mCurAttribute)); } if (mShowRequested) { if (DEBUG) Log.v(TAG, "Attach new input asks to show input"); - showCurrentInputLocked(mShowExplicitlyRequested - ? 0 : InputMethodManager.SHOW_IMPLICIT); + showCurrentInputLocked(getAppShowFlags(), null); } return needResult ? new InputBindResult(session.session, mCurId, mCurSeq) @@ -584,7 +633,8 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } InputBindResult startInputLocked(IInputMethodClient client, - EditorInfo attribute, boolean initial, boolean needResult) { + IInputContext inputContext, EditorInfo attribute, + boolean initial, boolean needResult) { // If no method is currently selected, do nothing. if (mCurMethodId == null) { return mNoBinding; @@ -613,7 +663,7 @@ public class InputMethodManagerService extends IInputMethodManager.Stub if (mCurClient != cs) { // If the client is changing, we need to switch over to the new // one. - unbindCurrentInputLocked(); + unbindCurrentClientLocked(); if (DEBUG) Log.v(TAG, "switching to client: client = " + cs.client.asBinder()); @@ -622,7 +672,8 @@ public class InputMethodManagerService extends IInputMethodManager.Stub try { cs.client.setActive(mScreenOn); } catch (RemoteException e) { - Log.e(TAG, "Got RemoteException sending setActive notification", e); + Log.w(TAG, "Got RemoteException sending setActive notification to pid " + + cs.pid + " uid " + cs.uid); } } } @@ -631,6 +682,7 @@ public class InputMethodManagerService extends IInputMethodManager.Stub mCurSeq++; if (mCurSeq <= 0) mCurSeq = 1; mCurClient = cs; + mCurInputContext = inputContext; mCurAttribute = attribute; // Check if the input method is changing. @@ -641,14 +693,31 @@ public class InputMethodManagerService extends IInputMethodManager.Stub return attachNewInputLocked(initial, needResult); } if (mHaveConnection) { - if (mCurMethod != null && !cs.sessionRequested) { - cs.sessionRequested = true; - if (DEBUG) Log.v(TAG, "Creating new session for client " + cs); - executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO( - MSG_CREATE_SESSION, mCurMethod, - new MethodCallback(mCurMethod))); + if (mCurMethod != null) { + if (!cs.sessionRequested) { + cs.sessionRequested = true; + if (DEBUG) Log.v(TAG, "Creating new session for client " + cs); + executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO( + MSG_CREATE_SESSION, mCurMethod, + new MethodCallback(mCurMethod))); + } + // Return to client, and we will get back with it when + // we have had a session made for it. + return new InputBindResult(null, mCurId, mCurSeq); + } else if (SystemClock.uptimeMillis() + < (mLastBindTime+TIME_TO_RECONNECT)) { + // In this case we have connected to the service, but + // don't yet have its interface. If it hasn't been too + // long since we did the connection, we'll return to + // the client and wait to get the service interface so + // we can report back. If it has been too long, we want + // to fall through so we can try a disconnect/reconnect + // to see if we can get back in touch with the service. + return new InputBindResult(null, mCurId, mCurSeq); + } else { + EventLog.writeEvent(LOG_IMF_FORCE_RECONNECT_IME, mCurMethodId, + SystemClock.uptimeMillis()-mLastBindTime, 0); } - return new InputBindResult(null, mCurId, mCurSeq); } } @@ -657,28 +726,17 @@ public class InputMethodManagerService extends IInputMethodManager.Stub throw new IllegalArgumentException("Unknown id: " + mCurMethodId); } - if (mCurToken != null) { - try { - mIWindowManager.removeWindowToken(mCurToken); - } catch (RemoteException e) { - } - mCurToken = null; - } - - if (mHaveConnection) { - mContext.unbindService(this); - mHaveConnection = false; - } - - clearCurMethod(); + unbindCurrentMethodLocked(false); mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE); mCurIntent.setComponent(info.getComponent()); if (mContext.bindService(mCurIntent, this, Context.BIND_AUTO_CREATE)) { + mLastBindTime = SystemClock.uptimeMillis(); mHaveConnection = true; mCurId = info.getId(); mCurToken = new Binder(); try { + if (DEBUG) Log.v(TAG, "Adding window token: " + mCurToken); mIWindowManager.addWindowToken(mCurToken, WindowManager.LayoutParams.TYPE_INPUT_METHOD); } catch (RemoteException e) { @@ -686,18 +744,20 @@ public class InputMethodManagerService extends IInputMethodManager.Stub return new InputBindResult(null, mCurId, mCurSeq); } else { mCurIntent = null; - Log.e(TAG, "Failure connecting to input method service: " + Log.w(TAG, "Failure connecting to input method service: " + mCurIntent); } return null; } public InputBindResult startInput(IInputMethodClient client, - EditorInfo attribute, boolean initial, boolean needResult) { + IInputContext inputContext, EditorInfo attribute, + boolean initial, boolean needResult) { synchronized (mMethodMap) { final long ident = Binder.clearCallingIdentity(); try { - return startInputLocked(client, attribute, initial, needResult); + return startInputLocked(client, inputContext, attribute, + initial, needResult); } finally { Binder.restoreCallingIdentity(ident); } @@ -712,6 +772,7 @@ public class InputMethodManagerService extends IInputMethodManager.Stub if (mCurIntent != null && name.equals(mCurIntent.getComponent())) { mCurMethod = IInputMethod.Stub.asInterface(service); if (mCurClient != null) { + if (DEBUG) Log.v(TAG, "Initiating attach with token: " + mCurToken); executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO( MSG_ATTACH_TOKEN, mCurMethod, mCurToken)); if (mCurClient != null) { @@ -728,7 +789,8 @@ public class InputMethodManagerService extends IInputMethodManager.Stub void onSessionCreated(IInputMethod method, IInputMethodSession session) { synchronized (mMethodMap) { - if (mCurMethod == method) { + if (mCurMethod != null && method != null + && mCurMethod.asBinder() == method.asBinder()) { if (mCurClient != null) { mCurClient.curSession = new SessionState(mCurClient, method, session); @@ -743,7 +805,30 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } } - void clearCurMethod() { + void unbindCurrentMethodLocked(boolean reportToClient) { + if (mHaveConnection) { + mContext.unbindService(this); + mHaveConnection = false; + } + + if (mCurToken != null) { + try { + if (DEBUG) Log.v(TAG, "Removing window token: " + mCurToken); + mIWindowManager.removeWindowToken(mCurToken); + } catch (RemoteException e) { + } + mCurToken = null; + } + + clearCurMethodLocked(); + + if (reportToClient && mCurClient != null) { + executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO( + MSG_UNBIND_METHOD, mCurSeq, mCurClient.client)); + } + } + + void clearCurMethodLocked() { if (mCurMethod != null) { for (ClientState cs : mClients.values()) { cs.sessionRequested = false; @@ -751,6 +836,7 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } mCurMethod = null; } + mStatusBar.setIconVisibility(mInputMethodIcon, false); } public void onServiceDisconnected(ComponentName name) { @@ -759,7 +845,10 @@ public class InputMethodManagerService extends IInputMethodManager.Stub + " mCurIntent=" + mCurIntent); if (mCurMethod != null && mCurIntent != null && name.equals(mCurIntent.getComponent())) { - clearCurMethod(); + clearCurMethodLocked(); + // We consider this to be a new bind attempt, since the system + // should now try to restart the service for us. + mLastBindTime = SystemClock.uptimeMillis(); mShowRequested = mInputShown; mInputShown = false; if (mCurClient != null) { @@ -770,35 +859,48 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } } - public void updateStatusIcon(int iconId, String iconPackage) { - if (iconId == 0) { - Log.d(TAG, "hide the small icon for the input method"); - mStatusBar.setIconVisibility(mInputMethodIcon, false); - } else { - Log.d(TAG, "show a small icon for the input method"); - - if (iconPackage != null - && iconPackage - .equals(InputMethodManager.BUILDIN_INPUTMETHOD_PACKAGE)) { - iconPackage = null; + public void updateStatusIcon(IBinder token, String packageName, int iconId) { + long ident = Binder.clearCallingIdentity(); + try { + if (token == null || mCurToken != token) { + Log.w(TAG, "Ignoring setInputMethod of token: " + token); + return; } - - mInputMethodData.iconId = iconId; - mInputMethodData.iconPackage = iconPackage; - mStatusBar.updateIcon(mInputMethodIcon, mInputMethodData, null); - mStatusBar.setIconVisibility(mInputMethodIcon, true); + + synchronized (mMethodMap) { + if (iconId == 0) { + if (DEBUG) Log.d(TAG, "hide the small icon for the input method"); + mStatusBar.setIconVisibility(mInputMethodIcon, false); + } else if (packageName != null) { + if (DEBUG) Log.d(TAG, "show a small icon for the input method"); + mInputMethodData.iconId = iconId; + mInputMethodData.iconPackage = packageName; + mStatusBar.updateIcon(mInputMethodIcon, mInputMethodData, null); + mStatusBar.setIconVisibility(mInputMethodIcon, true); + } + } + } finally { + Binder.restoreCallingIdentity(ident); } } void updateFromSettingsLocked() { + // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and + // ENABLED_INPUT_METHODS is taking care of keeping them correctly in + // sync, so we will never have a DEFAULT_INPUT_METHOD that is not + // enabled. String id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD); - if (id != null) { + if (id != null && id.length() > 0) { try { setInputMethodLocked(id); } catch (IllegalArgumentException e) { Log.w(TAG, "Unknown input method from prefs: " + id, e); + unbindCurrentMethodLocked(true); } + } else { + // There is no longer an input method set, so stop any current one. + unbindCurrentMethodLocked(true); } } @@ -817,154 +919,217 @@ public class InputMethodManagerService extends IInputMethodManager.Stub mCurMethodId = id; Settings.Secure.putString(mContext.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD, id); - - Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED); - intent.putExtra("input_method_id", id); - mContext.sendBroadcast(intent); - unbindCurrentInputLocked(); + + if (ActivityManagerNative.isSystemReady()) { + Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED); + intent.putExtra("input_method_id", id); + mContext.sendBroadcast(intent); + } + unbindCurrentClientLocked(); } finally { Binder.restoreCallingIdentity(ident); } } - public void showSoftInput(IInputMethodClient client, int flags) { - synchronized (mMethodMap) { - if (mCurClient == null || client == null - || mCurClient.client.asBinder() != client.asBinder()) { - try { - // We need to check if this is the current client with - // focus in the window manager, to allow this call to - // be made before input is started in it. - if (!mIWindowManager.inputMethodClientHasFocus(client)) { - Log.w(TAG, "Ignoring showSoftInput of: " + client); - return; + public boolean showSoftInput(IInputMethodClient client, int flags, + ResultReceiver resultReceiver) { + long ident = Binder.clearCallingIdentity(); + try { + synchronized (mMethodMap) { + if (mCurClient == null || client == null + || mCurClient.client.asBinder() != client.asBinder()) { + try { + // We need to check if this is the current client with + // focus in the window manager, to allow this call to + // be made before input is started in it. + if (!mIWindowManager.inputMethodClientHasFocus(client)) { + Log.w(TAG, "Ignoring showSoftInput of: " + client); + return false; + } + } catch (RemoteException e) { + return false; } - } catch (RemoteException e) { } + + if (DEBUG) Log.v(TAG, "Client requesting input be shown"); + return showCurrentInputLocked(flags, resultReceiver); } - - if (DEBUG) Log.v(TAG, "Client requesting input be shown"); - showCurrentInputLocked(flags); + } finally { + Binder.restoreCallingIdentity(ident); } } - void showCurrentInputLocked(int flags) { + boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) { mShowRequested = true; if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) { mShowExplicitlyRequested = true; } + if ((flags&InputMethodManager.SHOW_FORCED) != 0) { + mShowExplicitlyRequested = true; + mShowForced = true; + } + boolean res = false; if (mCurMethod != null) { - executeOrSendMessage(mCurMethod, mCaller.obtainMessageIO( - MSG_SHOW_SOFT_INPUT, mShowExplicitlyRequested ? 1 : 0, - mCurMethod)); + executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO( + MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod, + resultReceiver)); mInputShown = true; + res = true; + } else if (mHaveConnection && SystemClock.uptimeMillis() + < (mLastBindTime+TIME_TO_RECONNECT)) { + // The client has asked to have the input method shown, but + // we have been sitting here too long with a connection to the + // service and no interface received, so let's disconnect/connect + // to try to prod things along. + EventLog.writeEvent(LOG_IMF_FORCE_RECONNECT_IME, mCurMethodId, + SystemClock.uptimeMillis()-mLastBindTime,1); + mContext.unbindService(this); + mContext.bindService(mCurIntent, this, Context.BIND_AUTO_CREATE); } + + return res; } - public void hideSoftInput(IInputMethodClient client, int flags) { - synchronized (mMethodMap) { - if (mCurClient == null || client == null - || mCurClient.client.asBinder() != client.asBinder()) { - try { - // We need to check if this is the current client with - // focus in the window manager, to allow this call to - // be made before input is started in it. - if (!mIWindowManager.inputMethodClientHasFocus(client)) { - Log.w(TAG, "Ignoring hideSoftInput of: " + client); - return; + public boolean hideSoftInput(IInputMethodClient client, int flags, + ResultReceiver resultReceiver) { + long ident = Binder.clearCallingIdentity(); + try { + synchronized (mMethodMap) { + if (mCurClient == null || client == null + || mCurClient.client.asBinder() != client.asBinder()) { + try { + // We need to check if this is the current client with + // focus in the window manager, to allow this call to + // be made before input is started in it. + if (!mIWindowManager.inputMethodClientHasFocus(client)) { + Log.w(TAG, "Ignoring hideSoftInput of: " + client); + return false; + } + } catch (RemoteException e) { + return false; } - } catch (RemoteException e) { } + + if (DEBUG) Log.v(TAG, "Client requesting input be hidden"); + return hideCurrentInputLocked(flags, resultReceiver); } - - if (DEBUG) Log.v(TAG, "Client requesting input be hidden"); - hideCurrentInputLocked(flags); + } finally { + Binder.restoreCallingIdentity(ident); } } - void hideCurrentInputLocked(int flags) { + boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) { if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0 - && mShowExplicitlyRequested) { + && (mShowExplicitlyRequested || mShowForced)) { if (DEBUG) Log.v(TAG, "Not hiding: explicit show not cancelled by non-explicit hide"); - return; + return false; + } + if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) { + if (DEBUG) Log.v(TAG, + "Not hiding: forced show not cancelled by not-always hide"); + return false; } + boolean res; if (mInputShown && mCurMethod != null) { - executeOrSendMessage(mCurMethod, mCaller.obtainMessageO( - MSG_HIDE_SOFT_INPUT, mCurMethod)); + executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO( + MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver)); + res = true; + } else { + res = false; } mInputShown = false; mShowRequested = false; mShowExplicitlyRequested = false; + mShowForced = false; + return res; } - public void windowGainedFocus(IInputMethodClient client, + public void windowGainedFocus(IInputMethodClient client, IBinder windowToken, boolean viewHasFocus, boolean isTextEditor, int softInputMode, boolean first, int windowFlags) { - synchronized (mMethodMap) { - if (DEBUG) Log.v(TAG, "windowGainedFocus: " + client.asBinder() - + " viewHasFocus=" + viewHasFocus - + " isTextEditor=" + isTextEditor - + " softInputMode=#" + Integer.toHexString(softInputMode) - + " first=" + first + " flags=#" - + Integer.toHexString(windowFlags)); - - if (mCurClient == null || client == null - || mCurClient.client.asBinder() != client.asBinder()) { - try { - // We need to check if this is the current client with - // focus in the window manager, to allow this call to - // be made before input is started in it. - if (!mIWindowManager.inputMethodClientHasFocus(client)) { - Log.w(TAG, "Ignoring focus gain of: " + client); - return; + long ident = Binder.clearCallingIdentity(); + try { + synchronized (mMethodMap) { + if (DEBUG) Log.v(TAG, "windowGainedFocus: " + client.asBinder() + + " viewHasFocus=" + viewHasFocus + + " isTextEditor=" + isTextEditor + + " softInputMode=#" + Integer.toHexString(softInputMode) + + " first=" + first + " flags=#" + + Integer.toHexString(windowFlags)); + + if (mCurClient == null || client == null + || mCurClient.client.asBinder() != client.asBinder()) { + try { + // We need to check if this is the current client with + // focus in the window manager, to allow this call to + // be made before input is started in it. + if (!mIWindowManager.inputMethodClientHasFocus(client)) { + Log.w(TAG, "Client not active, ignoring focus gain of: " + client); + return; + } + } catch (RemoteException e) { } - } catch (RemoteException e) { } - } - - switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) { - case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED: - if (!isTextEditor || (softInputMode & - WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) - != WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) { - if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) { - // There is no focus view, and this window will - // be behind any soft input window, so hide the - // soft input window if it is shown. - if (DEBUG) Log.v(TAG, "Unspecified window will hide input"); - hideCurrentInputLocked(0); + + if (mCurFocusedWindow == windowToken) { + Log.w(TAG, "Window already focused, ignoring focus gain of: " + client); + return; + } + mCurFocusedWindow = windowToken; + + switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) { + case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED: + if (!isTextEditor || (softInputMode & + WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) + != WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) { + if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) { + // There is no focus view, and this window will + // be behind any soft input window, so hide the + // soft input window if it is shown. + if (DEBUG) Log.v(TAG, "Unspecified window will hide input"); + hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null); + } + } else if (isTextEditor && (softInputMode & + WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) + == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + && (softInputMode & + WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) { + // There is a focus view, and we are navigating forward + // into the window, so show the input window for the user. + if (DEBUG) Log.v(TAG, "Unspecified window will show input"); + showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null); } - } else if (isTextEditor && (softInputMode & - WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) - == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE - && (softInputMode & - WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) { - // There is a focus view, and we are navigating forward - // into the window, so show the input window for the user. - if (DEBUG) Log.v(TAG, "Unspecified window will show input"); - showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT); - } - break; - case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED: - // Do nothing. - break; - case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN: - if (DEBUG) Log.v(TAG, "Window asks to hide input"); - hideCurrentInputLocked(0); - break; - case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE: - if ((softInputMode & - WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) { - if (DEBUG) Log.v(TAG, "Window asks to show input going forward"); - showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT); - } - break; - case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE: - if (DEBUG) Log.v(TAG, "Window asks to always show input"); - showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT); - break; + break; + case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED: + // Do nothing. + break; + case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN: + if ((softInputMode & + WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) { + if (DEBUG) Log.v(TAG, "Window asks to hide input going forward"); + hideCurrentInputLocked(0, null); + } + break; + case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN: + if (DEBUG) Log.v(TAG, "Window asks to hide input"); + hideCurrentInputLocked(0, null); + break; + case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE: + if ((softInputMode & + WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) { + if (DEBUG) Log.v(TAG, "Window asks to show input going forward"); + showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null); + } + break; + case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE: + if (DEBUG) Log.v(TAG, "Window asks to always show input"); + showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null); + break; + } } + } finally { + Binder.restoreCallingIdentity(ident); } } @@ -981,7 +1146,7 @@ public class InputMethodManagerService extends IInputMethodManager.Stub public void setInputMethod(IBinder token, String id) { synchronized (mMethodMap) { - if (mCurToken == null) { + if (token == null) { if (mContext.checkCallingOrSelfPermission( android.Manifest.permission.WRITE_SECURE_SETTINGS) != PackageManager.PERMISSION_GRANTED) { @@ -991,19 +1156,45 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } } else if (mCurToken != token) { Log.w(TAG, "Ignoring setInputMethod of token: " + token); + return; } - setInputMethodLocked(id); + long ident = Binder.clearCallingIdentity(); + try { + setInputMethodLocked(id); + } finally { + Binder.restoreCallingIdentity(ident); + } } } public void hideMySoftInput(IBinder token, int flags) { synchronized (mMethodMap) { - if (mCurToken == null || mCurToken != token) { + if (token == null || mCurToken != token) { Log.w(TAG, "Ignoring hideInputMethod of token: " + token); + return; + } + long ident = Binder.clearCallingIdentity(); + try { + hideCurrentInputLocked(flags, null); + } finally { + Binder.restoreCallingIdentity(ident); + } + } + } + + public void showMySoftInput(IBinder token, int flags) { + synchronized (mMethodMap) { + if (token == null || mCurToken != token) { + Log.w(TAG, "Ignoring hideInputMethod of token: " + token); + return; + } + long ident = Binder.clearCallingIdentity(); + try { + showCurrentInputLocked(flags, null); + } finally { + Binder.restoreCallingIdentity(ident); } - - hideCurrentInputLocked(flags); } } @@ -1051,20 +1242,25 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } return true; case MSG_SHOW_SOFT_INPUT: + args = (HandlerCaller.SomeArgs)msg.obj; try { - ((IInputMethod)msg.obj).showSoftInput(msg.arg1 != 0); + ((IInputMethod)args.arg1).showSoftInput(msg.arg1, + (ResultReceiver)args.arg2); } catch (RemoteException e) { } return true; case MSG_HIDE_SOFT_INPUT: + args = (HandlerCaller.SomeArgs)msg.obj; try { - ((IInputMethod)msg.obj).hideSoftInput(); + ((IInputMethod)args.arg1).hideSoftInput(0, + (ResultReceiver)args.arg2); } catch (RemoteException e) { } return true; case MSG_ATTACH_TOKEN: args = (HandlerCaller.SomeArgs)msg.obj; try { + if (DEBUG) Log.v(TAG, "Sending attach of token: " + args.arg2); ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2); } catch (RemoteException e) { } @@ -1077,7 +1273,6 @@ public class InputMethodManagerService extends IInputMethodManager.Stub } catch (RemoteException e) { } return true; - // --------------------------------------------------------- case MSG_START_INPUT: @@ -1085,7 +1280,8 @@ public class InputMethodManagerService extends IInputMethodManager.Stub try { SessionState session = (SessionState)args.arg1; setEnabledSessionInMainThread(session); - session.method.startInput((EditorInfo)args.arg2); + session.method.startInput((IInputContext)args.arg2, + (EditorInfo)args.arg3); } catch (RemoteException e) { } return true; @@ -1094,7 +1290,8 @@ public class InputMethodManagerService extends IInputMethodManager.Stub try { SessionState session = (SessionState)args.arg1; setEnabledSessionInMainThread(session); - session.method.restartInput((EditorInfo)args.arg2); + session.method.restartInput((IInputContext)args.arg2, + (EditorInfo)args.arg3); } catch (RemoteException e) { } return true; @@ -1128,10 +1325,6 @@ public class InputMethodManagerService extends IInputMethodManager.Stub PackageManager pm = mContext.getPackageManager(); - Object[][] buildin = {{ - DefaultInputMethod.class.getName(), - DefaultInputMethod.getMetaInfo()}}; - List services = pm.queryIntentServices( new Intent(InputMethod.SERVICE_INTERFACE), PackageManager.GET_META_DATA); @@ -1150,39 +1343,6 @@ public class InputMethodManagerService extends IInputMethodManager.Stub if (DEBUG) Log.d(TAG, "Checking " + compName); - /* Built-in input methods are not currently supported... this will - * need to be reworked to bring them back (all input methods must - * now be published in a manifest). - */ - /* - if (compName.getPackageName().equals( - InputMethodManager.BUILDIN_INPUTMETHOD_PACKAGE)) { - // System build-in input methods; - String inputMethodName = null; - int kbType = 0; - String skbName = null; - - for (int j = 0; j < buildin.length; ++j) { - Object[] obj = buildin[j]; - if (compName.getClassName().equals(obj[0])) { - InputMethodMetaInfo imp = (InputMethodMetaInfo) obj[1]; - inputMethodName = imp.inputMethodName; - } - } - - InputMethodMetaInfo p = new InputMethodMetaInfo(compName, - inputMethodName, ""); - - list.add(p); - - if (DEBUG) { - Log.d(TAG, "Found a build-in input method " + p); - } - - continue; - } - */ - try { InputMethodInfo p = new InputMethodInfo(mContext, ri); list.add(p); @@ -1202,7 +1362,7 @@ public class InputMethodManagerService extends IInputMethodManager.Stub // ---------------------------------------------------------------------- - public void showInputMethodMenu() { + void showInputMethodMenu() { if (DEBUG) Log.v(TAG, "Show switching menu"); hideInputMethodMenu(); @@ -1302,91 +1462,96 @@ public class InputMethodManagerService extends IInputMethodManager.Stub + android.Manifest.permission.WRITE_SECURE_SETTINGS); } - // Make sure this is a valid input method. - InputMethodInfo imm = mMethodMap.get(id); - if (imm == null) { + long ident = Binder.clearCallingIdentity(); + try { + // Make sure this is a valid input method. + InputMethodInfo imm = mMethodMap.get(id); if (imm == null) { - throw new IllegalArgumentException("Unknown id: " + mCurMethodId); + if (imm == null) { + throw new IllegalArgumentException("Unknown id: " + mCurMethodId); + } } - } - - StringBuilder builder = new StringBuilder(256); - - boolean removed = false; - String firstId = null; - - // Look through the currently enabled input methods. - String enabledStr = Settings.Secure.getString(mContext.getContentResolver(), - Settings.Secure.ENABLED_INPUT_METHODS); - if (enabledStr != null) { - final TextUtils.SimpleStringSplitter splitter = mStringColonSplitter; - splitter.setString(enabledStr); - while (splitter.hasNext()) { - String curId = splitter.next(); - if (curId.equals(id)) { - if (enabled) { - // We are enabling this input method, but it is - // already enabled. Nothing to do. The previous - // state was enabled. - return true; + + StringBuilder builder = new StringBuilder(256); + + boolean removed = false; + String firstId = null; + + // Look through the currently enabled input methods. + String enabledStr = Settings.Secure.getString(mContext.getContentResolver(), + Settings.Secure.ENABLED_INPUT_METHODS); + if (enabledStr != null) { + final TextUtils.SimpleStringSplitter splitter = mStringColonSplitter; + splitter.setString(enabledStr); + while (splitter.hasNext()) { + String curId = splitter.next(); + if (curId.equals(id)) { + if (enabled) { + // We are enabling this input method, but it is + // already enabled. Nothing to do. The previous + // state was enabled. + return true; + } + // We are disabling this input method, and it is + // currently enabled. Skip it to remove from the + // new list. + removed = true; + } else if (!enabled) { + // We are building a new list of input methods that + // doesn't contain the given one. + if (firstId == null) firstId = curId; + if (builder.length() > 0) builder.append(':'); + builder.append(curId); } - // We are disabling this input method, and it is - // currently enabled. Skip it to remove from the - // new list. - removed = true; - } else if (!enabled) { - // We are building a new list of input methods that - // doesn't contain the given one. - if (firstId == null) firstId = curId; - if (builder.length() > 0) builder.append(':'); - builder.append(curId); } } - } - - if (!enabled) { - if (!removed) { - // We are disabling the input method but it is already - // disabled. Nothing to do. The previous state was - // disabled. - return false; - } - // Update the setting with the new list of input methods. - Settings.Secure.putString(mContext.getContentResolver(), - Settings.Secure.ENABLED_INPUT_METHODS, builder.toString()); - // We the disabled input method is currently selected, switch - // to another one. - String selId = Settings.Secure.getString(mContext.getContentResolver(), - Settings.Secure.DEFAULT_INPUT_METHOD); - if (id.equals(selId)) { + + if (!enabled) { + if (!removed) { + // We are disabling the input method but it is already + // disabled. Nothing to do. The previous state was + // disabled. + return false; + } + // Update the setting with the new list of input methods. Settings.Secure.putString(mContext.getContentResolver(), - Settings.Secure.DEFAULT_INPUT_METHOD, - firstId != null ? firstId : ""); + Settings.Secure.ENABLED_INPUT_METHODS, builder.toString()); + // We the disabled input method is currently selected, switch + // to another one. + String selId = Settings.Secure.getString(mContext.getContentResolver(), + Settings.Secure.DEFAULT_INPUT_METHOD); + if (id.equals(selId)) { + Settings.Secure.putString(mContext.getContentResolver(), + Settings.Secure.DEFAULT_INPUT_METHOD, + firstId != null ? firstId : ""); + } + // Previous state was enabled. + return true; } - // Previous state was enabled. - return true; - } - - // Add in the newly enabled input method. - if (enabledStr == null || enabledStr.length() == 0) { - enabledStr = id; - } else { - enabledStr = enabledStr + ':' + id; + + // Add in the newly enabled input method. + if (enabledStr == null || enabledStr.length() == 0) { + enabledStr = id; + } else { + enabledStr = enabledStr + ':' + id; + } + + Settings.Secure.putString(mContext.getContentResolver(), + Settings.Secure.ENABLED_INPUT_METHODS, enabledStr); + + // Previous state was disabled. + return false; + } finally { + Binder.restoreCallingIdentity(ident); } - - Settings.Secure.putString(mContext.getContentResolver(), - Settings.Secure.ENABLED_INPUT_METHODS, enabledStr); - - // Previous state was disabled. - return false; } } - + // ---------------------------------------------------------------------- @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission("android.permission.DUMP") + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump InputMethodManager from from pid=" @@ -1395,8 +1560,12 @@ public class InputMethodManagerService extends IInputMethodManager.Stub return; } + IInputMethod method; + ClientState client; + + final Printer p = new PrintWriterPrinter(pw); + synchronized (mMethodMap) { - final Printer p = new PrintWriterPrinter(pw); p.println("Current Input Method Manager state:"); int N = mMethodList.size(); p.println(" Input Methods:"); @@ -1416,17 +1585,41 @@ public class InputMethodManagerService extends IInputMethodManager.Stub p.println(" mInputMethodIcon=" + mInputMethodIcon); p.println(" mInputMethodData=" + mInputMethodData); p.println(" mCurrentMethod=" + mCurMethodId); - p.println(" mCurSeq=" + mCurSeq + " mCurClient=" + mCurClient); + client = mCurClient; + p.println(" mCurClient=" + client + " mCurSeq=" + mCurSeq); + p.println(" mCurFocusedWindow=" + mCurFocusedWindow); p.println(" mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection + " mBoundToMethod=" + mBoundToMethod); p.println(" mCurToken=" + mCurToken); p.println(" mCurIntent=" + mCurIntent); + method = mCurMethod; p.println(" mCurMethod=" + mCurMethod); p.println(" mEnabledSession=" + mEnabledSession); p.println(" mShowRequested=" + mShowRequested + " mShowExplicitlyRequested=" + mShowExplicitlyRequested + + " mShowForced=" + mShowForced + " mInputShown=" + mInputShown); p.println(" mScreenOn=" + mScreenOn); } + + if (client != null) { + p.println(" "); + pw.flush(); + try { + client.client.asBinder().dump(fd, args); + } catch (RemoteException e) { + p.println("Input method client dead: " + e); + } + } + + if (method != null) { + p.println(" "); + pw.flush(); + try { + method.asBinder().dump(fd, args); + } catch (RemoteException e) { + p.println("Input method service dead: " + e); + } + } } } diff --git a/services/java/com/android/server/KeyInputQueue.java b/services/java/com/android/server/KeyInputQueue.java index 9874042eaeae760b9499b56017cc6ec20ae09530..63b486ce77d780d96fe66fc8233ccb5db9d5a172 100644 --- a/services/java/com/android/server/KeyInputQueue.java +++ b/services/java/com/android/server/KeyInputQueue.java @@ -165,6 +165,7 @@ public abstract class KeyInputQueue { public static native int getScancodeState(int deviceId, int sw); public static native int getKeycodeState(int sw); public static native int getKeycodeState(int deviceId, int sw); + public static native boolean hasKeys(int[] keycodes, boolean[] keyExists); public static KeyEvent newKeyEvent(InputDevice device, long downTime, long eventTime, boolean down, int keycode, int repeatCount, diff --git a/services/java/com/android/server/LocationManagerService.java b/services/java/com/android/server/LocationManagerService.java index ed9ee7927313ca3bff30c6cf3baad45c8fa53053..e48e04757826b0feded9b4f1bdc3f60637496c47 100644 --- a/services/java/com/android/server/LocationManagerService.java +++ b/services/java/com/android/server/LocationManagerService.java @@ -18,14 +18,16 @@ package com.android.server; import java.io.BufferedReader; import java.io.File; +import java.io.FileDescriptor; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; -import java.util.Locale; +import java.util.Map; import java.util.Set; import java.util.regex.Pattern; @@ -46,6 +48,7 @@ import android.location.LocationManager; import android.location.LocationProvider; import android.location.LocationProviderImpl; import android.net.ConnectivityManager; +import android.net.Uri; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Binder; @@ -57,19 +60,22 @@ import android.os.PowerManager; import android.os.RemoteException; import android.os.SystemClock; import android.provider.Settings; -import android.provider.Settings.SettingNotFoundException; import android.telephony.CellLocation; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Config; import android.util.Log; +import android.util.PrintWriterPrinter; +import android.util.SparseIntArray; +import com.android.internal.app.IBatteryStats; import com.android.internal.location.CellState; import com.android.internal.location.GpsLocationProvider; -import com.android.internal.location.LocationCollector; -import com.android.internal.location.LocationMasfClient; -import com.android.internal.location.NetworkLocationProvider; +import com.android.internal.location.ILocationCollector; +import com.android.internal.location.INetworkLocationManager; +import com.android.internal.location.INetworkLocationProvider; import com.android.internal.location.TrackProvider; +import com.android.server.am.BatteryStatsService; /** * The service class that manages LocationProviders and issues location @@ -77,7 +83,8 @@ import com.android.internal.location.TrackProvider; * * {@hide} */ -public class LocationManagerService extends ILocationManager.Stub { +public class LocationManagerService extends ILocationManager.Stub + implements INetworkLocationManager { private static final String TAG = "LocationManagerService"; // Minimum time interval between last known location writes, in milliseconds. @@ -121,13 +128,16 @@ public class LocationManagerService extends ILocationManager.Stub { private final Context mContext; private GpsLocationProvider mGpsLocationProvider; - private NetworkLocationProvider mNetworkLocationProvider; + private boolean mGpsNavigating; + private LocationProviderImpl mNetworkLocationProvider; + private INetworkLocationProvider mNetworkLocationInterface; private LocationWorkerHandler mLocationHandler; // Handler messages private static final int MESSAGE_HEARTBEAT = 1; private static final int MESSAGE_ACQUIRE_WAKE_LOCK = 2; private static final int MESSAGE_RELEASE_WAKE_LOCK = 3; + private static final int MESSAGE_INSTALL_NETWORK_LOCATION_PROVIDER = 4; // Alarm manager and wakelock variables private final static String ALARM_INTENT = "com.android.location.ALARM_INTENT"; @@ -143,33 +153,41 @@ public class LocationManagerService extends ILocationManager.Stub { private boolean mWakeLockNetworkReceived = true; private boolean mWifiWakeLockAcquired = false; private boolean mCellWakeLockAcquired = false; - + + private final IBatteryStats mBatteryStats; + /** * Mapping from listener IBinder/PendingIntent to local Listener wrappers. */ - private final HashMap mListeners = - new HashMap(); + private final ArrayList mListeners = new ArrayList(); + /** + * Used for reporting which UIDs are causing the GPS to run. + */ + private final SparseIntArray mReportedGpsUids = new SparseIntArray(); + private int mReportedGpsSeq = 0; + /** * Mapping from listener IBinder/PendingIntent to a map from provider name to UpdateRecord. + * This also serves as the lock for our state. */ - private final HashMap> mLocationListeners = - new HashMap>(); + private final HashMap> mLocationListeners = + new HashMap>(); /** * Mapping from listener IBinder/PendingIntent to a map from provider name to last broadcast * location. */ - private final HashMap> mLastFixBroadcast = - new HashMap>(); - private final HashMap> mLastStatusBroadcast = - new HashMap>(); + private final HashMap> mLastFixBroadcast = + new HashMap>(); + private final HashMap> mLastStatusBroadcast = + new HashMap>(); /** * Mapping from provider name to all its UpdateRecords */ - private final HashMap> mRecordsByProvider = - new HashMap>(); + private final HashMap> mRecordsByProvider = + new HashMap>(); /** * Mappings from provider name to object to use for current location. Locations @@ -196,17 +214,16 @@ public class LocationManagerService extends ILocationManager.Stub { // Last known cell service state private TelephonyManager mTelephonyManager; - private int mSignalStrength = -1; // Location collector - private LocationCollector mCollector; - - // Location MASF service - private LocationMasfClient mMasfClient; + private ILocationCollector mCollector; // Wifi Manager private WifiManager mWifiManager; + private int mNetworkState = LocationProvider.TEMPORARILY_UNAVAILABLE; + private boolean mWifiEnabled = false; + /** * A wrapper class holding either an ILocationListener or a PendingIntent to receive * location updates. @@ -214,22 +231,48 @@ public class LocationManagerService extends ILocationManager.Stub { private final class Receiver implements IBinder.DeathRecipient { final ILocationListener mListener; final PendingIntent mPendingIntent; + final int mUid; + final Object mKey; - Receiver(ILocationListener listener) { + Receiver(ILocationListener listener, int uid) { mListener = listener; mPendingIntent = null; + mUid = uid; + mKey = listener.asBinder(); } - Receiver(PendingIntent intent) { + Receiver(PendingIntent intent, int uid) { mPendingIntent = intent; mListener = null; + mUid = uid; + mKey = intent; + } + + @Override + public boolean equals(Object otherObj) { + if (otherObj instanceof Receiver) { + return mKey.equals( + ((Receiver)otherObj).mKey); + } + return false; } - public Object getKey() { + @Override + public int hashCode() { + return mKey.hashCode(); + } + + + @Override + public String toString() { if (mListener != null) { - return mListener.asBinder(); + return "Receiver{" + + Integer.toHexString(System.identityHashCode(this)) + + " uid " + mUid + " Listener " + mKey + "}"; } else { - return mPendingIntent; + return "Receiver{" + + Integer.toHexString(System.identityHashCode(this)) + + " uid " + mUid + " Intent " + mKey + "}"; } } @@ -255,10 +298,13 @@ public class LocationManagerService extends ILocationManager.Stub { throw new IllegalStateException("Request for non-existent intent"); } - public void onStatusChanged(String provider, int status, Bundle extras) - throws RemoteException { + public boolean callStatusChangedLocked(String provider, int status, Bundle extras) { if (mListener != null) { - mListener.onStatusChanged(provider, status, extras); + try { + mListener.onStatusChanged(provider, status, extras); + } catch (RemoteException e) { + return false; + } } else { Intent statusChanged = new Intent(); statusChanged.putExtras(extras); @@ -266,23 +312,29 @@ public class LocationManagerService extends ILocationManager.Stub { try { mPendingIntent.send(mContext, 0, statusChanged, null, null); } catch (PendingIntent.CanceledException e) { - _removeUpdates(this); + return false; } } + return true; } - public void onLocationChanged(Location location) throws RemoteException { + public boolean callLocationChangedLocked(Location location) { if (mListener != null) { - mListener.onLocationChanged(location); + try { + mListener.onLocationChanged(location); + } catch (RemoteException e) { + return false; + } } else { Intent locationChanged = new Intent(); locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, location); try { mPendingIntent.send(mContext, 0, locationChanged, null, null); } catch (PendingIntent.CanceledException e) { - _removeUpdates(this); + return false; } } + return true; } public void binderDied() { @@ -290,12 +342,12 @@ public class LocationManagerService extends ILocationManager.Stub { Log.d(TAG, "Location listener died"); } synchronized (mLocationListeners) { - _removeUpdates(this); + removeUpdatesLocked(this); } } } - private Location readLastKnownLocation(String provider) { + private Location readLastKnownLocationLocked(String provider) { Location location = null; String s = null; try { @@ -338,7 +390,7 @@ public class LocationManagerService extends ILocationManager.Stub { return location; } - private void writeLastKnownLocation(String provider, + private void writeLastKnownLocationLocked(String provider, Location location) { long now = SystemClock.elapsedRealtime(); Long last = mLastWriteTime.get(provider); @@ -396,36 +448,30 @@ public class LocationManagerService extends ILocationManager.Stub { * properties */ private void loadProviders() { - synchronized (LocationManagerService.class) { + synchronized (mLocationListeners) { if (sProvidersLoaded) { return; } // Load providers - loadProvidersNoSync(); + loadProvidersLocked(); sProvidersLoaded = true; } } - private void loadProvidersNoSync() { + private void loadProvidersLocked() { try { - _loadProvidersNoSync(); + _loadProvidersLocked(); } catch (Exception e) { Log.e(TAG, "Exception loading providers:", e); } } - private void _loadProvidersNoSync() { + private void _loadProvidersLocked() { // Attempt to load "real" providers first - if (NetworkLocationProvider.isSupported()) { - // Create a network location provider - mNetworkLocationProvider = new NetworkLocationProvider(mContext, mMasfClient); - LocationProviderImpl.addProvider(mNetworkLocationProvider); - } - if (GpsLocationProvider.isSupported()) { // Create a gps location provider - mGpsLocationProvider = new GpsLocationProvider(mContext, mCollector); + mGpsLocationProvider = new GpsLocationProvider(mContext); LocationProviderImpl.addProvider(mGpsLocationProvider); } @@ -494,7 +540,7 @@ public class LocationManagerService extends ILocationManager.Stub { } } - updateProviders(); + updateProvidersLocked(); } /** @@ -509,18 +555,15 @@ public class LocationManagerService extends ILocationManager.Stub { Log.d(TAG, "Constructed LocationManager Service"); } - // Initialize the LocationMasfClient - mMasfClient = new LocationMasfClient(mContext); - - // Create location collector - mCollector = new LocationCollector(mMasfClient); - // Alarm manager, needs to be done before calling loadProviders() below mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Create a wake lock, needs to be done before calling loadProviders() below PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); + + // Battery statistics service to be notified when GPS turns on or off + mBatteryStats = BatteryStatsService.getService(); // Load providers loadProviders(); @@ -548,26 +591,71 @@ public class LocationManagerService extends ILocationManager.Stub { intentFilter.addAction(Intent.ACTION_SCREEN_OFF); intentFilter.addAction(Intent.ACTION_SCREEN_ON); intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); + intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); + intentFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED); context.registerReceiver(powerStateReceiver, intentFilter); // Get the wifi manager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // Create a wifi lock for future use - mWifiLock = getWifiWakelock(); - - // There might be an existing wifi scan available - if (mWifiManager != null) { - List wifiScanResults = mWifiManager.getScanResults(); - if (wifiScanResults != null && wifiScanResults.size() != 0) { - if (mNetworkLocationProvider != null) { - mNetworkLocationProvider.updateWifiScanResults(wifiScanResults); + mWifiLock = getWifiWakelockLocked(); + } + + public void setInstallCallback(InstallCallback callback) { + synchronized (mLocationListeners) { + mLocationHandler.removeMessages(MESSAGE_INSTALL_NETWORK_LOCATION_PROVIDER); + Message m = Message.obtain(mLocationHandler, + MESSAGE_INSTALL_NETWORK_LOCATION_PROVIDER, callback); + mLocationHandler.sendMessageAtFrontOfQueue(m); + } + } + + public void setNetworkLocationProvider(INetworkLocationProvider provider) { + synchronized (mLocationListeners) { + mNetworkLocationInterface = provider; + provider.addListener(getPackageNames()); + mNetworkLocationProvider = (LocationProviderImpl)provider; + LocationProviderImpl.addProvider(mNetworkLocationProvider); + updateProvidersLocked(); + + // notify NetworkLocationProvider of any events it might have missed + synchronized (mLocationListeners) { + mNetworkLocationProvider.updateNetworkState(mNetworkState); + mNetworkLocationInterface.updateWifiEnabledState(mWifiEnabled); + mNetworkLocationInterface.updateCellLockStatus(mCellWakeLockAcquired); + + if (mLastCellState != null) { + if (mCollector != null) { + mCollector.updateCellState(mLastCellState); + } + mNetworkLocationProvider.updateCellState(mLastCellState); + } + + // There might be an existing wifi scan available + if (mWifiManager != null) { + List wifiScanResults = mWifiManager.getScanResults(); + if (wifiScanResults != null && wifiScanResults.size() != 0) { + mNetworkLocationInterface.updateWifiScanResults(wifiScanResults); + if (mCollector != null) { + mCollector.updateWifiScanResults(wifiScanResults); + } + } } } } } - private WifiManager.WifiLock getWifiWakelock() { + public void setLocationCollector(ILocationCollector collector) { + synchronized (mLocationListeners) { + mCollector = collector; + if (mGpsLocationProvider != null) { + mGpsLocationProvider.setLocationCollector(mCollector); + } + } + } + + private WifiManager.WifiLock getWifiWakelockLocked() { if (mWifiLock == null && mWifiManager != null) { mWifiLock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, WIFILOCK_KEY); mWifiLock.setReferenceCounted(false); @@ -575,7 +663,7 @@ public class LocationManagerService extends ILocationManager.Stub { return mWifiLock; } - private boolean isAllowedBySettings(String provider) { + private boolean isAllowedBySettingsLocked(String provider) { if (mEnabledProviders.contains(provider)) { return true; } @@ -590,7 +678,7 @@ public class LocationManagerService extends ILocationManager.Stub { return ((allowedProviders != null) && (allowedProviders.contains(provider))); } - private void checkPermissions(String provider) { + private void checkPermissionsSafe(String provider) { if (LocationManager.GPS_PROVIDER.equals(provider) && (mContext.checkCallingPermission(ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { @@ -606,7 +694,7 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private boolean isAllowedProvider(String provider) { + private boolean isAllowedProviderSafe(String provider) { if (LocationManager.GPS_PROVIDER.equals(provider) && (mContext.checkCallingPermission(ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { @@ -631,7 +719,9 @@ public class LocationManagerService extends ILocationManager.Stub { public List getAllProviders() { try { - return _getAllProviders(); + synchronized (mLocationListeners) { + return _getAllProvidersLocked(); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -640,7 +730,7 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private List _getAllProviders() { + private List _getAllProvidersLocked() { if (Config.LOGD) { Log.d(TAG, "getAllProviders"); } @@ -655,7 +745,9 @@ public class LocationManagerService extends ILocationManager.Stub { public List getProviders(boolean enabledOnly) { try { - return _getProviders(enabledOnly); + synchronized (mLocationListeners) { + return _getProvidersLocked(enabledOnly); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -664,7 +756,7 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private List _getProviders(boolean enabledOnly) { + private List _getProvidersLocked(boolean enabledOnly) { if (Config.LOGD) { Log.d(TAG, "getProviders"); } @@ -673,8 +765,8 @@ public class LocationManagerService extends ILocationManager.Stub { for (LocationProviderImpl p : providers) { String name = p.getName(); - if (isAllowedProvider(name)) { - if (enabledOnly && !isAllowedBySettings(name)) { + if (isAllowedProviderSafe(name)) { + if (enabledOnly && !isAllowedBySettingsLocked(name)) { continue; } out.add(name); @@ -684,26 +776,33 @@ public class LocationManagerService extends ILocationManager.Stub { } public void updateProviders() { + synchronized (mLocationListeners) { + updateProvidersLocked(); + } + } + + private void updateProvidersLocked() { for (LocationProviderImpl p : LocationProviderImpl.getProviders()) { boolean isEnabled = p.isEnabled(); String name = p.getName(); - boolean shouldBeEnabled = isAllowedBySettings(name); + boolean shouldBeEnabled = isAllowedBySettingsLocked(name); // Collection is only allowed when network provider is being used - if (p.getName().equals(LocationManager.NETWORK_PROVIDER)) { + if (mCollector != null && + p.getName().equals(LocationManager.NETWORK_PROVIDER)) { mCollector.updateNetworkProviderStatus(shouldBeEnabled); } if (isEnabled && !shouldBeEnabled) { - updateProviderListeners(name, false); + updateProviderListenersLocked(name, false); } else if (!isEnabled && shouldBeEnabled) { - updateProviderListeners(name, true); + updateProviderListenersLocked(name, true); } } } - private void updateProviderListeners(String provider, boolean enabled) { + private void updateProviderListenersLocked(String provider, boolean enabled) { int listeners = 0; LocationProviderImpl p = LocationProviderImpl.getProvider(provider); @@ -711,49 +810,63 @@ public class LocationManagerService extends ILocationManager.Stub { return; } - synchronized (mRecordsByProvider) { - HashSet records = mRecordsByProvider.get(provider); - if (records != null) { - for (UpdateRecord record : records) { - // Sends a notification message to the receiver - try { - Receiver receiver = record.mReceiver; - if (receiver.isListener()) { - if (enabled) { - receiver.getListener().onProviderEnabled(provider); - } else { - receiver.getListener().onProviderDisabled(provider); - } + ArrayList deadReceivers = null; + + ArrayList records = mRecordsByProvider.get(provider); + if (records != null) { + final int N = records.size(); + for (int i=0; i(); + deadReceivers.add(receiver); } } - } catch (RemoteException e) { - // The death link will clean this up. } - listeners++; + } catch (RemoteException e) { + // The death link will clean this up. } + listeners++; } } + if (deadReceivers != null) { + for (int i=deadReceivers.size()-1; i>=0; i--) { + removeUpdatesLocked(deadReceivers.get(i)); + } + } + if (enabled) { p.enable(); if (listeners > 0) { - p.setMinTime(getMinTime(provider)); + p.setMinTime(getMinTimeLocked(provider)); p.enableLocationTracking(true); - updateWakelockStatus(mScreenOn); + updateWakelockStatusLocked(mScreenOn); } } else { p.enableLocationTracking(false); + if (p == mGpsLocationProvider) { + mGpsNavigating = false; + reportStopGpsLocked(); + } p.disable(); - updateWakelockStatus(mScreenOn); + updateWakelockStatusLocked(mScreenOn); } if (enabled && listeners > 0) { @@ -765,40 +878,43 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private long getMinTime(String provider) { + private long getMinTimeLocked(String provider) { long minTime = Long.MAX_VALUE; - synchronized (mRecordsByProvider) { - HashSet records = mRecordsByProvider.get(provider); - if (records != null) { - for (UpdateRecord r : records) { - minTime = Math.min(minTime, r.mMinTime); - } + ArrayList records = mRecordsByProvider.get(provider); + if (records != null) { + for (int i=records.size()-1; i>=0; i--) { + minTime = Math.min(minTime, records.get(i).mMinTime); } } return minTime; } private class UpdateRecord { - String mProvider; - Receiver mReceiver; - long mMinTime; - float mMinDistance; - String[] mPackages; + final String mProvider; + final Receiver mReceiver; + final long mMinTime; + final float mMinDistance; + final int mUid; + final String[] mPackages; + /** + * Note: must be constructed with lock held. + */ UpdateRecord(String provider, long minTime, float minDistance, - Receiver receiver, String[] packages) { + Receiver receiver, int uid, String[] packages) { mProvider = provider; mReceiver = receiver; mMinTime = minTime; mMinDistance = minDistance; + mUid = uid; mPackages = packages; - synchronized (mRecordsByProvider) { - HashSet records = mRecordsByProvider.get(provider); - if (records == null) { - records = new HashSet(); - mRecordsByProvider.put(provider, records); - } + ArrayList records = mRecordsByProvider.get(provider); + if (records == null) { + records = new ArrayList(); + mRecordsByProvider.put(provider, records); + } + if (!records.contains(this)) { records.add(this); } } @@ -807,18 +923,39 @@ public class LocationManagerService extends ILocationManager.Stub { * Method to be called when a record will no longer be used. Calling this multiple times * must have the same effect as calling it once. */ - public void dispose() { - synchronized (mRecordsByProvider) { - HashSet records = mRecordsByProvider.get(this.mProvider); - records.remove(this); - } + void disposeLocked() { + ArrayList records = mRecordsByProvider.get(this.mProvider); + records.remove(this); } + @Override + public String toString() { + return "UpdateRecord{" + + Integer.toHexString(System.identityHashCode(this)) + + " " + mProvider + " " + mReceiver + "}"; + } + + void dump(PrintWriter pw, String prefix) { + pw.println(prefix + this); + pw.println(prefix + "mProvider=" + mProvider + " mReceiver=" + mReceiver); + pw.println(prefix + "mMinTime=" + mMinTime + " mMinDistance=" + mMinDistance); + StringBuilder sb = new StringBuilder(); + if (mPackages != null) { + for (int i=0; i 0) sb.append(", "); + sb.append(mPackages[i]); + } + } + pw.println(prefix + "mUid=" + mUid + " mPackages=" + sb); + } + /** * Calls dispose(). */ @Override protected void finalize() { - dispose(); + synchronized (mLocationListeners) { + disposeLocked(); + } } } @@ -826,8 +963,10 @@ public class LocationManagerService extends ILocationManager.Stub { long minTime, float minDistance, ILocationListener listener) { try { - _requestLocationUpdates(provider, minTime, minDistance, - new Receiver(listener)); + synchronized (mLocationListeners) { + requestLocationUpdatesLocked(provider, minTime, minDistance, + new Receiver(listener, Binder.getCallingUid())); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -838,8 +977,10 @@ public class LocationManagerService extends ILocationManager.Stub { public void requestLocationUpdatesPI(String provider, long minTime, float minDistance, PendingIntent intent) { try { - _requestLocationUpdates(provider, minTime, minDistance, - new Receiver(intent)); + synchronized (mLocationListeners) { + requestLocationUpdatesLocked(provider, minTime, minDistance, + new Receiver(intent, Binder.getCallingUid())); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -847,11 +988,10 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void _requestLocationUpdates(String provider, + private void requestLocationUpdatesLocked(String provider, long minTime, float minDistance, Receiver receiver) { - Object key = receiver.getKey(); if (Config.LOGD) { - Log.d(TAG, "_requestLocationUpdates: listener = " + key); + Log.d(TAG, "_requestLocationUpdates: listener = " + receiver); } LocationProviderImpl impl = LocationProviderImpl.getProvider(provider); @@ -859,62 +999,63 @@ public class LocationManagerService extends ILocationManager.Stub { throw new IllegalArgumentException("provider=" + provider); } - checkPermissions(provider); + checkPermissionsSafe(provider); String[] packages = getPackageNames(); // so wakelock calls will succeed + final int callingUid = Binder.getCallingUid(); long identity = Binder.clearCallingIdentity(); try { - UpdateRecord r = new UpdateRecord(provider, minTime, minDistance, receiver, packages); - synchronized (mLocationListeners) { - if (mListeners.get(key) == null) { - try { - if (receiver.isListener()) { - receiver.getListener().asBinder().linkToDeath(receiver, 0); - } - mListeners.put(key, receiver); - } catch (RemoteException e) { - return; + UpdateRecord r = new UpdateRecord(provider, minTime, minDistance, + receiver, callingUid, packages); + if (!mListeners.contains(receiver)) { + try { + if (receiver.isListener()) { + receiver.getListener().asBinder().linkToDeath(receiver, 0); } + mListeners.add(receiver); + } catch (RemoteException e) { + return; } + } - HashMap records = mLocationListeners.get(key); - if (records == null) { - records = new HashMap(); - mLocationListeners.put(key, records); - } - UpdateRecord oldRecord = records.put(provider, r); - if (oldRecord != null) { - oldRecord.dispose(); - } - - if (impl instanceof NetworkLocationProvider) { - ((NetworkLocationProvider) impl).addListener(packages); - } - - boolean isProviderEnabled = isAllowedBySettings(provider); - if (isProviderEnabled) { - long minTimeForProvider = getMinTime(provider); - impl.setMinTime(minTimeForProvider); - impl.enableLocationTracking(true); - updateWakelockStatus(mScreenOn); + HashMap records = mLocationListeners.get(receiver); + if (records == null) { + records = new HashMap(); + mLocationListeners.put(receiver, records); + } + UpdateRecord oldRecord = records.put(provider, r); + if (oldRecord != null) { + oldRecord.disposeLocked(); + } - // Clear heartbeats if any before starting a new one - mLocationHandler.removeMessages(MESSAGE_HEARTBEAT, provider); - Message m = Message.obtain(mLocationHandler, MESSAGE_HEARTBEAT, provider); - mLocationHandler.sendMessageAtTime(m, SystemClock.uptimeMillis() + 1000); + boolean isProviderEnabled = isAllowedBySettingsLocked(provider); + if (isProviderEnabled) { + long minTimeForProvider = getMinTimeLocked(provider); + impl.setMinTime(minTimeForProvider); + impl.enableLocationTracking(true); + updateWakelockStatusLocked(mScreenOn); - } else { - try { - // Notify the listener that updates are currently disabled - if (receiver.isListener()) { - receiver.getListener().onProviderDisabled(provider); - } - } catch(RemoteException e) { - Log.w(TAG, "RemoteException calling onProviderDisabled on " + - receiver.getListener()); + if (provider.equals(LocationManager.GPS_PROVIDER)) { + if (mGpsNavigating) { + updateReportedGpsLocked(); + } + } + + // Clear heartbeats if any before starting a new one + mLocationHandler.removeMessages(MESSAGE_HEARTBEAT, provider); + Message m = Message.obtain(mLocationHandler, MESSAGE_HEARTBEAT, provider); + mLocationHandler.sendMessageAtTime(m, SystemClock.uptimeMillis() + 1000); + } else { + try { + // Notify the listener that updates are currently disabled + if (receiver.isListener()) { + receiver.getListener().onProviderDisabled(provider); } + } catch(RemoteException e) { + Log.w(TAG, "RemoteException calling onProviderDisabled on " + + receiver.getListener()); } } } finally { @@ -924,7 +1065,9 @@ public class LocationManagerService extends ILocationManager.Stub { public void removeUpdates(ILocationListener listener) { try { - _removeUpdates(new Receiver(listener)); + synchronized (mLocationListeners) { + removeUpdatesLocked(new Receiver(listener, Binder.getCallingUid())); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -934,7 +1077,9 @@ public class LocationManagerService extends ILocationManager.Stub { public void removeUpdatesPI(PendingIntent intent) { try { - _removeUpdates(new Receiver(intent)); + synchronized (mLocationListeners) { + removeUpdatesLocked(new Receiver(intent, Binder.getCallingUid())); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -942,72 +1087,75 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void _removeUpdates(Receiver receiver) { - Object key = receiver.getKey(); + private void removeUpdatesLocked(Receiver receiver) { if (Config.LOGD) { - Log.d(TAG, "_removeUpdates: listener = " + key); + Log.d(TAG, "_removeUpdates: listener = " + receiver); } // so wakelock calls will succeed + final int callingUid = Binder.getCallingUid(); long identity = Binder.clearCallingIdentity(); try { - synchronized (mLocationListeners) { - Receiver myReceiver = mListeners.remove(key); - if ((myReceiver != null) && (myReceiver.isListener())) { + int idx = mListeners.indexOf(receiver); + if (idx >= 0) { + Receiver myReceiver = mListeners.remove(idx); + if (myReceiver.isListener()) { myReceiver.getListener().asBinder().unlinkToDeath(myReceiver, 0); } + } - // Record which providers were associated with this listener - HashSet providers = new HashSet(); - HashMap oldRecords = mLocationListeners.get(key); - if (oldRecords != null) { - // Call dispose() on the obsolete update records. - for (UpdateRecord record : oldRecords.values()) { - if (record.mProvider.equals(LocationManager.NETWORK_PROVIDER)) { - if (mNetworkLocationProvider != null) { - mNetworkLocationProvider.removeListener(record.mPackages); - } + // Record which providers were associated with this listener + HashSet providers = new HashSet(); + HashMap oldRecords = mLocationListeners.get(receiver); + if (oldRecords != null) { + // Call dispose() on the obsolete update records. + for (UpdateRecord record : oldRecords.values()) { + if (record.mProvider.equals(LocationManager.NETWORK_PROVIDER)) { + if (mNetworkLocationInterface != null) { + mNetworkLocationInterface.removeListener(record.mPackages); } - record.dispose(); } - // Accumulate providers - providers.addAll(oldRecords.keySet()); + record.disposeLocked(); + } + // Accumulate providers + providers.addAll(oldRecords.keySet()); + } + + mLocationListeners.remove(receiver); + mLastFixBroadcast.remove(receiver); + mLastStatusBroadcast.remove(receiver); + + // See if the providers associated with this listener have any + // other listeners; if one does, inform it of the new smallest minTime + // value; if one does not, disable location tracking for it + for (String provider : providers) { + // If provider is already disabled, don't need to do anything + if (!isAllowedBySettingsLocked(provider)) { + continue; } - mLocationListeners.remove(key); - mLastFixBroadcast.remove(key); - mLastStatusBroadcast.remove(key); - - // See if the providers associated with this listener have any - // other listeners; if one does, inform it of the new smallest minTime - // value; if one does not, disable location tracking for it - for (String provider : providers) { - // If provider is already disabled, don't need to do anything - if (!isAllowedBySettings(provider)) { - continue; - } + boolean hasOtherListener = false; + ArrayList recordsForProvider = mRecordsByProvider.get(provider); + if (recordsForProvider != null && recordsForProvider.size() > 0) { + hasOtherListener = true; + } - boolean hasOtherListener = false; - synchronized (mRecordsByProvider) { - HashSet recordsForProvider = mRecordsByProvider.get(provider); - if (recordsForProvider != null && recordsForProvider.size() > 0) { - hasOtherListener = true; - } + LocationProviderImpl p = LocationProviderImpl.getProvider(provider); + if (p != null) { + if (hasOtherListener) { + p.setMinTime(getMinTimeLocked(provider)); + } else { + mLocationHandler.removeMessages(MESSAGE_HEARTBEAT, provider); + p.enableLocationTracking(false); } - - LocationProviderImpl p = LocationProviderImpl.getProvider(provider); - if (p != null) { - if (hasOtherListener) { - p.setMinTime(getMinTime(provider)); - } else { - mLocationHandler.removeMessages(MESSAGE_HEARTBEAT, provider); - p.enableLocationTracking(false); - } + + if (p == mGpsLocationProvider && mGpsNavigating) { + updateReportedGpsLocked(); } } - - updateWakelockStatus(mScreenOn); } + + updateWakelockStatusLocked(mScreenOn); } finally { Binder.restoreCallingIdentity(identity); } @@ -1018,7 +1166,7 @@ public class LocationManagerService extends ILocationManager.Stub { return false; } if (mContext.checkCallingPermission(ACCESS_FINE_LOCATION) != - PackageManager.PERMISSION_GRANTED) { + PackageManager.PERMISSION_GRANTED) { throw new SecurityException("Requires ACCESS_FINE_LOCATION permission"); } @@ -1032,36 +1180,42 @@ public class LocationManagerService extends ILocationManager.Stub { } public void removeGpsStatusListener(IGpsStatusListener listener) { - mGpsLocationProvider.removeGpsStatusListener(listener); + synchronized (mLocationListeners) { + mGpsLocationProvider.removeGpsStatusListener(listener); + } } public boolean sendExtraCommand(String provider, String command, Bundle extras) { // first check for permission to the provider - checkPermissions(provider); + checkPermissionsSafe(provider); // and check for ACCESS_LOCATION_EXTRA_COMMANDS if ((mContext.checkCallingPermission(ACCESS_LOCATION_EXTRA_COMMANDS) != PackageManager.PERMISSION_GRANTED)) { throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission"); } - LocationProviderImpl impl = LocationProviderImpl.getProvider(provider); - if (provider == null) { - return false; + synchronized (mLocationListeners) { + LocationProviderImpl impl = LocationProviderImpl.getProvider(provider); + if (provider == null) { + return false; + } + + return impl.sendExtraCommand(command, extras); } - - return impl.sendExtraCommand(command, extras); } class ProximityAlert { - double mLatitude; - double mLongitude; - float mRadius; - long mExpiration; - PendingIntent mIntent; - Location mLocation; - - public ProximityAlert(double latitude, double longitude, + final int mUid; + final double mLatitude; + final double mLongitude; + final float mRadius; + final long mExpiration; + final PendingIntent mIntent; + final Location mLocation; + + public ProximityAlert(int uid, double latitude, double longitude, float radius, long expiration, PendingIntent intent) { + mUid = uid; mLatitude = latitude; mLongitude = longitude; mRadius = radius; @@ -1073,15 +1227,15 @@ public class LocationManagerService extends ILocationManager.Stub { mLocation.setLongitude(longitude); } - public long getExpiration() { + long getExpiration() { return mExpiration; } - public PendingIntent getIntent() { + PendingIntent getIntent() { return mIntent; } - public boolean isInProximity(double latitude, double longitude) { + boolean isInProximity(double latitude, double longitude) { Location loc = new Location(""); loc.setLatitude(latitude); loc.setLongitude(longitude); @@ -1089,6 +1243,22 @@ public class LocationManagerService extends ILocationManager.Stub { double radius = loc.distanceTo(mLocation); return radius <= mRadius; } + + @Override + public String toString() { + return "ProximityAlert{" + + Integer.toHexString(System.identityHashCode(this)) + + " uid " + mUid + mIntent + "}"; + } + + void dump(PrintWriter pw, String prefix) { + pw.println(prefix + this); + pw.println(prefix + "mLatitude=" + mLatitude + " mLongitude=" + mLongitude); + pw.println(prefix + "mRadius=" + mRadius + " mExpiration=" + mExpiration); + pw.println(prefix + "mIntent=" + mIntent); + pw.println(prefix + "mLocation:"); + mLocation.dump(new PrintWriterPrinter(pw), prefix + " "); + } } // Listener for receiving locations to trigger proximity alerts @@ -1096,6 +1266,7 @@ public class LocationManagerService extends ILocationManager.Stub { boolean isGpsAvailable = false; + // Note: this is called with the lock held. public void onLocationChanged(Location loc) { // If Gps is available, then ignore updates from NetworkLocationProvider @@ -1180,16 +1351,19 @@ public class LocationManagerService extends ILocationManager.Stub { } + // Note: this is called with the lock held. public void onProviderDisabled(String provider) { if (provider.equals(LocationManager.GPS_PROVIDER)) { isGpsAvailable = false; } } + // Note: this is called with the lock held. public void onProviderEnabled(String provider) { // ignore } + // Note: this is called with the lock held. public void onStatusChanged(String provider, int status, Bundle extras) { if ((provider.equals(LocationManager.GPS_PROVIDER)) && (status != LocationProvider.AVAILABLE)) { @@ -1201,7 +1375,9 @@ public class LocationManagerService extends ILocationManager.Stub { public void addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent) { try { - _addProximityAlert(latitude, longitude, radius, expiration, intent); + synchronized (mLocationListeners) { + addProximityAlertLocked(latitude, longitude, radius, expiration, intent); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -1209,7 +1385,7 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void _addProximityAlert(double latitude, double longitude, + private void addProximityAlertLocked(double latitude, double longitude, float radius, long expiration, PendingIntent intent) { if (Config.LOGD) { Log.d(TAG, "addProximityAlert: latitude = " + latitude + @@ -1219,37 +1395,42 @@ public class LocationManagerService extends ILocationManager.Stub { } // Require ability to access all providers for now - if (!isAllowedProvider(LocationManager.GPS_PROVIDER) || - !isAllowedProvider(LocationManager.NETWORK_PROVIDER)) { + if (!isAllowedProviderSafe(LocationManager.GPS_PROVIDER) || + !isAllowedProviderSafe(LocationManager.NETWORK_PROVIDER)) { throw new SecurityException("Requires ACCESS_FINE_LOCATION permission"); } if (expiration != -1) { expiration += System.currentTimeMillis(); } - ProximityAlert alert = new ProximityAlert(latitude, longitude, radius, expiration, intent); + ProximityAlert alert = new ProximityAlert(Binder.getCallingUid(), + latitude, longitude, radius, expiration, intent); mProximityAlerts.put(intent, alert); if (mProximityListener == null) { - mProximityListener = new Receiver(new ProximityListener()); + mProximityListener = new Receiver(new ProximityListener(), -1); LocationProvider provider = LocationProviderImpl.getProvider( LocationManager.GPS_PROVIDER); if (provider != null) { - _requestLocationUpdates(provider.getName(), 1000L, 1.0f, mProximityListener); + requestLocationUpdatesLocked(provider.getName(), 1000L, 1.0f, mProximityListener); } provider = LocationProviderImpl.getProvider(LocationManager.NETWORK_PROVIDER); if (provider != null) { - _requestLocationUpdates(provider.getName(), 1000L, 1.0f, mProximityListener); + requestLocationUpdatesLocked(provider.getName(), 1000L, 1.0f, mProximityListener); } + } else if (mGpsNavigating) { + updateReportedGpsLocked(); } } public void removeProximityAlert(PendingIntent intent) { try { - _removeProximityAlert(intent); + synchronized (mLocationListeners) { + removeProximityAlertLocked(intent); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -1257,15 +1438,17 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void _removeProximityAlert(PendingIntent intent) { + private void removeProximityAlertLocked(PendingIntent intent) { if (Config.LOGD) { Log.d(TAG, "removeProximityAlert: intent = " + intent); } mProximityAlerts.remove(intent); if (mProximityAlerts.size() == 0) { - _removeUpdates(mProximityListener); + removeUpdatesLocked(mProximityListener); mProximityListener = null; + } else if (mGpsNavigating) { + updateReportedGpsLocked(); } } @@ -1276,7 +1459,9 @@ public class LocationManagerService extends ILocationManager.Stub { */ public Bundle getProviderInfo(String provider) { try { - return _getProviderInfo(provider); + synchronized (mLocationListeners) { + return _getProviderInfoLocked(provider); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -1285,13 +1470,13 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private Bundle _getProviderInfo(String provider) { + private Bundle _getProviderInfoLocked(String provider) { LocationProviderImpl p = LocationProviderImpl.getProvider(provider); if (p == null) { return null; } - checkPermissions(provider); + checkPermissionsSafe(provider); Bundle b = new Bundle(); b.putBoolean("network", p.requiresNetwork()); @@ -1309,7 +1494,9 @@ public class LocationManagerService extends ILocationManager.Stub { public boolean isProviderEnabled(String provider) { try { - return _isProviderEnabled(provider); + synchronized (mLocationListeners) { + return _isProviderEnabledLocked(provider); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -1318,19 +1505,21 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private boolean _isProviderEnabled(String provider) { - checkPermissions(provider); + private boolean _isProviderEnabledLocked(String provider) { + checkPermissionsSafe(provider); LocationProviderImpl p = LocationProviderImpl.getProvider(provider); if (p == null) { throw new IllegalArgumentException("provider=" + provider); } - return isAllowedBySettings(provider); + return isAllowedBySettingsLocked(provider); } public Location getLastKnownLocation(String provider) { try { - return _getLastKnownLocation(provider); + synchronized (mLocationListeners) { + return _getLastKnownLocationLocked(provider); + } } catch (SecurityException se) { throw se; } catch (Exception e) { @@ -1339,22 +1528,22 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private Location _getLastKnownLocation(String provider) { - checkPermissions(provider); + private Location _getLastKnownLocationLocked(String provider) { + checkPermissionsSafe(provider); LocationProviderImpl p = LocationProviderImpl.getProvider(provider); if (p == null) { throw new IllegalArgumentException("provider=" + provider); } - if (!isAllowedBySettings(provider)) { + if (!isAllowedBySettingsLocked(provider)) { return null; } Location location = mLastKnownLocation.get(provider); if (location == null) { // Get the persistent last known location for the provider - location = readLastKnownLocation(provider); + location = readLastKnownLocationLocked(provider); if (location != null) { mLastKnownLocation.put(provider, location); } @@ -1363,7 +1552,7 @@ public class LocationManagerService extends ILocationManager.Stub { return location; } - private boolean shouldBroadcast(Location loc, Location lastLoc, UpdateRecord record) { + private static boolean shouldBroadcastSafe(Location loc, Location lastLoc, UpdateRecord record) { // Always broadcast the first update if (lastLoc == null) { return true; @@ -1386,8 +1575,8 @@ public class LocationManagerService extends ILocationManager.Stub { return true; } - private void handleLocationChanged(String provider) { - HashSet records = mRecordsByProvider.get(provider); + private void handleLocationChangedLocked(String provider) { + ArrayList records = mRecordsByProvider.get(provider); if (records == null || records.size() == 0) { return; } @@ -1424,9 +1613,9 @@ public class LocationManagerService extends ILocationManager.Stub { } else { location.set(loc); } - writeLastKnownLocation(provider, loc); + writeLastKnownLocationLocked(provider, loc); - if (p instanceof NetworkLocationProvider) { + if (p instanceof INetworkLocationProvider) { mWakeLockNetworkReceived = true; } else if (p instanceof GpsLocationProvider) { // Gps location received signal is in NetworkStateBroadcastReceiver @@ -1459,40 +1648,44 @@ public class LocationManagerService extends ILocationManager.Stub { extras.putAll(mockExtras); } + ArrayList deadReceivers = null; + // Broadcast location or status to all listeners - for (UpdateRecord r : records) { + final int N = records.size(); + for (int i=0; i map = mLastFixBroadcast.get(key); + HashMap map = mLastFixBroadcast.get(receiver); if (map == null) { map = new HashMap(); - mLastFixBroadcast.put(key, map); + mLastFixBroadcast.put(receiver, map); } Location lastLoc = map.get(provider); - if ((lastLoc == null) || shouldBroadcast(loc, lastLoc, r)) { + if ((lastLoc == null) || shouldBroadcastSafe(loc, lastLoc, r)) { if (lastLoc == null) { lastLoc = new Location(loc); map.put(provider, lastLoc); } else { lastLoc.set(loc); } - try { - receiver.onLocationChanged(loc); - } catch (RemoteException doe) { + if (!receiver.callLocationChangedLocked(loc)) { Log.w(TAG, "RemoteException calling onLocationChanged on " + receiver); - _removeUpdates(receiver); + if (deadReceivers == null) { + deadReceivers = new ArrayList(); + } + deadReceivers.add(receiver); } } } // Broadcast status message - HashMap statusMap = mLastStatusBroadcast.get(key); + HashMap statusMap = mLastStatusBroadcast.get(receiver); if (statusMap == null) { statusMap = new HashMap(); - mLastStatusBroadcast.put(key, statusMap); + mLastStatusBroadcast.put(receiver, statusMap); } long prevStatusUpdateTime = (statusMap.get(provider) != null) ? statusMap.get(provider) : 0; @@ -1501,14 +1694,23 @@ public class LocationManagerService extends ILocationManager.Stub { (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) { statusMap.put(provider, newStatusUpdateTime); - try { - receiver.onStatusChanged(provider, status, extras); - } catch (RemoteException doe) { + if (!receiver.callStatusChangedLocked(provider, status, extras)) { Log.w(TAG, "RemoteException calling onStatusChanged on " + receiver); - _removeUpdates(receiver); + if (deadReceivers == null) { + deadReceivers = new ArrayList(); + } + if (!deadReceivers.contains(receiver)) { + deadReceivers.add(receiver); + } } } } + + if (deadReceivers != null) { + for (int i=deadReceivers.size()-1; i>=0; i--) { + removeUpdatesLocked(deadReceivers.get(i)); + } + } } private class LocationWorkerHandler extends Handler { @@ -1519,57 +1721,68 @@ public class LocationManagerService extends ILocationManager.Stub { if (msg.what == MESSAGE_HEARTBEAT) { // log("LocationWorkerHandler: Heartbeat!"); - synchronized (mRecordsByProvider) { + synchronized (mLocationListeners) { String provider = (String) msg.obj; - if (!isAllowedBySettings(provider)) { + if (!isAllowedBySettingsLocked(provider)) { return; } // Process the location fix if the screen is on or we're holding a wakelock if (mScreenOn || (mWakeLockAcquireTime != 0)) { - handleLocationChanged(provider); + handleLocationChangedLocked(provider); } // If it continues to have listeners - HashSet records = mRecordsByProvider.get(provider); + ArrayList records = mRecordsByProvider.get(provider); if (records != null && records.size() > 0) { Message m = Message.obtain(this, MESSAGE_HEARTBEAT, provider); sendMessageAtTime(m, SystemClock.uptimeMillis() + 1000); } - } - - if ((mWakeLockAcquireTime != 0) && - (SystemClock.elapsedRealtime() - mWakeLockAcquireTime - > MAX_TIME_FOR_WAKE_LOCK)) { - - removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK); - removeMessages(MESSAGE_RELEASE_WAKE_LOCK); - - log("LocationWorkerHandler: Exceeded max time for wake lock"); - Message m = Message.obtain(this, MESSAGE_RELEASE_WAKE_LOCK); - sendMessageAtFrontOfQueue(m); - - } else if (mWakeLockAcquireTime != 0 && - mWakeLockGpsReceived && mWakeLockNetworkReceived) { - - removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK); - removeMessages(MESSAGE_RELEASE_WAKE_LOCK); - log("LocationWorkerHandler: Locations received."); - mWakeLockAcquireTime = 0; - Message m = Message.obtain(this, MESSAGE_RELEASE_WAKE_LOCK); - sendMessageDelayed(m, TIME_AFTER_WAKE_LOCK); + if ((mWakeLockAcquireTime != 0) && + (SystemClock.elapsedRealtime() - mWakeLockAcquireTime + > MAX_TIME_FOR_WAKE_LOCK)) { + + removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK); + removeMessages(MESSAGE_RELEASE_WAKE_LOCK); + + log("LocationWorkerHandler: Exceeded max time for wake lock"); + Message m = Message.obtain(this, MESSAGE_RELEASE_WAKE_LOCK); + sendMessageAtFrontOfQueue(m); + + } else if (mWakeLockAcquireTime != 0 && + mWakeLockGpsReceived && mWakeLockNetworkReceived) { + + removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK); + removeMessages(MESSAGE_RELEASE_WAKE_LOCK); + + log("LocationWorkerHandler: Locations received."); + mWakeLockAcquireTime = 0; + Message m = Message.obtain(this, MESSAGE_RELEASE_WAKE_LOCK); + sendMessageDelayed(m, TIME_AFTER_WAKE_LOCK); + } } } else if (msg.what == MESSAGE_ACQUIRE_WAKE_LOCK) { log("LocationWorkerHandler: Acquire"); - acquireWakeLock(); + synchronized (mLocationListeners) { + acquireWakeLockLocked(); + } } else if (msg.what == MESSAGE_RELEASE_WAKE_LOCK) { log("LocationWorkerHandler: Release"); // Update wakelock status so the next alarm is set before releasing wakelock - updateWakelockStatus(mScreenOn); - releaseWakeLock(); + synchronized (mLocationListeners) { + updateWakelockStatusLocked(mScreenOn); + releaseWakeLockLocked(); + } + } else if (msg.what == MESSAGE_INSTALL_NETWORK_LOCATION_PROVIDER) { + synchronized (mLocationListeners) { + Log.d(TAG, "installing network location provider"); + INetworkLocationManager.InstallCallback callback = + (INetworkLocationManager.InstallCallback)msg.obj; + callback.installNetworkLocationProvider(LocationManagerService.this); + } } } catch (Exception e) { // Log, don't crash! @@ -1578,45 +1791,113 @@ public class LocationManagerService extends ILocationManager.Stub { } } + class CellLocationUpdater extends Thread { + CellLocation mNextLocation; + + CellLocationUpdater() { + super("CellLocationUpdater"); + } + + @Override + public void run() { + int curAsu = -1; + CellLocation curLocation = null; + + while (true) { + // See if there is more work to do... + synchronized (mLocationListeners) { + if (curLocation == mNextLocation) { + mCellLocationUpdater = null; + break; + } + + curLocation = mNextLocation; + if (curLocation == null) { + mCellLocationUpdater = null; + break; + } + + curAsu = mLastSignalStrength; + + mNextLocation = null; + } + + try { + // Gets cell state. This can block so must be done without + // locks held. + CellState cs = new CellState(mTelephonyManager, curLocation, curAsu); + + synchronized (mLocationListeners) { + mLastCellState = cs; + + cs.updateSignalStrength(mLastSignalStrength); + cs.updateRadioType(mLastRadioType); + + // Notify collector + if (mCollector != null) { + mCollector.updateCellState(cs); + } + + // Updates providers + List providers = LocationProviderImpl.getProviders(); + for (LocationProviderImpl provider : providers) { + if (provider.requiresCell()) { + provider.updateCellState(cs); + } + } + } + } catch (RuntimeException e) { + Log.e(TAG, "Exception in PhoneStateListener.onCellLocationChanged:", e); + } + } + } + } + + CellLocationUpdater mCellLocationUpdater = null; + CellState mLastCellState = null; + int mLastSignalStrength = -1; + int mLastRadioType = -1; + PhoneStateListener mPhoneStateListener = new PhoneStateListener() { - private CellState mLastCellState = null; @Override public void onCellLocationChanged(CellLocation cellLocation) { - try { - int asu = mSignalStrength; - - // Gets cell state - mLastCellState = new CellState(mTelephonyManager, cellLocation, asu); - - // Notify collector - mCollector.updateCellState(mLastCellState); - - // Updates providers - List providers = LocationProviderImpl.getProviders(); - for (LocationProviderImpl provider : providers) { - if (provider.requiresCell()) { - provider.updateCellState(mLastCellState); - } + synchronized (mLocationListeners) { + if (mCellLocationUpdater == null) { + mCellLocationUpdater = new CellLocationUpdater(); + mCellLocationUpdater.start(); } - } catch (Exception e) { - Log.e(TAG, "Exception in PhoneStateListener.onCellLocationCahnged:", e); + mCellLocationUpdater.mNextLocation = cellLocation; } } @Override public void onSignalStrengthChanged(int asu) { - mSignalStrength = asu; - - if (mLastCellState != null) { - mLastCellState.updateSignalStrength(asu); + synchronized (mLocationListeners) { + mLastSignalStrength = asu; + + if (mLastCellState != null) { + mLastCellState.updateSignalStrength(asu); + } } } @Override public void onDataConnectionStateChanged(int state) { - if (mLastCellState != null) { - mLastCellState.updateRadioType(mTelephonyManager); + synchronized (mLocationListeners) { + // Get radio type + int radioType = mTelephonyManager.getNetworkType(); + if (radioType == TelephonyManager.NETWORK_TYPE_GPRS || + radioType == TelephonyManager.NETWORK_TYPE_EDGE) { + radioType = CellState.RADIO_TYPE_GPRS; + } else if (radioType == TelephonyManager.NETWORK_TYPE_UMTS) { + radioType = CellState.RADIO_TYPE_WCDMA; + } + mLastRadioType = radioType; + + if (mLastCellState != null) { + mLastCellState.updateRadioType(radioType); + } } } }; @@ -1626,29 +1907,82 @@ public class LocationManagerService extends ILocationManager.Stub { String action = intent.getAction(); if (action.equals(ALARM_INTENT)) { - mLocationHandler.removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK); - mLocationHandler.removeMessages(MESSAGE_RELEASE_WAKE_LOCK); - - log("PowerStateBroadcastReceiver: Alarm received"); - Message m = mLocationHandler.obtainMessage(MESSAGE_ACQUIRE_WAKE_LOCK); - mLocationHandler.sendMessageAtFrontOfQueue(m); + synchronized (mLocationListeners) { + log("PowerStateBroadcastReceiver: Alarm received"); + mLocationHandler.removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK); + // Have to do this immediately, rather than posting a + // message, so we execute our code while the system + // is holding a wake lock until the alarm broadcast + // is finished. + acquireWakeLockLocked(); + } } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { log("PowerStateBroadcastReceiver: Screen off"); - updateWakelockStatus(false); + synchronized (mLocationListeners) { + updateWakelockStatusLocked(false); + } } else if (action.equals(Intent.ACTION_SCREEN_ON)) { log("PowerStateBroadcastReceiver: Screen on"); - updateWakelockStatus(true); + synchronized (mLocationListeners) { + updateWakelockStatusLocked(true); + } } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { log("PowerStateBroadcastReceiver: Battery changed"); - int scale = intent.getIntExtra(BATTERY_EXTRA_SCALE, 100); - int level = intent.getIntExtra(BATTERY_EXTRA_LEVEL, 0); - boolean plugged = intent.getIntExtra(BATTERY_EXTRA_PLUGGED, 0) != 0; - - // Notify collector battery state - mCollector.updateBatteryState(scale, level, plugged); + synchronized (mLocationListeners) { + int scale = intent.getIntExtra(BATTERY_EXTRA_SCALE, 100); + int level = intent.getIntExtra(BATTERY_EXTRA_LEVEL, 0); + boolean plugged = intent.getIntExtra(BATTERY_EXTRA_PLUGGED, 0) != 0; + + // Notify collector battery state + if (mCollector != null) { + mCollector.updateBatteryState(scale, level, plugged); + } + } + } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED) + || action.equals(Intent.ACTION_PACKAGE_RESTARTED)) { + synchronized (mLocationListeners) { + int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); + if (uid >= 0) { + ArrayList removedRecs = null; + for (ArrayList i : mRecordsByProvider.values()) { + for (int j=i.size()-1; j>=0; j--) { + UpdateRecord ur = i.get(j); + if (ur.mReceiver.isPendingIntent() && ur.mUid == uid) { + if (removedRecs == null) { + removedRecs = new ArrayList(); + } + if (!removedRecs.contains(ur.mReceiver)) { + removedRecs.add(ur.mReceiver); + } + } + } + } + ArrayList removedAlerts = null; + for (ProximityAlert i : mProximityAlerts.values()) { + if (i.mUid == uid) { + if (removedAlerts == null) { + removedAlerts = new ArrayList(); + } + if (!removedAlerts.contains(i)) { + removedAlerts.add(i); + } + } + } + if (removedRecs != null) { + for (int i=removedRecs.size()-1; i>=0; i--) { + removeUpdatesLocked(removedRecs.get(i)); + } + } + if (removedAlerts != null) { + for (int i=removedAlerts.size()-1; i>=0; i--) { + removeProximityAlertLocked(removedAlerts.get(i).mIntent); + } + } + } + } } } } @@ -1666,25 +2000,31 @@ public class LocationManagerService extends ILocationManager.Stub { } // Notify provider and collector of Wifi scan results - mCollector.updateWifiScanResults(wifiScanResults); - if (mNetworkLocationProvider != null) { - mNetworkLocationProvider.updateWifiScanResults(wifiScanResults); + synchronized (mLocationListeners) { + if (mCollector != null) { + mCollector.updateWifiScanResults(wifiScanResults); + } + if (mNetworkLocationInterface != null) { + mNetworkLocationInterface.updateWifiScanResults(wifiScanResults); + } } } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { - int networkState = LocationProvider.TEMPORARILY_UNAVAILABLE; - boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (!noConnectivity) { - networkState = LocationProvider.AVAILABLE; + mNetworkState = LocationProvider.AVAILABLE; + } else { + mNetworkState = LocationProvider.TEMPORARILY_UNAVAILABLE; } // Notify location providers of current network state - List providers = LocationProviderImpl.getProviders(); - for (LocationProviderImpl provider : providers) { - if (provider.requiresNetwork()) { - provider.updateNetworkState(networkState); + synchronized (mLocationListeners) { + List providers = LocationProviderImpl.getProviders(); + for (LocationProviderImpl provider : providers) { + if (provider.requiresNetwork()) { + provider.updateNetworkState(mNetworkState); + } } } @@ -1692,18 +2032,19 @@ public class LocationManagerService extends ILocationManager.Stub { int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN); - boolean enabled; if (state == WifiManager.WIFI_STATE_ENABLED) { - enabled = true; + mWifiEnabled = true; } else if (state == WifiManager.WIFI_STATE_DISABLED) { - enabled = false; + mWifiEnabled = false; } else { return; } // Notify network provider of current wifi enabled state - if (mNetworkLocationProvider != null) { - mNetworkLocationProvider.updateWifiEnabledState(enabled); + synchronized (mLocationListeners) { + if (mNetworkLocationInterface != null) { + mNetworkLocationInterface.updateWifiEnabledState(mWifiEnabled); + } } } else if (action.equals(GpsLocationProvider.GPS_ENABLED_CHANGE_ACTION)) { @@ -1711,9 +2052,16 @@ public class LocationManagerService extends ILocationManager.Stub { final boolean enabled = intent.getBooleanExtra(GpsLocationProvider.EXTRA_ENABLED, false); - if (!enabled) { - // When GPS is disabled, we are OK to release wake-lock - mWakeLockGpsReceived = true; + synchronized (mLocationListeners) { + if (enabled) { + updateReportedGpsLocked(); + mGpsNavigating = true; + } else { + reportStopGpsLocked(); + mGpsNavigating = false; + // When GPS is disabled, we are OK to release wake-lock + mWakeLockGpsReceived = true; + } } } @@ -1722,7 +2070,7 @@ public class LocationManagerService extends ILocationManager.Stub { // Wake locks - private void updateWakelockStatus(boolean screenOn) { + private void updateWakelockStatusLocked(boolean screenOn) { log("updateWakelockStatus(): " + screenOn); boolean needsLock = false; @@ -1737,11 +2085,10 @@ public class LocationManagerService extends ILocationManager.Stub { needsLock = true; minTime = Math.min(mGpsLocationProvider.getMinTime(), minTime); if (screenOn) { - startGps(); + startGpsLocked(); } else if (mScreenOn && !screenOn) { - // We just turned the screen off so stop navigating - stopGps(); + stopGpsLocked(); } } @@ -1767,13 +2114,13 @@ public class LocationManagerService extends ILocationManager.Stub { // Clear out existing wakelocks mLocationHandler.removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK); mLocationHandler.removeMessages(MESSAGE_RELEASE_WAKE_LOCK); - releaseWakeLock(); + releaseWakeLockLocked(); } } - private void acquireWakeLock() { + private void acquireWakeLockLocked() { try { - acquireWakeLockX(); + acquireWakeLockXLocked(); } catch (Exception e) { // This is to catch a runtime exception thrown when we try to release an // already released lock. @@ -1781,7 +2128,7 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void acquireWakeLockX() { + private void acquireWakeLockXLocked() { if (mWakeLock.isHeld()) { log("Must release wakelock before acquiring"); mWakeLockAcquireTime = 0; @@ -1808,7 +2155,7 @@ public class LocationManagerService extends ILocationManager.Stub { log("Acquired wakelock"); // Start the gps provider - startGps(); + startGpsLocked(); // Acquire cell lock if (mCellWakeLockAcquired) { @@ -1821,12 +2168,12 @@ public class LocationManagerService extends ILocationManager.Stub { } // Notify NetworkLocationProvider - if (mNetworkLocationProvider != null) { - mNetworkLocationProvider.updateCellLockStatus(mCellWakeLockAcquired); + if (mNetworkLocationInterface != null) { + mNetworkLocationInterface.updateCellLockStatus(mCellWakeLockAcquired); } // Acquire wifi lock - WifiManager.WifiLock wifiLock = getWifiWakelock(); + WifiManager.WifiLock wifiLock = getWifiWakelockLocked(); if (wifiLock != null) { if (mWifiWakeLockAcquired) { // Lock is already acquired @@ -1840,7 +2187,86 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void startGps() { + private boolean reportGpsUidLocked(int curSeq, int nextSeq, int uid) { + int seq = mReportedGpsUids.get(uid, -1); + if (seq == curSeq) { + // Already reported; propagate to next sequence. + mReportedGpsUids.put(uid, nextSeq); + return true; + } else if (seq != nextSeq) { + try { + // New UID; report it. + mBatteryStats.noteStartGps(uid); + mReportedGpsUids.put(uid, nextSeq); + return true; + } catch (RemoteException e) { + } + } + return false; + } + + private void updateReportedGpsLocked() { + if (mGpsLocationProvider == null) { + return; + } + + final String name = mGpsLocationProvider.getName(); + final int curSeq = mReportedGpsSeq; + final int nextSeq = (curSeq+1) >= 0 ? (curSeq+1) : 0; + mReportedGpsSeq = nextSeq; + + ArrayList urs = mRecordsByProvider.get(name); + int num = 0; + final int N = urs.size(); + for (int i=0; i=0; i--) { + if (mReportedGpsUids.valueAt(i) != nextSeq) { + try { + mBatteryStats.noteStopGps(mReportedGpsUids.keyAt(i)); + } catch (RemoteException e) { + } + mReportedGpsUids.removeAt(i); + } + } + } + } + + private void reportStopGpsLocked() { + int curSeq = mReportedGpsSeq; + for (int i=mReportedGpsUids.size()-1; i>=0; i--) { + if (mReportedGpsUids.valueAt(i) == curSeq) { + try { + mBatteryStats.noteStopGps(mReportedGpsUids.keyAt(i)); + } catch (RemoteException e) { + } + } + } + curSeq++; + if (curSeq < 0) curSeq = 0; + mReportedGpsSeq = curSeq; + mReportedGpsUids.clear(); + } + + private void startGpsLocked() { boolean gpsActive = (mGpsLocationProvider != null) && mGpsLocationProvider.isLocationTracking(); if (gpsActive) { @@ -1848,7 +2274,7 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void stopGps() { + private void stopGpsLocked() { boolean gpsActive = mGpsLocationProvider != null && mGpsLocationProvider.isLocationTracking(); if (gpsActive) { @@ -1856,9 +2282,9 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void releaseWakeLock() { + private void releaseWakeLockLocked() { try { - releaseWakeLockX(); + releaseWakeLockXLocked(); } catch (Exception e) { // This is to catch a runtime exception thrown when we try to release an // already released lock. @@ -1866,9 +2292,9 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void releaseWakeLockX() { + private void releaseWakeLockXLocked() { // Release wifi lock - WifiManager.WifiLock wifiLock = getWifiWakelock(); + WifiManager.WifiLock wifiLock = getWifiWakelockLocked(); if (wifiLock != null) { if (mWifiWakeLockAcquired) { wifiLock.release(); @@ -1877,9 +2303,8 @@ public class LocationManagerService extends ILocationManager.Stub { } if (!mScreenOn) { - // Stop the gps - stopGps(); + stopGpsLocked(); } // Release cell lock @@ -1889,8 +2314,8 @@ public class LocationManagerService extends ILocationManager.Stub { } // Notify NetworkLocationProvider - if (mNetworkLocationProvider != null) { - mNetworkLocationProvider.updateCellLockStatus(mCellWakeLockAcquired); + if (mNetworkLocationInterface != null) { + mNetworkLocationInterface.updateCellLockStatus(mCellWakeLockAcquired); } // Release wake lock @@ -1907,15 +2332,13 @@ public class LocationManagerService extends ILocationManager.Stub { public String getFromLocation(double latitude, double longitude, int maxResults, String language, String country, String variant, String appName, List

              addrs) { - try { - Locale locale = new Locale(language, country, variant); - mMasfClient.reverseGeocode(locale, appName, latitude, longitude, maxResults, addrs); - return null; - } catch(IOException e) { - return e.getMessage(); - } catch(Exception e) { - Log.e(TAG, "getFromLocation got exception:", e); - return null; + synchronized (mLocationListeners) { + if (mNetworkLocationInterface != null) { + return mNetworkLocationInterface.getFromLocation(latitude, longitude, maxResults, + language, country, variant, appName, addrs); + } else { + return null; + } } } @@ -1923,18 +2346,14 @@ public class LocationManagerService extends ILocationManager.Stub { double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude, int maxResults, String language, String country, String variant, String appName, List
              addrs) { - - try { - Locale locale = new Locale(language, country, variant); - mMasfClient.forwardGeocode(locale, appName, locationName, - lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude, upperRightLongitude, - maxResults, addrs); - return null; - } catch(IOException e) { - return e.getMessage(); - } catch(Exception e) { - Log.e(TAG, "getFromLocationName got exception:", e); - return null; + synchronized (mLocationListeners) { + if (mNetworkLocationInterface != null) { + return mNetworkLocationInterface.getFromLocationName(locationName, lowerLeftLatitude, + lowerLeftLongitude, upperRightLatitude, upperRightLongitude, maxResults, + language, country, variant, appName, addrs); + } else { + return null; + } } } @@ -1970,43 +2389,63 @@ public class LocationManagerService extends ILocationManager.Stub { @Override public void disable() { String name = getName(); - mEnabledProviders.remove(name); - mDisabledProviders.add(name); + // We shouldn't normally need to lock, since this should only be called + // by the service with the lock held, but let's be paranid. + synchronized (mLocationListeners) { + mEnabledProviders.remove(name); + mDisabledProviders.add(name); + } } @Override public void enable() { String name = getName(); - mEnabledProviders.add(name); - mDisabledProviders.remove(name); + // We shouldn't normally need to lock, since this should only be called + // by the service with the lock held, but let's be paranid. + synchronized (mLocationListeners) { + mEnabledProviders.add(name); + mDisabledProviders.remove(name); + } } @Override public boolean getLocation(Location l) { - Location loc = mMockProviderLocation.get(getName()); - if (loc == null) { - return false; + // We shouldn't normally need to lock, since this should only be called + // by the service with the lock held, but let's be paranid. + synchronized (mLocationListeners) { + Location loc = mMockProviderLocation.get(getName()); + if (loc == null) { + return false; + } + l.set(loc); + return true; } - l.set(loc); - return true; } @Override public int getStatus(Bundle extras) { - String name = getName(); - Integer s = mMockProviderStatus.get(name); - int status = (s == null) ? AVAILABLE : s.intValue(); - Bundle newExtras = mMockProviderStatusExtras.get(name); - if (newExtras != null) { - extras.clear(); - extras.putAll(newExtras); + // We shouldn't normally need to lock, since this should only be called + // by the service with the lock held, but let's be paranid. + synchronized (mLocationListeners) { + String name = getName(); + Integer s = mMockProviderStatus.get(name); + int status = (s == null) ? AVAILABLE : s.intValue(); + Bundle newExtras = mMockProviderStatusExtras.get(name); + if (newExtras != null) { + extras.clear(); + extras.putAll(newExtras); + } + return status; } - return status; } @Override public boolean isEnabled() { - return mEnabledProviders.contains(getName()); + // We shouldn't normally need to lock, since this should only be called + // by the service with the lock held, but let's be paranid. + synchronized (mLocationListeners) { + return mEnabledProviders.contains(getName()); + } } @Override @@ -2055,14 +2494,9 @@ public class LocationManagerService extends ILocationManager.Stub { } } - private void checkMockPermissions() { - boolean allowMocks = false; - try { - allowMocks = Settings.Secure.getInt(mContext.getContentResolver(), - Settings.Secure.ALLOW_MOCK_LOCATION) == 1; - } catch (SettingNotFoundException e) { - // Do nothing - } + private void checkMockPermissionsSafe() { + boolean allowMocks = Settings.Secure.getInt(mContext.getContentResolver(), + Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 1; if (!allowMocks) { throw new SecurityException("Requires ACCESS_MOCK_LOCATION secure setting"); } @@ -2076,87 +2510,103 @@ public class LocationManagerService extends ILocationManager.Stub { public void addTestProvider(String name, boolean requiresNetwork, boolean requiresSatellite, boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude, boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy) { - checkMockPermissions(); - - MockProvider provider = new MockProvider(name, requiresNetwork, requiresSatellite, - requiresCell, hasMonetaryCost, supportsAltitude, - supportsSpeed, supportsBearing, powerRequirement, accuracy); - if (LocationProviderImpl.getProvider(name) != null) { - throw new IllegalArgumentException("Provider \"" + name + "\" already exists"); + checkMockPermissionsSafe(); + + synchronized (mLocationListeners) { + MockProvider provider = new MockProvider(name, requiresNetwork, requiresSatellite, + requiresCell, hasMonetaryCost, supportsAltitude, + supportsSpeed, supportsBearing, powerRequirement, accuracy); + if (LocationProviderImpl.getProvider(name) != null) { + throw new IllegalArgumentException("Provider \"" + name + "\" already exists"); + } + LocationProviderImpl.addProvider(provider); + updateProvidersLocked(); } - LocationProviderImpl.addProvider(provider); - updateProviders(); } public void removeTestProvider(String provider) { - checkMockPermissions(); - LocationProviderImpl p = LocationProviderImpl.getProvider(provider); - if (p == null) { - throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + checkMockPermissionsSafe(); + synchronized (mLocationListeners) { + LocationProviderImpl p = LocationProviderImpl.getProvider(provider); + if (p == null) { + throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + } + LocationProviderImpl.removeProvider(p); + updateProvidersLocked(); } - LocationProviderImpl.removeProvider(p); - updateProviders(); } public void setTestProviderLocation(String provider, Location loc) { - checkMockPermissions(); - if (LocationProviderImpl.getProvider(provider) == null) { - throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + checkMockPermissionsSafe(); + synchronized (mLocationListeners) { + if (LocationProviderImpl.getProvider(provider) == null) { + throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + } + mMockProviderLocation.put(provider, loc); } - mMockProviderLocation.put(provider, loc); } public void clearTestProviderLocation(String provider) { - checkMockPermissions(); - if (LocationProviderImpl.getProvider(provider) == null) { - throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + checkMockPermissionsSafe(); + synchronized (mLocationListeners) { + if (LocationProviderImpl.getProvider(provider) == null) { + throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + } + mMockProviderLocation.remove(provider); } - mMockProviderLocation.remove(provider); } public void setTestProviderEnabled(String provider, boolean enabled) { - checkMockPermissions(); - if (LocationProviderImpl.getProvider(provider) == null) { - throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); - } - if (enabled) { - mEnabledProviders.add(provider); - mDisabledProviders.remove(provider); - } else { - mEnabledProviders.remove(provider); - mDisabledProviders.add(provider); + checkMockPermissionsSafe(); + synchronized (mLocationListeners) { + if (LocationProviderImpl.getProvider(provider) == null) { + throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + } + if (enabled) { + mEnabledProviders.add(provider); + mDisabledProviders.remove(provider); + } else { + mEnabledProviders.remove(provider); + mDisabledProviders.add(provider); + } + updateProvidersLocked(); } - updateProviders(); } public void clearTestProviderEnabled(String provider) { - checkMockPermissions(); - if (LocationProviderImpl.getProvider(provider) == null) { - throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + checkMockPermissionsSafe(); + synchronized (mLocationListeners) { + if (LocationProviderImpl.getProvider(provider) == null) { + throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + } + mEnabledProviders.remove(provider); + mDisabledProviders.remove(provider); + updateProvidersLocked(); } - mEnabledProviders.remove(provider); - mDisabledProviders.remove(provider); - updateProviders(); } public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) { - checkMockPermissions(); - if (LocationProviderImpl.getProvider(provider) == null) { - throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + checkMockPermissionsSafe(); + synchronized (mLocationListeners) { + if (LocationProviderImpl.getProvider(provider) == null) { + throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + } + mMockProviderStatus.put(provider, new Integer(status)); + mMockProviderStatusExtras.put(provider, extras); + mMockProviderStatusUpdateTime.put(provider, new Long(updateTime)); } - mMockProviderStatus.put(provider, new Integer(status)); - mMockProviderStatusExtras.put(provider, extras); - mMockProviderStatusUpdateTime.put(provider, new Long(updateTime)); } public void clearTestProviderStatus(String provider) { - checkMockPermissions(); - if (LocationProviderImpl.getProvider(provider) == null) { - throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + checkMockPermissionsSafe(); + synchronized (mLocationListeners) { + if (LocationProviderImpl.getProvider(provider) == null) { + throw new IllegalArgumentException("Provider \"" + provider + "\" unknown"); + } + mMockProviderStatus.remove(provider); + mMockProviderStatusExtras.remove(provider); + mMockProviderStatusUpdateTime.remove(provider); } - mMockProviderStatus.remove(provider); - mMockProviderStatusExtras.remove(provider); - mMockProviderStatusUpdateTime.remove(provider); } private void log(String log) { @@ -2164,5 +2614,157 @@ public class LocationManagerService extends ILocationManager.Stub { Log.d(TAG, log); } } + + protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) + != PackageManager.PERMISSION_GRANTED) { + pw.println("Permission Denial: can't dump AlarmManager from from pid=" + + Binder.getCallingPid() + + ", uid=" + Binder.getCallingUid()); + return; + } + + synchronized (mLocationListeners) { + pw.println("Current Location Manager state:"); + pw.println(" sProvidersLoaded=" + sProvidersLoaded); + pw.println(" mGpsLocationProvider=" + mGpsLocationProvider); + pw.println(" mGpsNavigating=" + mGpsNavigating); + pw.println(" mNetworkLocationProvider=" + mNetworkLocationProvider); + pw.println(" mNetworkLocationInterface=" + mNetworkLocationInterface); + pw.println(" mLastSignalStrength=" + mLastSignalStrength + + " mLastRadioType=" + mLastRadioType); + pw.println(" mCellLocationUpdater=" + mCellLocationUpdater); + pw.println(" mLastCellState=" + mLastCellState); + pw.println(" mCollector=" + mCollector); + pw.println(" mAlarmInterval=" + mAlarmInterval + + " mScreenOn=" + mScreenOn + + " mWakeLockAcquireTime=" + mWakeLockAcquireTime); + pw.println(" mWakeLockGpsReceived=" + mWakeLockGpsReceived + + " mWakeLockNetworkReceived=" + mWakeLockNetworkReceived); + pw.println(" mWifiWakeLockAcquired=" + mWifiWakeLockAcquired + + " mCellWakeLockAcquired=" + mCellWakeLockAcquired); + pw.println(" Listeners:"); + int N = mListeners.size(); + for (int i=0; i> i + : mLocationListeners.entrySet()) { + pw.println(" " + i.getKey() + ":"); + for (Map.Entry j : i.getValue().entrySet()) { + pw.println(" " + j.getKey() + ":"); + j.getValue().dump(pw, " "); + } + } + pw.println(" Last Fix Broadcasts:"); + for (Map.Entry> i + : mLastFixBroadcast.entrySet()) { + pw.println(" " + i.getKey() + ":"); + for (Map.Entry j : i.getValue().entrySet()) { + pw.println(" " + j.getKey() + ":"); + j.getValue().dump(new PrintWriterPrinter(pw), " "); + } + } + pw.println(" Last Status Broadcasts:"); + for (Map.Entry> i + : mLastStatusBroadcast.entrySet()) { + pw.println(" " + i.getKey() + ":"); + for (Map.Entry j : i.getValue().entrySet()) { + pw.println(" " + j.getKey() + " -> 0x" + + Long.toHexString(j.getValue())); + } + } + pw.println(" Records by Provider:"); + for (Map.Entry> i + : mRecordsByProvider.entrySet()) { + pw.println(" " + i.getKey() + ":"); + for (UpdateRecord j : i.getValue()) { + pw.println(" " + j + ":"); + j.dump(pw, " "); + } + } + pw.println(" Locations by Provider:"); + for (Map.Entry i + : mLocationsByProvider.entrySet()) { + pw.println(" " + i.getKey() + ":"); + i.getValue().dump(new PrintWriterPrinter(pw), " "); + } + pw.println(" Last Known Locations:"); + for (Map.Entry i + : mLastKnownLocation.entrySet()) { + pw.println(" " + i.getKey() + ":"); + i.getValue().dump(new PrintWriterPrinter(pw), " "); + } + if (mProximityAlerts.size() > 0) { + pw.println(" Proximity Alerts:"); + for (Map.Entry i + : mProximityAlerts.entrySet()) { + pw.println(" " + i.getKey() + ":"); + i.getValue().dump(pw, " "); + } + } + if (mProximitiesEntered.size() > 0) { + pw.println(" Proximities Entered:"); + for (ProximityAlert i : mProximitiesEntered) { + pw.println(" " + i + ":"); + i.dump(pw, " "); + } + } + pw.println(" mProximityListener=" + mProximityListener); + if (mEnabledProviders.size() > 0) { + pw.println(" Enabled Providers:"); + for (String i : mEnabledProviders) { + pw.println(" " + i); + } + + } + if (mDisabledProviders.size() > 0) { + pw.println(" Disabled Providers:"); + for (String i : mDisabledProviders) { + pw.println(" " + i); + } + + } + if (mMockProviders.size() > 0) { + pw.println(" Mock Providers:"); + for (Map.Entry i : mMockProviders.entrySet()) { + pw.println(" " + i.getKey() + " -> " + i.getValue()); + } + } + if (mMockProviderLocation.size() > 0) { + pw.println(" Mock Provider Location:"); + for (Map.Entry i : mMockProviderLocation.entrySet()) { + pw.println(" " + i.getKey() + ":"); + i.getValue().dump(new PrintWriterPrinter(pw), " "); + } + } + if (mMockProviderStatus.size() > 0) { + pw.println(" Mock Provider Status:"); + for (Map.Entry i : mMockProviderStatus.entrySet()) { + pw.println(" " + i.getKey() + " -> 0x" + + Integer.toHexString(i.getValue())); + } + } + if (mMockProviderStatusExtras.size() > 0) { + pw.println(" Mock Provider Status Extras:"); + for (Map.Entry i : mMockProviderStatusExtras.entrySet()) { + pw.println(" " + i.getKey() + " -> " + i.getValue()); + } + } + if (mMockProviderStatusUpdateTime.size() > 0) { + pw.println(" Mock Provider Status Update Time:"); + for (Map.Entry i : mMockProviderStatusUpdateTime.entrySet()) { + pw.println(" " + i.getKey() + " -> " + i.getValue()); + } + } + pw.println(" Reported GPS UIDs @ seq " + mReportedGpsSeq + ":"); + N = mReportedGpsUids.size(); + for (int i=0; i 0 ? event.substring(colonIndex + 1) : null); - if (event.equals(MOUNTD_UMS_ENABLED)) { + if (event.equals(VOLD_EVT_UMS_ENABLED)) { mUmsEnabled = true; - } else if (event.equals(MOUNTD_UMS_DISABLED)) { + } else if (event.equals(VOLD_EVT_UMS_DISABLED)) { mUmsEnabled = false; - } else if (event.equals(MOUNTD_UMS_CONNECTED)) { + } else if (event.equals(VOLD_EVT_UMS_CONNECTED)) { mUmsConnected = true; mService.notifyUmsConnected(); - } else if (event.equals(MOUNTD_UMS_DISCONNECTED)) { + } else if (event.equals(VOLD_EVT_UMS_DISCONNECTED)) { mUmsConnected = false; mService.notifyUmsDisconnected(); - } else if (event.startsWith(MOUNTD_MEDIA_REMOVED)) { + } else if (event.startsWith(VOLD_EVT_NOMEDIA)) { mService.notifyMediaRemoved(path); - } else if (event.startsWith(MOUNTD_MEDIA_UNMOUNTED)) { + } else if (event.startsWith(VOLD_EVT_UNMOUNTED)) { mService.notifyMediaUnmounted(path); - } else if (event.startsWith(MOUNTD_MEDIA_MOUNTED)) { + } else if (event.startsWith(VOLD_EVT_CHECKING)) { + mService.notifyMediaChecking(path); + } else if (event.startsWith(VOLD_EVT_NOFS)) { + mService.notifyMediaNoFs(path); + } else if (event.startsWith(VOLD_EVT_MOUNTED)) { mService.notifyMediaMounted(path, false); - } else if (event.startsWith(MOUNTD_MEDIA_MOUNTED_READ_ONLY)) { + } else if (event.startsWith(VOLD_EVT_MOUNTED_RO)) { mService.notifyMediaMounted(path, true); - } else if (event.startsWith(MOUNTD_MEDIA_SHARED)) { + } else if (event.startsWith(VOLD_EVT_UMS)) { mService.notifyMediaShared(path); - } else if (event.startsWith(MOUNTD_MEDIA_BAD_REMOVAL)) { + } else if (event.startsWith(VOLD_EVT_BAD_REMOVAL)) { mService.notifyMediaBadRemoval(path); // also send media eject intent, to notify apps to close any open // files on the media. mService.notifyMediaEject(path); - } else if (event.startsWith(MOUNTD_MEDIA_UNMOUNTABLE)) { + } else if (event.startsWith(VOLD_EVT_DAMAGED)) { mService.notifyMediaUnmountable(path); - } else if (event.startsWith(MOUNTD_REQUEST_EJECT)) { + } else if (event.startsWith(VOLD_EVT_EJECTING)) { mService.notifyMediaEject(path); } } @@ -156,7 +164,7 @@ final class MountListener implements Runnable { private void writeCommand2(String command, String argument) { synchronized (this) { if (mOutputStream == null) { - Log.e(TAG, "No connection to mountd", new IllegalStateException()); + Log.e(TAG, "No connection to vold", new IllegalStateException()); } else { StringBuilder builder = new StringBuilder(command); if (argument != null) { @@ -183,7 +191,7 @@ final class MountListener implements Runnable { try { socket = new LocalSocket(); - LocalSocketAddress address = new LocalSocketAddress(MOUNTD_SOCKET, + LocalSocketAddress address = new LocalSocketAddress(VOLD_SOCKET, LocalSocketAddress.Namespace.RESERVED); socket.connect(address); @@ -193,7 +201,7 @@ final class MountListener implements Runnable { byte[] buffer = new byte[100]; - writeCommand(MOUNTD_SEND_STATUS); + writeCommand(VOLD_CMD_SEND_UMS_STATUS); while (true) { int count = inputStream.read(buffer); @@ -242,7 +250,7 @@ final class MountListener implements Runnable { * create tons of throwaway LocalSockets, making * system_server GC constantly. */ - Log.e(TAG, "Failed to connect to mountd", new IllegalStateException()); + Log.e(TAG, "Failed to connect to vold", new IllegalStateException()); SystemClock.sleep(2000); } @@ -283,7 +291,7 @@ final class MountListener implements Runnable { * @param enable true to enable USB mass storage support */ void setMassStorageEnabled(boolean enable) { - writeCommand(enable ? MOUNTD_ENABLE_UMS : MOUNTD_DISABLE_UMS); + writeCommand(enable ? VOLD_CMD_ENABLE_UMS : VOLD_CMD_DISABLE_UMS); } /** @@ -297,14 +305,20 @@ final class MountListener implements Runnable { * Mount media at given mount point. */ public void mountMedia(String mountPoint) { - writeCommand2(MOUNTD_MOUNT_MEDIA, mountPoint); + writeCommand2(VOLD_CMD_MOUNT_VOLUME, mountPoint); } /** * Unmount media at given mount point. */ public void ejectMedia(String mountPoint) { - writeCommand2(MOUNTD_EJECT_MEDIA, mountPoint); + writeCommand2(VOLD_CMD_EJECT_MEDIA, mountPoint); } -} + /** + * Format media at given mount point. + */ + public void formatMedia(String mountPoint) { + writeCommand2(VOLD_CMD_FORMAT_MEDIA, mountPoint); + } +} diff --git a/services/java/com/android/server/MountService.java b/services/java/com/android/server/MountService.java index 002ebeda208a4624f93ff65cd1c041fdafd9fb57..f81c5198d0c7a2791b0ba0af1e43ab27b68d9384 100644 --- a/services/java/com/android/server/MountService.java +++ b/services/java/com/android/server/MountService.java @@ -19,15 +19,19 @@ package com.android.server; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; +import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.res.Resources; import android.net.Uri; import android.os.IMountService; import android.os.Environment; import android.os.RemoteException; +import android.os.SystemProperties; import android.os.UEventObserver; +import android.text.TextUtils; import android.util.Log; import java.io.File; @@ -52,24 +56,34 @@ class MountService extends IMountService.Stub { private MountListener mListener; /** - * The notification that is shown when USB is connected. It leads the user - * to a dialog to enable mass storage mode. + * The notification that is shown when a USB mass storage host + * is connected. *

              - * This is lazily created, so use {@link #getUsbStorageNotification()}. + * This is lazily created, so use {@link #setUsbStorageNotification()}. */ private Notification mUsbStorageNotification; - private class SdDoorListener extends UEventObserver { - static final String SD_DOOR_UEVENT_MATCH = "DEVPATH=/devices/virtual/switch/sd-door"; - static final String SD_DOOR_SWITCH_NAME = "sd-door"; - public void onUEvent(UEvent event) { - if (SD_DOOR_SWITCH_NAME.equals(event.get("SWITCH_NAME"))) { - sdDoorStateChanged(event.get("SWITCH_STATE")); - } - } - }; + /** + * The notification that is shown when the following media events occur: + * - Media is being checked + * - Media is blank (or unknown filesystem) + * - Media is corrupt + * - Media is safe to unmount + * - Media is missing + *

              + * This is lazily created, so use {@link #setMediaStorageNotification()}. + */ + private Notification mMediaStorageNotification; + private boolean mShowSafeUnmountNotificationWhenUnmounted; + + private boolean mPlaySounds; + + private boolean mMounted; + + private boolean mAutoStartUms; + /** * Constructs a new MountService instance * @@ -77,13 +91,30 @@ class MountService extends IMountService.Stub { */ public MountService(Context context) { mContext = context; + + // Register a BOOT_COMPLETED handler so that we can start + // MountListener. We defer the startup so that we don't + // start processing events before we ought-to + mContext.registerReceiver(mBroadcastReceiver, + new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null); + mListener = new MountListener(this); - Thread thread = new Thread(mListener, MountListener.class.getName()); - thread.start(); - SdDoorListener sdDoorListener = new SdDoorListener(); - sdDoorListener.startObserving(SdDoorListener.SD_DOOR_UEVENT_MATCH); + mShowSafeUnmountNotificationWhenUnmounted = false; + + mPlaySounds = SystemProperties.get("persist.service.mount.playsnd", "1").equals("1"); + + mAutoStartUms = SystemProperties.get("persist.service.mount.umsauto", "0").equals("1"); } + BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { + Thread thread = new Thread(mListener, MountListener.class.getName()); + thread.start(); + } + } + }; + /** * @return true if USB mass storage support is enabled. */ @@ -129,19 +160,119 @@ class MountService extends IMountService.Stub { throw new SecurityException("Requires MOUNT_UNMOUNT_FILESYSTEMS permission"); } + // Set a flag so that when we get the unmounted event, we know + // to display the notification + mShowSafeUnmountNotificationWhenUnmounted = true; + // tell mountd to unmount the media mListener.ejectMedia(mountPath); } + /** + * Attempt to format external media + */ + public void formatMedia(String formatPath) throws RemoteException { + if (mContext.checkCallingOrSelfPermission( + android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS) + != PackageManager.PERMISSION_GRANTED) { + throw new SecurityException("Requires MOUNT_FORMAT_FILESYSTEMS permission"); + } + + mListener.formatMedia(formatPath); + } + + /** + * Returns true if we're playing media notification sounds. + */ + public boolean getPlayNotificationSounds() { + return mPlaySounds; + } + + /** + * Set whether or not we're playing media notification sounds. + */ + public void setPlayNotificationSounds(boolean enabled) { + if (mContext.checkCallingOrSelfPermission( + android.Manifest.permission.WRITE_SETTINGS) + != PackageManager.PERMISSION_GRANTED) { + throw new SecurityException("Requires WRITE_SETTINGS permission"); + } + mPlaySounds = enabled; + SystemProperties.set("persist.service.mount.playsnd", (enabled ? "1" : "0")); + } + + /** + * Returns true if we auto-start UMS on cable insertion. + */ + public boolean getAutoStartUms() { + return mAutoStartUms; + } + + /** + * Set whether or not we're playing media notification sounds. + */ + public void setAutoStartUms(boolean enabled) { + if (mContext.checkCallingOrSelfPermission( + android.Manifest.permission.WRITE_SETTINGS) + != PackageManager.PERMISSION_GRANTED) { + throw new SecurityException("Requires WRITE_SETTINGS permission"); + } + mAutoStartUms = enabled; + SystemProperties.set("persist.service.mount.umsauto", (enabled ? "1" : "0")); + } + + /** + * Update the state of the USB mass storage notification + */ + void updateUsbMassStorageNotification(boolean suppressIfConnected, boolean sound) { + + try { + + if (getMassStorageConnected() && !suppressIfConnected) { + Intent intent = new Intent(); + intent.setClass(mContext, com.android.internal.app.UsbStorageActivity.class); + PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0); + setUsbStorageNotification( + com.android.internal.R.string.usb_storage_notification_title, + com.android.internal.R.string.usb_storage_notification_message, + com.android.internal.R.drawable.stat_sys_data_usb, + sound, true, pi); + } else { + setUsbStorageNotification(0, 0, 0, false, false, null); + } + } catch (RemoteException e) { + // Nothing to do + } + } + + void handlePossibleExplicitUnmountBroadcast(String path) { + if (mMounted) { + mMounted = false; + Intent intent = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, + Uri.parse("file://" + path)); + mContext.sendBroadcast(intent); + } + } + /** * Broadcasts the USB mass storage connected event to all clients. */ void notifyUmsConnected() { String storageState = Environment.getExternalStorageState(); if (!storageState.equals(Environment.MEDIA_REMOVED) && - !storageState.equals(Environment.MEDIA_BAD_REMOVAL)) { - setUsbStorageNotificationVisibility(true); + !storageState.equals(Environment.MEDIA_BAD_REMOVAL) && + !storageState.equals(Environment.MEDIA_CHECKING)) { + + if (mAutoStartUms) { + try { + setMassStorageEnabled(true); + } catch (RemoteException e) { + } + } else { + updateUsbMassStorageNotification(false, true); + } } + Intent intent = new Intent(Intent.ACTION_UMS_CONNECTED); mContext.sendBroadcast(intent); } @@ -150,7 +281,7 @@ class MountService extends IMountService.Stub { * Broadcasts the USB mass storage disconnected event to all clients. */ void notifyUmsDisconnected() { - setUsbStorageNotificationVisibility(false); + updateUsbMassStorageNotification(false, false); Intent intent = new Intent(Intent.ACTION_UMS_DISCONNECTED); mContext.sendBroadcast(intent); } @@ -159,6 +290,15 @@ class MountService extends IMountService.Stub { * Broadcasts the media removed event to all clients. */ void notifyMediaRemoved(String path) { + updateUsbMassStorageNotification(true, false); + + setMediaStorageNotification( + com.android.internal.R.string.ext_media_nomedia_notification_title, + com.android.internal.R.string.ext_media_nomedia_notification_message, + com.android.internal.R.drawable.stat_sys_no_sim, + true, false, null); + handlePossibleExplicitUnmountBroadcast(path); + Intent intent = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path)); mContext.sendBroadcast(intent); @@ -168,18 +308,68 @@ class MountService extends IMountService.Stub { * Broadcasts the media unmounted event to all clients. */ void notifyMediaUnmounted(String path) { + if (mShowSafeUnmountNotificationWhenUnmounted) { + setMediaStorageNotification( + com.android.internal.R.string.ext_media_safe_unmount_notification_title, + com.android.internal.R.string.ext_media_safe_unmount_notification_message, + com.android.internal.R.drawable.stat_notify_sim_toolkit, + true, true, null); + mShowSafeUnmountNotificationWhenUnmounted = false; + } else { + setMediaStorageNotification(0, 0, 0, false, false, null); + } + updateUsbMassStorageNotification(false, false); + Intent intent = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path)); mContext.sendBroadcast(intent); } + /** + * Broadcasts the media checking event to all clients. + */ + void notifyMediaChecking(String path) { + setMediaStorageNotification( + com.android.internal.R.string.ext_media_checking_notification_title, + com.android.internal.R.string.ext_media_checking_notification_message, + com.android.internal.R.drawable.stat_notify_sim_toolkit, + true, false, null); + + updateUsbMassStorageNotification(true, false); + Intent intent = new Intent(Intent.ACTION_MEDIA_CHECKING, + Uri.parse("file://" + path)); + mContext.sendBroadcast(intent); + } + + /** + * Broadcasts the media nofs event to all clients. + */ + void notifyMediaNoFs(String path) { + + Intent intent = new Intent(); + intent.setClass(mContext, com.android.internal.app.ExternalMediaFormatActivity.class); + PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0); + + setMediaStorageNotification(com.android.internal.R.string.ext_media_nofs_notification_title, + com.android.internal.R.string.ext_media_nofs_notification_message, + com.android.internal.R.drawable.stat_sys_no_sim, + true, false, pi); + updateUsbMassStorageNotification(false, false); + intent = new Intent(Intent.ACTION_MEDIA_NOFS, + Uri.parse("file://" + path)); + mContext.sendBroadcast(intent); + } + /** * Broadcasts the media mounted event to all clients. */ void notifyMediaMounted(String path, boolean readOnly) { + setMediaStorageNotification(0, 0, 0, false, false, null); + updateUsbMassStorageNotification(false, false); Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path)); intent.putExtra("read-only", readOnly); + mMounted = true; mContext.sendBroadcast(intent); } @@ -187,7 +377,15 @@ class MountService extends IMountService.Stub { * Broadcasts the media shared event to all clients. */ void notifyMediaShared(String path) { - Intent intent = new Intent(Intent.ACTION_MEDIA_SHARED, + Intent intent = new Intent(); + intent.setClass(mContext, com.android.internal.app.UsbStorageStopActivity.class); + PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0); + setUsbStorageNotification(com.android.internal.R.string.usb_storage_stop_notification_title, + com.android.internal.R.string.usb_storage_stop_notification_message, + com.android.internal.R.drawable.stat_sys_warning, + false, true, pi); + handlePossibleExplicitUnmountBroadcast(path); + intent = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path)); mContext.sendBroadcast(intent); } @@ -196,16 +394,39 @@ class MountService extends IMountService.Stub { * Broadcasts the media bad removal event to all clients. */ void notifyMediaBadRemoval(String path) { + updateUsbMassStorageNotification(true, false); + setMediaStorageNotification(com.android.internal.R.string.ext_media_badremoval_notification_title, + com.android.internal.R.string.ext_media_badremoval_notification_message, + com.android.internal.R.drawable.stat_sys_warning, + true, true, null); + + handlePossibleExplicitUnmountBroadcast(path); Intent intent = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path)); mContext.sendBroadcast(intent); + + intent = new Intent(Intent.ACTION_MEDIA_REMOVED, + Uri.parse("file://" + path)); + mContext.sendBroadcast(intent); } /** * Broadcasts the media unmountable event to all clients. */ void notifyMediaUnmountable(String path) { - Intent intent = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, + Intent intent = new Intent(); + intent.setClass(mContext, com.android.internal.app.ExternalMediaFormatActivity.class); + PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0); + + setMediaStorageNotification(com.android.internal.R.string.ext_media_unmountable_notification_title, + com.android.internal.R.string.ext_media_unmountable_notification_message, + com.android.internal.R.drawable.stat_sys_no_sim, + true, false, pi); + updateUsbMassStorageNotification(false, false); + + handlePossibleExplicitUnmountBroadcast(path); + + intent = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path)); mContext.sendBroadcast(intent); } @@ -219,90 +440,132 @@ class MountService extends IMountService.Stub { mContext.sendBroadcast(intent); } - private void sdDoorStateChanged(String doorState) { - File directory = Environment.getExternalStorageDirectory(); - String storageState = Environment.getExternalStorageState(); - - if (directory != null) { - try { - if (doorState.equals("open") && (storageState.equals(Environment.MEDIA_MOUNTED) || - storageState.equals(Environment.MEDIA_MOUNTED_READ_ONLY))) { - // request SD card unmount if SD card door is opened - unmountMedia(directory.getPath()); - } else if (doorState.equals("closed") && storageState.equals(Environment.MEDIA_UNMOUNTED)) { - // attempt to remount SD card - mountMedia(directory.getPath()); - } - } catch (RemoteException e) { - // Nothing to do. - } - } - } - /** - * Sets the visibility of the USB storage notification. This should be - * called when a USB cable is connected and also when it is disconnected. - * - * @param visible Whether to show or hide the notification. + * Sets the USB storage notification. */ - private void setUsbStorageNotificationVisibility(boolean visible) { + private synchronized void setUsbStorageNotification(int titleId, int messageId, int icon, boolean sound, boolean visible, + PendingIntent pi) { + + if (!visible && mUsbStorageNotification == null) { + return; + } + NotificationManager notificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); + if (notificationManager == null) { return; } - - /* - * The convention for notification IDs is to use the icon's resource ID - * when the icon is only used by a single notification type, which is - * the case here. - */ - Notification notification = getUsbStorageNotification(); - final int notificationId = notification.icon; if (visible) { - notificationManager.notify(notificationId, notification); + Resources r = Resources.getSystem(); + CharSequence title = r.getText(titleId); + CharSequence message = r.getText(messageId); + + if (mUsbStorageNotification == null) { + mUsbStorageNotification = new Notification(); + mUsbStorageNotification.icon = icon; + mUsbStorageNotification.when = 0; + } + + if (sound && mPlaySounds) { + mUsbStorageNotification.defaults |= Notification.DEFAULT_SOUND; + } else { + mUsbStorageNotification.defaults &= ~Notification.DEFAULT_SOUND; + } + + mUsbStorageNotification.flags = Notification.FLAG_ONGOING_EVENT; + + mUsbStorageNotification.tickerText = title; + if (pi == null) { + Intent intent = new Intent(); + pi = PendingIntent.getBroadcast(mContext, 0, intent, 0); + } + + mUsbStorageNotification.setLatestEventInfo(mContext, title, message, pi); + } + + final int notificationId = mUsbStorageNotification.icon; + if (visible) { + notificationManager.notify(notificationId, mUsbStorageNotification); } else { notificationManager.cancel(notificationId); } } + private synchronized boolean getMediaStorageNotificationDismissable() { + if ((mMediaStorageNotification != null) && + ((mMediaStorageNotification.flags & Notification.FLAG_AUTO_CANCEL) == + Notification.FLAG_AUTO_CANCEL)) + return true; + + return false; + } + /** - * Gets the USB storage notification. - * - * @return A {@link Notification} that leads to the dialog to enable USB storage. + * Sets the media storage notification. */ - private synchronized Notification getUsbStorageNotification() { - Resources r = Resources.getSystem(); - CharSequence title = - r.getText(com.android.internal.R.string.usb_storage_notification_title); - CharSequence message = - r.getText(com.android.internal.R.string.usb_storage_notification_message); - - if (mUsbStorageNotification == null) { - mUsbStorageNotification = new Notification(); - mUsbStorageNotification.icon = com.android.internal.R.drawable.stat_sys_data_usb; - mUsbStorageNotification.when = 0; - mUsbStorageNotification.flags = Notification.FLAG_AUTO_CANCEL; - mUsbStorageNotification.defaults |= Notification.DEFAULT_SOUND; + private synchronized void setMediaStorageNotification(int titleId, int messageId, int icon, boolean visible, + boolean dismissable, PendingIntent pi) { + + if (!visible && mMediaStorageNotification == null) { + return; } - mUsbStorageNotification.tickerText = title; - mUsbStorageNotification.setLatestEventInfo(mContext, title, message, - getUsbStorageDialogIntent()); + NotificationManager notificationManager = (NotificationManager) mContext + .getSystemService(Context.NOTIFICATION_SERVICE); - return mUsbStorageNotification; - } + if (notificationManager == null) { + return; + } + + if (mMediaStorageNotification != null && visible) { + /* + * Dismiss the previous notification - we're about to + * re-use it. + */ + final int notificationId = mMediaStorageNotification.icon; + notificationManager.cancel(notificationId); + } + + if (visible) { + Resources r = Resources.getSystem(); + CharSequence title = r.getText(titleId); + CharSequence message = r.getText(messageId); + + if (mMediaStorageNotification == null) { + mMediaStorageNotification = new Notification(); + mMediaStorageNotification.when = 0; + } + + if (mPlaySounds) { + mMediaStorageNotification.defaults |= Notification.DEFAULT_SOUND; + } else { + mMediaStorageNotification.defaults &= ~Notification.DEFAULT_SOUND; + } + + if (dismissable) { + mMediaStorageNotification.flags = Notification.FLAG_AUTO_CANCEL; + } else { + mMediaStorageNotification.flags = Notification.FLAG_ONGOING_EVENT; + } + + mMediaStorageNotification.tickerText = title; + if (pi == null) { + Intent intent = new Intent(); + pi = PendingIntent.getBroadcast(mContext, 0, intent, 0); + } + + mMediaStorageNotification.icon = icon; + mMediaStorageNotification.setLatestEventInfo(mContext, title, message, pi); + } - /** - * Creates a pending intent to start the USB storage activity. - * - * @return A {@link PendingIntent} that start the USB storage activity. - */ - private PendingIntent getUsbStorageDialogIntent() { - Intent intent = new Intent(); - intent.setClass(mContext, com.android.internal.app.UsbStorageActivity.class); - return PendingIntent.getActivity(mContext, 0, intent, 0); + final int notificationId = mMediaStorageNotification.icon; + if (visible) { + notificationManager.notify(notificationId, mMediaStorageNotification); + } else { + notificationManager.cancel(notificationId); + } } } diff --git a/services/java/com/android/server/NetStatService.java b/services/java/com/android/server/NetStatService.java index 11dbe6326351f8a17fd5961525799098679c1042..1ea0bac437659985c367ab661b51c250367d13d4 100644 --- a/services/java/com/android/server/NetStatService.java +++ b/services/java/com/android/server/NetStatService.java @@ -26,20 +26,35 @@ public class NetStatService extends INetStatService.Stub { } - public int getTxPackets() { - return NetStat.netStatGetTxPkts(); + public long getMobileTxPackets() { + return NetStat.getMobileTxPkts(); } - public int getRxPackets() { - return NetStat.netStatGetRxPkts(); + public long getMobileRxPackets() { + return NetStat.getMobileRxPkts(); } - public int getTxBytes() { - return NetStat.netStatGetTxBytes(); + public long getMobileTxBytes() { + return NetStat.getMobileTxBytes(); } - public int getRxBytes() { - return NetStat.netStatGetRxBytes(); + public long getMobileRxBytes() { + return NetStat.getMobileRxBytes(); } + public long getTotalTxPackets() { + return NetStat.getTotalTxPkts(); + } + + public long getTotalRxPackets() { + return NetStat.getTotalRxPkts(); + } + + public long getTotalTxBytes() { + return NetStat.getTotalTxBytes(); + } + + public long getTotalRxBytes() { + return NetStat.getTotalRxBytes(); + } } diff --git a/services/java/com/android/server/NotificationManagerService.java b/services/java/com/android/server/NotificationManagerService.java index eb9ebe95aae19509e2abac14182a6c7296a07171..bc4b169ce9d5a46a4c9ee5f04baaf257b3b4f902 100644 --- a/services/java/com/android/server/NotificationManagerService.java +++ b/services/java/com/android/server/NotificationManagerService.java @@ -311,6 +311,17 @@ class NotificationManagerService extends INotificationManager.Stub mBatteryFull = batteryFull; updateLights(); } + } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED) + || action.equals(Intent.ACTION_PACKAGE_RESTARTED)) { + Uri uri = intent.getData(); + if (uri == null) { + return; + } + String pkgName = uri.getSchemeSpecificPart(); + if (pkgName == null) { + return; + } + cancelAllNotifications(pkgName); } } }; @@ -331,6 +342,8 @@ class NotificationManagerService extends INotificationManager.Stub // register for battery changed notifications IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_BATTERY_CHANGED); + filter.addAction(Intent.ACTION_PACKAGE_REMOVED); + filter.addAction(Intent.ACTION_PACKAGE_RESTARTED); mContext.registerReceiver(mIntentReceiver, filter); } @@ -865,7 +878,7 @@ class NotificationManagerService extends INotificationManager.Stub // ====================================================================== @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission("android.permission.DUMP") + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump NotificationManager from from pid=" + Binder.getCallingPid() diff --git a/services/java/com/android/server/PackageManagerService.java b/services/java/com/android/server/PackageManagerService.java index 58ad42620ff0dafcc66bc94730548cddd4ee7e51..9f428e985b60589e76db8ced76f13ec98bb59d87 100644 --- a/services/java/com/android/server/PackageManagerService.java +++ b/services/java/com/android/server/PackageManagerService.java @@ -97,6 +97,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; @@ -983,6 +984,20 @@ class PackageManagerService extends IPackageManager.Stub { } return null; } + + public String[] getSystemSharedLibraryNames() { + Set libSet; + synchronized (mPackages) { + libSet = mSharedLibraries.keySet(); + } + int size = libSet.size(); + if (size > 0) { + String[] libs = new String[size]; + libSet.toArray(libs); + return libs; + } + return null; + } public int checkPermission(String permName, String pkgName) { synchronized (mPackages) { @@ -1813,7 +1828,7 @@ class PackageManagerService extends IPackageManager.Stub { } return true; } - + private PackageParser.Package scanPackageLI( File scanFile, File destCodeFile, File destResourceFile, PackageParser.Package pkg, int parseFlags, int scanMode) { @@ -1910,19 +1925,18 @@ class PackageManagerService extends IPackageManager.Stub { } } + // Just create the setting, don't add it yet pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile, - destResourceFile, pkg.applicationInfo.flags, true); + destResourceFile, pkg.applicationInfo.flags, true, false); if (pkgSetting == null) { Log.w(TAG, "Creating application package " + pkgName + " failed"); mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; return null; } - synchronized(mPackages) { - if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) { - pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; - } + if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) { + pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; } - + pkg.applicationInfo.uid = pkgSetting.userId; pkg.mExtras = pkgSetting; @@ -1970,24 +1984,12 @@ class PackageManagerService extends IPackageManager.Stub { long scanFileTime = scanFile.lastModified(); final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp(); - - // At this point we know it is okay to accept the package, though - // errors can still happen as we try to install... - - if ((scanMode&SCAN_MONITOR) != 0) { - pkg.mPath = destCodeFile.getAbsolutePath(); - mAppDirs.put(pkg.mPath, pkg); - } pkg.applicationInfo.processName = fixProcessName( pkg.applicationInfo.packageName, pkg.applicationInfo.processName, pkg.applicationInfo.uid); pkg.applicationInfo.publicSourceDir = pkgSetting.resourcePathString; - synchronized (mPackages) { - mPackages.put(pkg.applicationInfo.packageName, pkg); - } - File dataPath; if (mPlatformPackage == pkg) { // The system package is special. @@ -2030,8 +2032,7 @@ class PackageManagerService extends IPackageManager.Stub { return null; } } - - } + } if (!recovered) { mHasSystemUidErrors = true; } @@ -2063,7 +2064,7 @@ class PackageManagerService extends IPackageManager.Stub { int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid, pkg.applicationInfo.uid); if(ret < 0) { - //error from installer + // Error from installer mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; return null; } @@ -2133,8 +2134,17 @@ class PackageManagerService extends IPackageManager.Stub { pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; } + if ((scanMode&SCAN_MONITOR) != 0) { + pkg.mPath = destCodeFile.getAbsolutePath(); + mAppDirs.put(pkg.mPath, pkg); + } + synchronized (mPackages) { - + // We don't expect installation to fail beyond this point + // Add the new setting to mSettings + mSettings.insertPackageSettingLP(pkgSetting, pkg.packageName, suid); + // Add the new setting to mPackages + mPackages.put(pkg.applicationInfo.packageName, pkg); int N = pkg.providers.size(); StringBuilder r = null; int i; @@ -2678,7 +2688,7 @@ class PackageManagerService extends IPackageManager.Stub { grantPermissionsLP(pkg, false); } } - + private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) { final PackageSetting ps = (PackageSetting)pkg.mExtras; if (ps == null) { @@ -2724,7 +2734,19 @@ class PackageManagerService extends IPackageManager.Stub { == PackageManager.SIGNATURE_MATCH); if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) { if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { - allowed = true; + // For updated system applications, the signatureOrSystem permission + // is granted only if it had been defined by the original application. + if ((pkg.applicationInfo.flags + & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) { + PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName); + if(sysPs.grantedPermissions.contains(perm)) { + allowed = true; + } else { + allowed = false; + } + } else { + allowed = true; + } } } } else { @@ -3157,6 +3179,7 @@ class PackageManagerService extends IPackageManager.Stub { if (removedPackage != null) { Bundle extras = new Bundle(1); extras.putInt(Intent.EXTRA_UID, removedUid); + extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras); } if (addedPackage != null) { @@ -3169,7 +3192,7 @@ class PackageManagerService extends IPackageManager.Stub { private final String mRootDir; private final boolean mIsRom; } - + /* Called when a downloaded package installation has been confirmed by the user */ public void installPackage( final Uri packageURI, final IPackageInstallObserver observer, final int flags) { @@ -3191,12 +3214,15 @@ class PackageManagerService extends IPackageManager.Stub { Log.i(TAG, "Observer no longer exists."); } } - // There appears to be a subtle deadlock condition if the sendPackageBroadcast call appears - // in the synchronized block above. + // There appears to be a subtle deadlock condition if the sendPackageBroadcast + // call appears in the synchronized block above. if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { - res.removedInfo.sendBroadcast(); + res.removedInfo.sendBroadcast(false, true); Bundle extras = new Bundle(1); extras.putInt(Intent.EXTRA_UID, res.uid); + if (res.removedInfo.removedPackage != null) { + extras.putBoolean(Intent.EXTRA_REPLACING, true); + } sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, res.pkg.applicationInfo.packageName, extras); @@ -3217,7 +3243,7 @@ class PackageManagerService extends IPackageManager.Stub { /* * Install a non-existing package. */ - private void installNewPackageLI(String pkgName, int parseFlags, + private void installNewPackageLI(String pkgName, File tmpPackageFile, String destFilePath, File destPackageFile, File destResourceFile, PackageParser.Package pkg, boolean forwardLocked, @@ -3241,7 +3267,7 @@ class PackageManagerService extends IPackageManager.Stub { } mLastScanError = PackageManager.INSTALL_SUCCEEDED; PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile, - destResourceFile, pkg, parseFlags, + destResourceFile, pkg, 0, SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)); @@ -3273,7 +3299,7 @@ class PackageManagerService extends IPackageManager.Stub { } } - private void replacePackageLI(String pkgName, int parseFlags, + private void replacePackageLI(String pkgName, File tmpPackageFile, String destFilePath, File destPackageFile, File destResourceFile, PackageParser.Package pkg, boolean forwardLocked, @@ -3290,16 +3316,15 @@ class PackageManagerService extends IPackageManager.Stub { boolean sysPkg = ((deletedPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0); if(sysPkg) { replaceSystemPackageLI(deletedPackage, - parseFlags, tmpPackageFile, destFilePath, destPackageFile, destResourceFile, pkg, forwardLocked, res); } else { - replaceNonSystemPackageLI(deletedPackage, parseFlags, tmpPackageFile, destFilePath, + replaceNonSystemPackageLI(deletedPackage, tmpPackageFile, destFilePath, destPackageFile, destResourceFile, pkg, forwardLocked, res); } } - private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, int parseFlags, + private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, File tmpPackageFile, String destFilePath, File destPackageFile, File destResourceFile, PackageParser.Package pkg, boolean forwardLocked, @@ -3308,6 +3333,7 @@ class PackageManagerService extends IPackageManager.Stub { String pkgName = deletedPackage.packageName; boolean deletedPkg = true; boolean updatedSettings = false; + int parseFlags = PackageManager.REPLACE_EXISTING_PACKAGE; // First delete the existing package while retaining the data directory if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA, res.removedInfo)) { @@ -3383,14 +3409,15 @@ class PackageManagerService extends IPackageManager.Stub { } } - private void replaceSystemPackageLI(PackageParser.Package deletedPackage, int parseFlags, + private void replaceSystemPackageLI(PackageParser.Package deletedPackage, File tmpPackageFile, String destFilePath, File destPackageFile, File destResourceFile, PackageParser.Package pkg, boolean forwardLocked, PackageInstalledInfo res) { PackageParser.Package newPackage = null; boolean updatedSettings = false; - parseFlags |= PackageParser.PARSE_IS_SYSTEM; + int parseFlags = PackageManager.REPLACE_EXISTING_PACKAGE | + PackageParser.PARSE_IS_SYSTEM; String packageName = deletedPackage.packageName; res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; if (packageName == null) { @@ -3534,7 +3561,6 @@ class PackageManagerService extends IPackageManager.Stub { String pkgName = null; boolean forwardLocked = false; boolean replacingExistingPackage = false; - // Result object to be returned PackageInstalledInfo res = new PackageInstalledInfo(); res.returnCode = PackageManager.INSTALL_SUCCEEDED; @@ -3640,13 +3666,13 @@ class PackageManagerService extends IPackageManager.Stub { } if(replacingExistingPackage) { - replacePackageLI(pkgName, pFlags, + replacePackageLI(pkgName, tmpPackageFile, destFilePath, destPackageFile, destResourceFile, pkg, forwardLocked, res); } else { - installNewPackageLI(pkgName, pFlags, + installNewPackageLI(pkgName, tmpPackageFile, destFilePath, destPackageFile, destResourceFile, pkg, forwardLocked, @@ -3842,7 +3868,7 @@ class PackageManagerService extends IPackageManager.Stub { } if(res && sendBroadCast) { - info.sendBroadcast(); + info.sendBroadcast(deleteCodeAndResources, false); } return res; } @@ -3852,9 +3878,13 @@ class PackageManagerService extends IPackageManager.Stub { int uid = -1; int removedUid = -1; - void sendBroadcast() { + void sendBroadcast(boolean fullRemove, boolean replacing) { Bundle extras = new Bundle(1); extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid); + extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); + if (replacing) { + extras.putBoolean(Intent.EXTRA_REPLACING, true); + } if (removedPackage != null) { sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras); } @@ -3967,7 +3997,6 @@ class PackageManagerService extends IPackageManager.Stub { File sourceFile = new File(applicationInfo.sourceDir); if (!sourceFile.exists()) { Log.w(TAG, "Package source " + applicationInfo.sourceDir + " does not exist."); - return false; } outInfo.uid = applicationInfo.uid; @@ -4463,6 +4492,10 @@ class PackageManagerService extends IPackageManager.Stub { mSystemReady = true; } + public boolean isSafeMode() { + return mSafeMode; + } + public boolean hasSystemUidErrors() { return mHasSystemUidErrors; } @@ -4482,7 +4515,7 @@ class PackageManagerService extends IPackageManager.Stub { @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission(android.Manifest.permission.DUMP) + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump ActivityManager from from pid=" + Binder.getCallingPid() @@ -5279,10 +5312,10 @@ class PackageManagerService extends IPackageManager.Stub { PackageSetting getPackageLP(PackageParser.Package pkg, SharedUserSetting sharedUser, File codePath, File resourcePath, - int pkgFlags, boolean create) { + int pkgFlags, boolean create, boolean add) { final String name = pkg.packageName; PackageSetting p = getPackageLP(name, sharedUser, codePath, - resourcePath, pkgFlags, create); + resourcePath, pkgFlags, create, add); if (p != null) { p.pkg = pkg; @@ -5413,7 +5446,7 @@ class PackageManagerService extends IPackageManager.Stub { private PackageSetting getPackageLP(String name, SharedUserSetting sharedUser, File codePath, File resourcePath, - int pkgFlags, boolean create) { + int pkgFlags, boolean create, boolean add) { PackageSetting p = mPackages.get(name); if (p != null) { if (!p.codePath.equals(codePath)) { @@ -5427,6 +5460,12 @@ class PackageManagerService extends IPackageManager.Stub { // has to delete the one installed in the data partition in order to pick up the // new system package. return p; + } else if ((p.pkg != null) && (p.pkg.applicationInfo != null) && + ((p.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)) { + // Check for non-system apps + reportSettingsProblem(Log.WARN, + "Package " + name + " codePath changed from " + p.codePath + + " to " + codePath + "; Retaining data and using new code"); } else { reportSettingsProblem(Log.WARN, "Package " + name + " codePath changed from " + p.codePath @@ -5458,15 +5497,25 @@ class PackageManagerService extends IPackageManager.Stub { } else { p.userId = FIRST_APPLICATION_UID; } - if (p.userId < 0) { reportSettingsProblem(Log.WARN, "Package " + name + " could not be assigned a valid uid"); return null; } - mPackages.put(name, p); + if (add) { + // Finish adding new package by adding it and updating shared + // user preferences + insertPackageSettingLP(p, name, sharedUser); + } } - + return p; + } + + // Utility method that adds a PackageSetting to mPackages and + // completes updating the shared user attributes + private void insertPackageSettingLP(PackageSetting p, String name, + SharedUserSetting sharedUser) { + mPackages.put(name, p); if (sharedUser != null) { if (p.sharedUser != null && p.sharedUser != sharedUser) { reportSettingsProblem(Log.ERROR, @@ -5476,17 +5525,16 @@ class PackageManagerService extends IPackageManager.Stub { p.sharedUser.packages.remove(p); } else if (p.userId != sharedUser.userId) { reportSettingsProblem(Log.ERROR, - "Package " + p.name + " was user id " + p.userId - + " but is now user " + sharedUser - + " with id " + sharedUser.userId - + "; I am not changing its files so it will probably fail!"); + "Package " + p.name + " was user id " + p.userId + + " but is now user " + sharedUser + + " with id " + sharedUser.userId + + "; I am not changing its files so it will probably fail!"); } sharedUser.packages.add(p); p.sharedUser = sharedUser; p.userId = sharedUser.userId; } - return p; } private void updateSharedUserPerms (PackageSetting deletedPs) { @@ -5637,23 +5685,8 @@ class PackageManagerService extends IPackageManager.Stub { } for (PackageSetting pkg : mDisabledSysPackages.values()) { - serializer.startTag(null, "updated-package"); - serializer.attribute(null, "name", pkg.name); - serializer.attribute(null, "codePath", pkg.codePathString); - serializer.attribute(null, "ts", pkg.getTimeStampStr()); - if (!pkg.resourcePathString.equals(pkg.codePathString)) { - serializer.attribute(null, "resourcePath", pkg.resourcePathString); - } - if (pkg.sharedUser == null) { - serializer.attribute(null, "userId", - Integer.toString(pkg.userId)); - } else { - serializer.attribute(null, "sharedUserId", - Integer.toString(pkg.userId)); - } - serializer.endTag(null, "updated-package"); + writeDisabledSysPackage(serializer, pkg); } - serializer.startTag(null, "preferred-packages"); int N = mPreferredPackages.size(); @@ -5716,6 +5749,43 @@ class PackageManagerService extends IPackageManager.Stub { //Debug.stopMethodTracing(); } + void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg) + throws java.io.IOException { + serializer.startTag(null, "updated-package"); + serializer.attribute(null, "name", pkg.name); + serializer.attribute(null, "codePath", pkg.codePathString); + serializer.attribute(null, "ts", pkg.getTimeStampStr()); + if (!pkg.resourcePathString.equals(pkg.codePathString)) { + serializer.attribute(null, "resourcePath", pkg.resourcePathString); + } + if (pkg.sharedUser == null) { + serializer.attribute(null, "userId", + Integer.toString(pkg.userId)); + } else { + serializer.attribute(null, "sharedUserId", + Integer.toString(pkg.userId)); + } + serializer.startTag(null, "perms"); + if (pkg.sharedUser == null) { + // If this is a shared user, the permissions will + // be written there. We still need to write an + // empty permissions list so permissionsFixed will + // be set. + for (final String name : pkg.grantedPermissions) { + BasePermission bp = mPermissions.get(name); + if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) { + // We only need to write signature or system permissions but this wont + // match the semantics of grantedPermissions. So write all permissions. + serializer.startTag(null, "item"); + serializer.attribute(null, "name", name); + serializer.endTag(null, "item"); + } + } + } + serializer.endTag(null, "perms"); + serializer.endTag(null, "updated-package"); + } + void writePackage(XmlSerializer serializer, final PackageSetting pkg) throws java.io.IOException { serializer.startTag(null, "package"); @@ -5892,33 +5962,7 @@ class PackageManagerService extends IPackageManager.Stub { } else if (tagName.equals("preferred-activities")) { readPreferredActivitiesLP(parser); } else if(tagName.equals("updated-package")) { - String name = parser.getAttributeValue(null, "name"); - String codePathStr = parser.getAttributeValue(null, "codePath"); - String resourcePathStr = parser.getAttributeValue(null, "resourcePath"); - if(resourcePathStr == null) { - resourcePathStr = codePathStr; - } - - int pkgFlags = 0; - pkgFlags |= ApplicationInfo.FLAG_SYSTEM; - PackageSetting ps = new PackageSetting(name, - new File(codePathStr), - new File(resourcePathStr), pkgFlags); - String timeStampStr = parser.getAttributeValue(null, "ts"); - if (timeStampStr != null) { - try { - long timeStamp = Long.parseLong(timeStampStr); - ps.setTimeStamp(timeStamp, timeStampStr); - } catch (NumberFormatException e) { - } - } - String idStr = parser.getAttributeValue(null, "userId"); - ps.userId = idStr != null ? Integer.parseInt(idStr) : 0; - if(ps.userId <= 0) { - String sharedIdStr = parser.getAttributeValue(null, "sharedUserId"); - ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0; - } - mDisabledSysPackages.put(name, ps); + readDisabledSysPackageLP(parser); } else { Log.w(TAG, "Unknown element under : " + parser.getName()); @@ -5945,7 +5989,7 @@ class PackageManagerService extends IPackageManager.Stub { if (idObj != null && idObj instanceof SharedUserSetting) { PackageSetting p = getPackageLP(pp.name, (SharedUserSetting)idObj, pp.codePath, pp.resourcePath, - pp.pkgFlags, true); + pp.pkgFlags, true, true); if (p == null) { Log.w(TAG, "Unable to create application package for " + pp.name); @@ -6056,6 +6100,58 @@ class PackageManagerService extends IPackageManager.Stub { } } + private void readDisabledSysPackageLP(XmlPullParser parser) + throws XmlPullParserException, IOException { + String name = parser.getAttributeValue(null, "name"); + String codePathStr = parser.getAttributeValue(null, "codePath"); + String resourcePathStr = parser.getAttributeValue(null, "resourcePath"); + if(resourcePathStr == null) { + resourcePathStr = codePathStr; + } + + int pkgFlags = 0; + pkgFlags |= ApplicationInfo.FLAG_SYSTEM; + PackageSetting ps = new PackageSetting(name, + new File(codePathStr), + new File(resourcePathStr), pkgFlags); + String timeStampStr = parser.getAttributeValue(null, "ts"); + if (timeStampStr != null) { + try { + long timeStamp = Long.parseLong(timeStampStr); + ps.setTimeStamp(timeStamp, timeStampStr); + } catch (NumberFormatException e) { + } + } + String idStr = parser.getAttributeValue(null, "userId"); + ps.userId = idStr != null ? Integer.parseInt(idStr) : 0; + if(ps.userId <= 0) { + String sharedIdStr = parser.getAttributeValue(null, "sharedUserId"); + ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0; + } + int outerDepth = parser.getDepth(); + int type; + while ((type=parser.next()) != XmlPullParser.END_DOCUMENT + && (type != XmlPullParser.END_TAG + || parser.getDepth() > outerDepth)) { + if (type == XmlPullParser.END_TAG + || type == XmlPullParser.TEXT) { + continue; + } + + String tagName = parser.getName(); + if (tagName.equals("perms")) { + readGrantedPermissionsLP(parser, + ps.grantedPermissions); + } else { + reportSettingsProblem(Log.WARN, + "Unknown element under : " + + parser.getName()); + XmlUtils.skipCurrentTag(parser); + } + } + mDisabledSysPackages.put(name, ps); + } + private void readPackageLP(XmlPullParser parser) throws XmlPullParserException, IOException { String name = null; diff --git a/services/java/com/android/server/PowerManagerService.java b/services/java/com/android/server/PowerManagerService.java index ca0ad1a15c82f7a586390ec9036669909c96206c..ad30ffcc0780aa6b3b8f41400e613bd260fb4604 100644 --- a/services/java/com/android/server/PowerManagerService.java +++ b/services/java/com/android/server/PowerManagerService.java @@ -182,6 +182,7 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage private long mScreenOnTime; private long mScreenOnStartTime; private boolean mPreventScreenOn; + private int mScreenBrightnessOverride = -1; // Used when logging number and duration of touch-down cycles private long mTotalTouchDownTime; @@ -245,7 +246,13 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage public void acquire() { if (!mRefCounted || mCount++ == 0) { - PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken, mTag); + long ident = Binder.clearCallingIdentity(); + try { + PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken, + MY_UID, mTag); + } finally { + Binder.restoreCallingIdentity(ident); + } } } @@ -486,12 +493,18 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage public void acquireWakeLock(int flags, IBinder lock, String tag) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); - synchronized (mLocks) { - acquireWakeLockLocked(flags, lock, tag); + int uid = Binder.getCallingUid(); + long ident = Binder.clearCallingIdentity(); + try { + synchronized (mLocks) { + acquireWakeLockLocked(flags, lock, uid, tag); + } + } finally { + Binder.restoreCallingIdentity(ident); } } - public void acquireWakeLockLocked(int flags, IBinder lock, String tag) { + public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) { int acquireUid = -1; String acquireName = null; int acquireType = -1; @@ -504,7 +517,7 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage WakeLock wl; boolean newlock; if (index < 0) { - wl = new WakeLock(flags, lock, tag, Binder.getCallingUid()); + wl = new WakeLock(flags, lock, tag, uid); switch (wl.flags & LOCK_MASK) { case PowerManager.FULL_WAKE_LOCK: @@ -573,9 +586,7 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage if (acquireType >= 0) { try { - long origId = Binder.clearCallingIdentity(); mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType); - Binder.restoreCallingIdentity(origId); } catch (RemoteException e) { // Ignore } @@ -627,12 +638,13 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage releaseType = wl.monitorType; if (releaseType >= 0) { + long origId = Binder.clearCallingIdentity(); try { - long origId = Binder.clearCallingIdentity(); mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType); - Binder.restoreCallingIdentity(origId); } catch (RemoteException e) { // Ignore + } finally { + Binder.restoreCallingIdentity(origId); } } } @@ -757,7 +769,7 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage @Override public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission(android.Manifest.permission.DUMP) + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump PowerManager from from pid=" + Binder.getCallingPid() @@ -790,6 +802,8 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage + " mUserActivityAllowed=" + mUserActivityAllowed); pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay); + pw.println(" mPreventScreenOn=" + mPreventScreenOn + + " mScreenBrightnessOverride=" + mScreenBrightnessOverride); pw.println(" mTotalDelaySetting=" + mTotalDelaySetting); pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock); pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock); @@ -959,7 +973,7 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage if (mSpew) { Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock); } - if (mContext != null) { + if (mContext != null && ActivityManagerNative.isSystemReady()) { mContext.sendOrderedBroadcast(mScreenOnIntent, null, mScreenOnBroadcastDone, mHandler, 0, null, null); } else { @@ -980,7 +994,7 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage // ignore it. } - if (mContext != null) { + if (mContext != null && ActivityManagerNative.isSystemReady()) { mContext.sendOrderedBroadcast(mScreenOffIntent, null, mScreenOffBroadcastDone, mHandler, 0, null, null); } else { @@ -992,11 +1006,9 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage } } else { - synchronized (mLocks) { - EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 4, - mBroadcastWakeLock.mCount); - mBroadcastWakeLock.release(); - } + // If we're in this case, then this handler is running for a previous + // paired transaction. mBroadcastWakeLock will already have been released + // in sendNotificationLocked. } } }; @@ -1070,7 +1082,6 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage * lock (rather than an IPowerManager call). */ public void preventScreenOn(boolean prevent) { - // TODO: use a totally new permission (separate from DEVICE_POWER) for this? mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); synchronized (mLocks) { @@ -1119,6 +1130,17 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage } } + public void setScreenBrightnessOverride(int brightness) { + mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); + + synchronized (mLocks) { + if (mScreenBrightnessOverride != brightness) { + mScreenBrightnessOverride = brightness; + updateLightsLocked(mPowerState, SCREEN_ON_BIT); + } + } + } + /** * Sanity-check that gets called 5 seconds after any call to * preventScreenOn(true). This ensures that the original call @@ -1204,7 +1226,7 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage } if (mPowerState != newState) { - err = updateLightsLocked(newState, becauseOfUser); + err = updateLightsLocked(newState, 0); if (err != 0) { return; } @@ -1232,6 +1254,14 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage } if (reallyTurnScreenOn) { err = Power.setScreenState(true); + long identity = Binder.clearCallingIdentity(); + try { + mBatteryStats.noteScreenOn(); + } catch (RemoteException e) { + Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e); + } finally { + Binder.restoreCallingIdentity(identity); + } } else { Power.setScreenState(false); // But continue as if we really did turn the screen on... @@ -1250,8 +1280,17 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage } } else { mScreenOffTime = SystemClock.elapsedRealtime(); + long identity = Binder.clearCallingIdentity(); + try { + mBatteryStats.noteScreenOff(); + } catch (RemoteException e) { + Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e); + } finally { + Binder.restoreCallingIdentity(identity); + } + mPowerState &= ~SCREEN_ON_BIT; if (!mScreenBrightness.animating) { - err = turnScreenOffLocked(becauseOfUser); + err = screenOffFinishedAnimating(becauseOfUser); } else { mOffBecauseOfUser = becauseOfUser; err = 0; @@ -1262,24 +1301,25 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage } } - private int turnScreenOffLocked(boolean becauseOfUser) { - if ((mPowerState&SCREEN_ON_BIT) != 0) { - EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0, - mTotalTouchDownTime, mTouchCycles); - mLastTouchDown = 0; - int err = Power.setScreenState(false); + private int screenOffFinishedAnimating(boolean becauseOfUser) { + // I don't think we need to check the current state here because all of these + // Power.setScreenState and sendNotificationLocked can both handle being + // called multiple times in the same state. -joeo + EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0, + mTotalTouchDownTime, mTouchCycles); + mLastTouchDown = 0; + int err = Power.setScreenState(false); + if (mScreenOnStartTime != 0) { mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime; mScreenOnStartTime = 0; - if (err == 0) { - mPowerState &= ~SCREEN_ON_BIT; - int why = becauseOfUser - ? WindowManagerPolicy.OFF_BECAUSE_OF_USER - : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT; - sendNotificationLocked(false, why); - } - return err; } - return 0; + if (err == 0) { + int why = becauseOfUser + ? WindowManagerPolicy.OFF_BECAUSE_OF_USER + : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT; + sendNotificationLocked(false, why); + } + return err; } private boolean batteryIsLow() { @@ -1287,9 +1327,9 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD); } - private int updateLightsLocked(int newState, boolean becauseOfUser) { + private int updateLightsLocked(int newState, int forceState) { int oldState = mPowerState; - int difference = newState ^ oldState; + int difference = (newState ^ oldState) | forceState; if (difference == 0) { return 0; } @@ -1494,7 +1534,7 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage animating = more; if (!more) { if (mask == Power.SCREEN_LIGHT && curIntValue == Power.BRIGHTNESS_OFF) { - turnScreenOffLocked(mOffBecauseOfUser); + screenOffFinishedAnimating(mOffBecauseOfUser); } } return more; @@ -1521,6 +1561,9 @@ class PowerManagerService extends IPowerManager.Stub implements LocalPowerManage private int getPreferredBrightness() { try { + if (mScreenBrightnessOverride >= 0) { + return mScreenBrightnessOverride; + } final int brightness = Settings.System.getInt(mContext.getContentResolver(), SCREEN_BRIGHTNESS); // Don't let applications turn the screen all the way off diff --git a/services/java/com/android/server/SensorService.java b/services/java/com/android/server/SensorService.java index f56088c642a78ae5f446fb6d79b3f72c903a5ac0..b2530383f347637060676cc78f7b792142a23c57 100644 --- a/services/java/com/android/server/SensorService.java +++ b/services/java/com/android/server/SensorService.java @@ -45,7 +45,7 @@ class SensorService extends ISensorService.Stub { private static final int SENSOR_DISABLE = -1; /** - * Battery statistics to be updated when sensors are enabled and diabled. + * Battery statistics to be updated when sensors are enabled and disabled. */ final IBatteryStats mBatteryStats = BatteryStatsService.getService(); @@ -105,9 +105,9 @@ class SensorService extends ISensorService.Stub { return _sensors_control_open(); } - public boolean enableSensor(IBinder binder, int sensor, int enable) + public boolean enableSensor(IBinder binder, String name, int sensor, int enable) throws RemoteException { - if (localLOGV) Log.d(TAG, "enableSensor " + sensor + " " + enable); + if (localLOGV) Log.d(TAG, "enableSensor " + name + "(#" + sensor + ") " + enable); // Inform battery statistics service of status change int uid = Binder.getCallingUid(); @@ -119,7 +119,10 @@ class SensorService extends ISensorService.Stub { } Binder.restoreCallingIdentity(identity); - if (binder == null) throw new NullPointerException("listener is null in enableSensor"); + if (binder == null) { + Log.w(TAG, "listener is null (sensor=" + name + ", id=" + sensor + ")"); + return false; + } synchronized(mListeners) { if (enable!=SENSOR_DISABLE && !_sensors_control_activate(sensor, true)) { @@ -145,7 +148,11 @@ class SensorService extends ISensorService.Stub { } if (l == null) { - throw new NullPointerException("no Listener object in enableSensor"); + // by construction, this means we're disabling a listener we + // don't know about... + Log.w(TAG, "listener with binder " + binder + + ", doesn't exist (sensor=" + name + ", id=" + sensor + ")"); + return false; } if (minDelay >= 0) { diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java index 7f7a52e0acceb5f2e7cc1dab7adcc643217a429e..a629ec61ffccefc69b2620f0ec1682a78abba299 100644 --- a/services/java/com/android/server/SystemServer.java +++ b/services/java/com/android/server/SystemServer.java @@ -16,35 +16,36 @@ package com.android.server; +import com.android.server.am.ActivityManagerService; +import com.android.server.status.StatusBarService; + +import dalvik.system.PathClassLoader; +import dalvik.system.VMRuntime; + import android.app.ActivityManagerNative; +import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentService; import android.content.Context; +import android.content.Intent; import android.content.pm.IPackageManager; import android.database.ContentObserver; import android.database.Cursor; import android.media.AudioService; +import android.os.IBinder; import android.os.Looper; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.SystemProperties; -import android.os.IBinder; -import android.provider.Settings; import android.provider.Contacts.People; -import android.server.BluetoothDeviceService; +import android.provider.Settings; import android.server.BluetoothA2dpService; -import android.server.checkin.FallbackCheckinService; +import android.server.BluetoothDeviceService; import android.server.search.SearchManagerService; import android.util.EventLog; import android.util.Log; -import dalvik.system.TouchDex; -import dalvik.system.VMRuntime; - -import com.android.server.am.ActivityManagerService; -import com.android.server.status.StatusBarService; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -180,13 +181,13 @@ class ServerThread extends Thread { StatusBarService statusBar = null; InputMethodManagerService imm = null; - + AppWidgetService appWidget = null; + if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) { try { Log.i(TAG, "Starting Status Bar Service."); statusBar = new StatusBarService(context); ServiceManager.addService("statusbar", statusBar); - com.android.server.status.StatusBarPolicy.installIcons(context, statusBar); } catch (Throwable e) { Log.e(TAG, "Failure starting StatusBarService", e); } @@ -205,7 +206,7 @@ class ServerThread extends Thread { } catch (Throwable e) { Log.e(TAG, "Failure starting Input Manager Service", e); } - + try { Log.i(TAG, "Starting Hardware Service."); ServiceManager.addService("hardware", new HardwareService(context)); @@ -272,9 +273,14 @@ class ServerThread extends Thread { } try { - Log.i(TAG, "Starting Checkin Service"); - addService(context, "checkin", "com.google.android.server.checkin.CheckinService", - FallbackCheckinService.class); + Log.i(TAG, "Starting Checkin Service."); + Intent intent = new Intent().setComponent(new ComponentName( + "com.google.android.server.checkin", + "com.google.android.server.checkin.CheckinService")); + if (context.startService(intent) == null) { + Log.w(TAG, "Using fallback Checkin Service."); + ServiceManager.addService("checkin", new FallbackCheckinService(context)); + } } catch (Throwable e) { Log.e(TAG, "Failure starting Checkin Service", e); } @@ -302,10 +308,17 @@ class ServerThread extends Thread { } try { - Log.i(TAG, "Starting Gadget Service"); - ServiceManager.addService(Context.GADGET_SERVICE, new GadgetService(context)); + Log.i(TAG, "Starting AppWidget Service"); + appWidget = new AppWidgetService(context); + ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget); } catch (Throwable e) { - Log.e(TAG, "Failure starting Gadget Service", e); + Log.e(TAG, "Failure starting AppWidget Service", e); + } + + try { + com.android.server.status.StatusBarPolicy.installIcons(context, statusBar); + } catch (Throwable e) { + Log.e(TAG, "Failure installing status bar icons", e); } } @@ -318,6 +331,7 @@ class ServerThread extends Thread { false, new AdbSettingsObserver()); // It is now time to start up the app processes... + boolean safeMode = wm.detectSafeMode(); if (statusBar != null) { statusBar.systemReady(); } @@ -330,6 +344,9 @@ class ServerThread extends Thread { pm.systemReady(); } catch (RemoteException e) { } + if (appWidget != null) { + appWidget.systemReady(safeMode); + } // After making the following code, third party code may be running... try { @@ -342,51 +359,6 @@ class ServerThread extends Thread { Looper.loop(); Log.d(TAG, "System ServerThread is exiting!"); } - - private void addService(Context context, String name, String serviceClass, - Class fallback) { - - final IBinder service = findService(context, serviceClass, fallback); - if (service != null) { - ServiceManager.addService(name, service); - } else { - Log.e(TAG, "Failure starting service '" + name + "' with class " + serviceClass); - } - } - - private IBinder findService(Context context, String serviceClass, - Class fallback) { - - IBinder service = null; - try { - Class klass = Class.forName(serviceClass); - Constructor c = klass.getConstructor(Context.class); - service = (IBinder) c.newInstance(context); - } catch (ClassNotFoundException e) { - // Ignore - } catch (IllegalAccessException e) { - // Ignore - } catch (NoSuchMethodException e) { - // Ignore - } catch (InvocationTargetException e) { - // Ignore - } catch (InstantiationException e) { - // Ignore - } - - if (service == null && fallback != null) { - Log.w(TAG, "Could not find " + serviceClass + ", trying fallback"); - try { - service = fallback.newInstance(); - } catch (IllegalAccessException e) { - // Ignore - } catch (InstantiationException e) { - // Ignore - } - } - - return service; - } } class DemoThread extends Thread diff --git a/services/java/com/android/server/TelephonyRegistry.java b/services/java/com/android/server/TelephonyRegistry.java index dbaf0869547ac127566ccf97747ea32032d64cbe..a74915c063bc8bb9fed9c1e2d27c78ec44477302 100644 --- a/services/java/com/android/server/TelephonyRegistry.java +++ b/services/java/com/android/server/TelephonyRegistry.java @@ -28,17 +28,20 @@ import android.telephony.PhoneStateListener; import android.telephony.ServiceState; import android.telephony.TelephonyManager; import android.text.TextUtils; +import android.util.Log; import java.util.ArrayList; import java.io.FileDescriptor; import java.io.PrintWriter; +import com.android.internal.app.IBatteryStats; import com.android.internal.telephony.ITelephonyRegistry; import com.android.internal.telephony.IPhoneStateListener; import com.android.internal.telephony.DefaultPhoneNotifier; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneStateIntentReceiver; import com.android.internal.telephony.TelephonyIntents; +import com.android.server.am.BatteryStatsService; /** @@ -55,8 +58,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { int events; } - private Context mContext; - private ArrayList mRecords = new ArrayList(); + private final Context mContext; + private final ArrayList mRecords = new ArrayList(); + private final IBatteryStats mBatteryStats; private int mCallState = TelephonyManager.CALL_STATE_IDLE; private String mCallIncomingNumber = ""; @@ -81,6 +85,7 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { TelephonyRegistry(Context context) { CellLocation.getEmpty().fillInNotifierBundle(mCellLocation); mContext = context; + mBatteryStats = BatteryStatsService.getService(); } public void listen(String pkgForDebug, IPhoneStateListener callback, int events, @@ -183,6 +188,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } public void notifyCallState(int state, String incomingNumber) { + if (!checkPhoneStatePermission("notifyCallState()")) { + return; + } synchronized (mRecords) { mCallState = state; mCallIncomingNumber = incomingNumber; @@ -202,6 +210,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } public void notifyServiceState(ServiceState state) { + if (!checkPhoneStatePermission("notifyServiceState()")) { + return; + } synchronized (mRecords) { mServiceState = state; final int N = mRecords.size(); @@ -216,6 +227,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } public void notifySignalStrength(int signalStrengthASU) { + if (!checkPhoneStatePermission("notifySignalStrength()")) { + return; + } synchronized (mRecords) { mSignalStrength = signalStrengthASU; final int N = mRecords.size(); @@ -234,6 +248,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } public void notifyMessageWaitingChanged(boolean mwi) { + if (!checkPhoneStatePermission("notifyMessageWaitingChanged()")) { + return; + } synchronized (mRecords) { mMessageWaiting = mwi; final int N = mRecords.size(); @@ -251,6 +268,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } public void notifyCallForwardingChanged(boolean cfi) { + if (!checkPhoneStatePermission("notifyCallForwardingChanged()")) { + return; + } synchronized (mRecords) { mCallForwarding = cfi; final int N = mRecords.size(); @@ -268,6 +288,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } public void notifyDataActivity(int state) { + if (!checkPhoneStatePermission("notifyDataActivity()")) { + return; + } synchronized (mRecords) { mDataActivity = state; final int N = mRecords.size(); @@ -286,6 +309,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { public void notifyDataConnection(int state, boolean isDataConnectivityPissible, String reason, String apn, String interfaceName) { + if (!checkPhoneStatePermission("notifyDataConnection()")) { + return; + } synchronized (mRecords) { mDataConnectionState = state; mDataConnectionPossible = isDataConnectivityPissible; @@ -309,6 +335,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } public void notifyDataConnectionFailed(String reason) { + if (!checkPhoneStatePermission("notifyDataConnectionFailed()")) { + return; + } /* * This is commented out because there is on onDataConnectionFailed callback * on PhoneStateListener. There should be. @@ -327,6 +356,9 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } public void notifyCellLocation(Bundle cellLocation) { + if (!checkPhoneStatePermission("notifyCellLocation()")) { + return; + } synchronized (mRecords) { mCellLocation = cellLocation; final int N = mRecords.size(); @@ -363,7 +395,7 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { @Override public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission(android.Manifest.permission.DUMP) + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump telephony.registry from from pid=" + Binder.getCallingPid() @@ -414,6 +446,18 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { } private void broadcastCallStateChanged(int state, String incomingNumber) { + long ident = Binder.clearCallingIdentity(); + try { + if (state == TelephonyManager.CALL_STATE_IDLE) { + mBatteryStats.notePhoneOff(); + } else { + mBatteryStats.notePhoneOn(); + } + } catch (RemoteException e) { + } finally { + Binder.restoreCallingIdentity(ident); + } + Intent intent = new Intent(TelephonyManager.ACTION_PHONE_STATE_CHANGED); intent.putExtra(Phone.STATE_KEY, DefaultPhoneNotifier.convertCallState(state).toString()); @@ -443,4 +487,16 @@ class TelephonyRegistry extends ITelephonyRegistry.Stub { intent.putExtra(Phone.FAILURE_REASON_KEY, reason); mContext.sendStickyBroadcast(intent); } + + private boolean checkPhoneStatePermission(String method) { + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.MODIFY_PHONE_STATE) + == PackageManager.PERMISSION_GRANTED) { + return true; + } + String msg = "Modify Phone State Permission Denial: " + method + " from pid=" + + Binder.getCallingPid() + + ", uid=" + Binder.getCallingUid(); + Log.w(TAG, msg); + return false; + } } diff --git a/services/java/com/android/server/WifiService.java b/services/java/com/android/server/WifiService.java index 2d61b1e537640a343461017b9ed4ff057f813c0b..e298f49378de54907fe5b2a33a4a05e2fa70a2e7 100644 --- a/services/java/com/android/server/WifiService.java +++ b/services/java/com/android/server/WifiService.java @@ -24,6 +24,7 @@ import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN; import android.app.AlarmManager; import android.app.PendingIntent; +import android.bluetooth.BluetoothA2dp; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; @@ -86,10 +87,13 @@ public class WifiService extends IWifiManager.Stub { private final LockList mLocks = new LockList(); /** - * See {@link Settings.System#WIFI_IDLE_MS}. This is the default value if a - * Settings.System value is not present. + * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a + * Settings.Gservices value is not present. This timeout value is chosen as + * the approximate point at which the battery drain caused by Wi-Fi + * being enabled but not active exceeds the battery drain caused by + * re-establishing a connection to the mobile data network. */ - private static final long DEFAULT_IDLE_MILLIS = 2 * 60 * 1000; /* 2 minutes */ + private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */ private static final String WAKELOCK_TAG = "WifiService"; @@ -100,7 +104,7 @@ public class WifiService extends IWifiManager.Stub { * provides a bit of extra margin. *

              * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}. - * This is the default value if a Settings.System value is not present. + * This is the default value if a Settings.Secure value is not present. */ private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000; @@ -204,8 +208,6 @@ public class WifiService extends IWifiManager.Stub { mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK); synchronized (sDriverStopWakeLock) { if (sDriverStopWakeLock.isHeld()) { - if (DBG) Log.d(TAG, "Releasing driver-stop wakelock " + - sDriverStopWakeLock); sDriverStopWakeLock.release(); } } @@ -213,9 +215,18 @@ public class WifiService extends IWifiManager.Stub { } ); - Log.d(TAG, "WifiService starting up with Wi-Fi " + - (wifiEnabled ? "enabled" : "disabled")); - registerForBroadcasts(); + Log.i(TAG, "WifiService starting up with Wi-Fi " + + (wifiEnabled ? "enabled" : "disabled")); + + mContext.registerReceiver( + new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + updateWifiState(); + } + }, + new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)); + setWifiEnabledBlocking(wifiEnabled, false); } @@ -293,7 +304,7 @@ public class WifiService extends IWifiManager.Stub { decrementHiddentNetworkPresentCounter(); } } - mIsHiddenNetworkPresent.put(netId, new Boolean(present)); + mIsHiddenNetworkPresent.put(netId, present); } } else { Log.e(TAG, "addOrUpdateHiddenNetwork(): Invalid (negative) network id!"); @@ -422,6 +433,7 @@ public class WifiService extends IWifiManager.Stub { /** * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} + * @param enable {@code true} to enable, {@code false} to disable. * @return {@code true} if the enable/disable operation was * started or is already in the queue. */ @@ -429,10 +441,6 @@ public class WifiService extends IWifiManager.Stub { enforceChangePermission(); if (mWifiHandler == null) return false; - /* - * Remove any enable/disable Wi-Fi messages we may have in the queue - * before adding a new one - */ synchronized (mWifiHandler) { sWakeLock.acquire(); sendEnableMessage(enable, true); @@ -458,40 +466,42 @@ public class WifiService extends IWifiManager.Stub { return false; } - updateWifiState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING); + setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING); if (enable) { if (!WifiNative.loadDriver()) { Log.e(TAG, "Failed to load Wi-Fi driver."); - updateWifiState(WIFI_STATE_UNKNOWN); + setWifiEnabledState(WIFI_STATE_UNKNOWN); return false; } if (!WifiNative.startSupplicant()) { WifiNative.unloadDriver(); Log.e(TAG, "Failed to start supplicant daemon."); - updateWifiState(WIFI_STATE_UNKNOWN); + setWifiEnabledState(WIFI_STATE_UNKNOWN); return false; } + registerForBroadcasts(); mWifiStateTracker.startEventLoop(); } else { - // Remove notification (it will no-op if it isn't visible) + mContext.unregisterReceiver(mReceiver); + // Remove notification (it will no-op if it isn't visible) mWifiStateTracker.setNotificationVisible(false, 0, false, 0); boolean failedToStopSupplicantOrUnloadDriver = false; if (!WifiNative.stopSupplicant()) { Log.e(TAG, "Failed to stop supplicant daemon."); - updateWifiState(WIFI_STATE_UNKNOWN); + setWifiEnabledState(WIFI_STATE_UNKNOWN); failedToStopSupplicantOrUnloadDriver = true; } - + // We must reset the interface before we unload the driver mWifiStateTracker.resetInterface(); - + if (!WifiNative.unloadDriver()) { Log.e(TAG, "Failed to unload Wi-Fi driver."); if (!failedToStopSupplicantOrUnloadDriver) { - updateWifiState(WIFI_STATE_UNKNOWN); + setWifiEnabledState(WIFI_STATE_UNKNOWN); failedToStopSupplicantOrUnloadDriver = true; } } @@ -505,7 +515,7 @@ public class WifiService extends IWifiManager.Stub { if (persist) { persistWifiEnabled(enable); } - updateWifiState(eventualWifiState); + setWifiEnabledState(eventualWifiState); /* * Initialize the hidden networks state and the number of allowed @@ -519,7 +529,7 @@ public class WifiService extends IWifiManager.Stub { return true; } - private void updateWifiState(int wifiState) { + private void setWifiEnabledState(int wifiState) { final int previousWifiState = mWifiState; // Update state @@ -527,6 +537,7 @@ public class WifiService extends IWifiManager.Stub { // Broadcast final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION); + intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState); intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState); mContext.sendStickyBroadcast(intent); @@ -551,7 +562,7 @@ public class WifiService extends IWifiManager.Stub { * {@link WifiManager#WIFI_STATE_ENABLING}, * {@link WifiManager#WIFI_STATE_UNKNOWN} */ - public int getWifiState() { + public int getWifiEnabledState() { enforceAccessPermission(); return mWifiState; } @@ -1082,9 +1093,7 @@ public class WifiService extends IWifiManager.Stub { */ removeNetworkIfHidden(netId); - synchronized (mWifiStateTracker) { - return WifiNative.removeNetworkCommand(netId); - } + return mWifiStateTracker.removeNetwork(netId); } /** @@ -1221,7 +1230,6 @@ public class WifiService extends IWifiManager.Stub { if (scanResult != null) { scanResult.level = -scanResultLevel; scanList.add(scanResult); - //if (DBG) Log.d(TAG, "ScanResult: " + scanResult); } } else if (DBG) { Log.w(TAG, @@ -1344,7 +1352,7 @@ public class WifiService extends IWifiManager.Stub { if (result && mNeedReconfig) { mNeedReconfig = false; result = WifiNative.reloadConfigCommand(); - + if (result) { Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION); mContext.sendBroadcast(intent); @@ -1359,7 +1367,7 @@ public class WifiService extends IWifiManager.Stub { * in the current regulatory domain. This method should be used only * if the correct number of channels cannot be determined automatically * for some reason. If the operation is successful, the new value is - * persisted as a System setting. + * persisted as a Secure setting. * @param numChannels the number of allowed channels. Must be greater than 0 * and less than or equal to 16. * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g., @@ -1441,14 +1449,12 @@ public class WifiService extends IWifiManager.Stub { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); - long idleMillis = Settings.System.getLong(mContext.getContentResolver(), - Settings.System.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS); + long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(), + Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS); int stayAwakeConditions = Settings.System.getInt(mContext.getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0); - if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) { - /* do nothing, we'll check isAirplaneModeOn later. */ - } else if (action.equals(Intent.ACTION_SCREEN_ON)) { + if (action.equals(Intent.ACTION_SCREEN_ON)) { mAlarmManager.cancel(mIdleIntent); mDeviceIdle = false; mScreenOff = false; @@ -1485,6 +1491,12 @@ public class WifiService extends IWifiManager.Stub { return; } mPluggedType = pluggedType; + } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) { + boolean isBluetoothPlaying = + intent.getIntExtra( + BluetoothA2dp.SINK_STATE, + BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING; + mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying); } else { return; } @@ -1543,7 +1555,6 @@ public class WifiService extends IWifiManager.Stub { } private void sendStartMessage(boolean scanOnlyMode) { - if (DBG) Log.d(TAG, "sendStartMessage(" + scanOnlyMode + ")"); Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget(); } @@ -1561,6 +1572,9 @@ public class WifiService extends IWifiManager.Stub { } synchronized (mWifiHandler) { + if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) { + return; + } if (wifiShouldBeEnabled) { if (wifiShouldBeStarted) { sWakeLock.acquire(); @@ -1573,6 +1587,15 @@ public class WifiService extends IWifiManager.Stub { mContext.getContentResolver(), Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS, DEFAULT_WAKELOCK_TIMEOUT); + /* + * The following wakelock is held in order to ensure + * that the connectivity manager has time to fail over + * to the mobile data network. The connectivity manager + * releases it once mobile data connectivity has been + * established. If connectivity cannot be established, + * the wakelock is released after wakeLockTimeout + * milliseconds have elapsed. + */ sDriverStopWakeLock.acquire(); mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI); mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout); @@ -1585,18 +1608,13 @@ public class WifiService extends IWifiManager.Stub { } private void registerForBroadcasts() { - if (isAirplaneSensitive()) { - mContext.registerReceiver(mReceiver, - new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)); - } - mContext.registerReceiver(mReceiver, - new IntentFilter(Intent.ACTION_SCREEN_ON)); - mContext.registerReceiver(mReceiver, - new IntentFilter(Intent.ACTION_SCREEN_OFF)); - mContext.registerReceiver(mReceiver, - new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); - mContext.registerReceiver(mReceiver, - new IntentFilter(ACTION_DEVICE_IDLE)); + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(Intent.ACTION_SCREEN_ON); + intentFilter.addAction(Intent.ACTION_SCREEN_OFF); + intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); + intentFilter.addAction(ACTION_DEVICE_IDLE); + intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION); + mContext.registerReceiver(mReceiver, intentFilter); } private boolean isAirplaneSensitive() { @@ -1664,7 +1682,7 @@ public class WifiService extends IWifiManager.Stub { @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - if (mContext.checkCallingPermission(android.Manifest.permission.DUMP) + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump WifiService from from pid=" + Binder.getCallingPid() @@ -1672,11 +1690,14 @@ public class WifiService extends IWifiManager.Stub { return; } pw.println("Wi-Fi is " + stateName(mWifiState)); - pw.println("stay-awake conditions: " + + pw.println("Stay-awake conditions: " + Settings.System.getInt(mContext.getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0)); pw.println(); + pw.println("Internal state:"); + pw.println(mWifiStateTracker); + pw.println(); pw.println("Latest scan results:"); List scanResults = mWifiStateTracker.getScanResultsList(); if (scanResults != null && scanResults.size() != 0) { @@ -1786,13 +1807,6 @@ public class WifiService extends IWifiManager.Stub { return -1; } - private synchronized void clear() { - if (!mList.isEmpty()) { - mList.clear(); - updateWifiState(); - } - } - private void dump(PrintWriter pw) { for (WifiLock l : mList) { pw.print(" "); diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java index 7ed0aecdbc0300f6845d00fd90c8d1b5dca1d5f8..e4bd3c3d3705fb823f538a03297268f3b38deaf3 100644 --- a/services/java/com/android/server/WindowManagerService.java +++ b/services/java/com/android/server/WindowManagerService.java @@ -66,6 +66,7 @@ import android.os.Looper; import android.os.Message; import android.os.Parcel; import android.os.ParcelFileDescriptor; +import android.os.Power; import android.os.PowerManager; import android.os.Process; import android.os.RemoteException; @@ -122,7 +123,9 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo static final boolean DEBUG = false; static final boolean DEBUG_FOCUS = false; static final boolean DEBUG_ANIM = false; + static final boolean DEBUG_LAYERS = false; static final boolean DEBUG_INPUT = false; + static final boolean DEBUG_INPUT_METHOD = false; static final boolean DEBUG_VISIBILITY = false; static final boolean DEBUG_ORIENTATION = false; static final boolean DEBUG_APP_TRANSITIONS = false; @@ -202,6 +205,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo final boolean mHaveInputMethods; + final boolean mLimitedAlphaCompositing; + final WindowManagerPolicy mPolicy = PolicyManager.makeNewWindowManager(); final IActivityManager mActivityManager; @@ -306,6 +311,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo final float[] mTmpFloats = new float[9]; + boolean mSafeMode; boolean mDisplayEnabled = false; boolean mSystemBooted = false; int mRotation = 0; @@ -316,12 +322,16 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo boolean mLayoutNeeded = true; boolean mAnimationPending = false; - boolean mSurfacesChanged = false; boolean mDisplayFrozen = false; boolean mWindowsFreezingScreen = false; long mFreezeGcPending = 0; int mAppsFreezingScreen = 0; + // This is held as long as we have the screen frozen, to give us time to + // perform a rotation animation when turning off shows the lock screen which + // changes the orientation. + PowerManager.WakeLock mScreenFrozenLock; + // State management of app transitions. When we are preparing for a // transition, mNextAppTransition will be the kind of transition to // perform or TRANSIT_NONE if we are not waiting. If we are waiting, @@ -347,6 +357,9 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // This just indicates the window the input method is on top of, not // necessarily the window its input is going to. WindowState mInputMethodTarget = null; + WindowState mUpcomingInputMethodTarget = null; + boolean mInputMethodTargetWaitingAnim; + int mInputMethodAnimLayerAdjustment; WindowState mInputMethodWindow = null; final ArrayList mInputMethodDialogs = new ArrayList(); @@ -461,9 +474,15 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo boolean haveInputMethods) { mContext = context; mHaveInputMethods = haveInputMethods; + mLimitedAlphaCompositing = context.getResources().getBoolean( + com.android.internal.R.bool.config_sf_limitedAlpha); mPowerManager = pm; mPowerManager.setPolicy(mPolicy); + PowerManager pmc = (PowerManager)context.getSystemService(Context.POWER_SERVICE); + mScreenFrozenLock = pmc.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + "SCREEN_FROZEN"); + mScreenFrozenLock.setReferenceCounted(false); mActivityManager = ActivityManagerNative.getDefault(); mBatteryStats = BatteryStatsService.getService(); @@ -734,7 +753,16 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } } - int findDesiredInputMethodWindowIndexLocked() { + static boolean canBeImeTarget(WindowState w) { + final int fl = w.mAttrs.flags + & (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM); + if (fl == 0 || fl == (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM)) { + return w.isVisibleOrAdding(); + } + return false; + } + + int findDesiredInputMethodWindowIndexLocked(boolean willMove) { final ArrayList localmWindows = mWindows; final int N = localmWindows.size(); WindowState w = null; @@ -742,28 +770,120 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo while (i > 0) { i--; w = (WindowState)localmWindows.get(i); - final int fl = w.mAttrs.flags - & (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM); + //Log.i(TAG, "Checking window @" + i + " " + w + " fl=0x" - // + Integer.toHexString(fl)); - if (fl == 0 || fl == (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM)) { + // + Integer.toHexString(w.mAttrs.flags)); + if (canBeImeTarget(w)) { //Log.i(TAG, "Putting input method here!"); - if (w.isVisibleOrAdding()) { - break; + + // Yet more tricksyness! If this window is a "starting" + // window, we do actually want to be on top of it, but + // it is not -really- where input will go. So if the caller + // is not actually looking to move the IME, look down below + // for a real window to target... + if (!willMove + && w.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING + && i > 0) { + WindowState wb = (WindowState)localmWindows.get(i-1); + if (wb.mAppToken == w.mAppToken && canBeImeTarget(wb)) { + i--; + w = wb; + } } + break; } } + + mUpcomingInputMethodTarget = w; + + if (DEBUG_INPUT_METHOD) Log.v(TAG, "Desired input method target=" + + w + " willMove=" + willMove); + + if (willMove && w != null) { + final WindowState curTarget = mInputMethodTarget; + if (curTarget != null && curTarget.mAppToken != null) { + + // Now some fun for dealing with window animations that + // modify the Z order. We need to look at all windows below + // the current target that are in this app, finding the highest + // visible one in layering. + AppWindowToken token = curTarget.mAppToken; + WindowState highestTarget = null; + int highestPos = 0; + if (token.animating || token.animation != null) { + int pos = 0; + pos = localmWindows.indexOf(curTarget); + while (pos >= 0) { + WindowState win = (WindowState)localmWindows.get(pos); + if (win.mAppToken != token) { + break; + } + if (!win.mRemoved) { + if (highestTarget == null || win.mAnimLayer > + highestTarget.mAnimLayer) { + highestTarget = win; + highestPos = pos; + } + } + pos--; + } + } + + if (highestTarget != null) { + if (DEBUG_INPUT_METHOD) Log.v(TAG, "mNextAppTransition=" + + mNextAppTransition + " " + highestTarget + + " animating=" + highestTarget.isAnimating() + + " layer=" + highestTarget.mAnimLayer + + " new layer=" + w.mAnimLayer); + + if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) { + // If we are currently setting up for an animation, + // hold everything until we can find out what will happen. + mInputMethodTargetWaitingAnim = true; + mInputMethodTarget = highestTarget; + return highestPos + 1; + } else if (highestTarget.isAnimating() && + highestTarget.mAnimLayer > w.mAnimLayer) { + // If the window we are currently targeting is involved + // with an animation, and it is on top of the next target + // we will be over, then hold off on moving until + // that is done. + mInputMethodTarget = highestTarget; + return highestPos + 1; + } + } + } + } + //Log.i(TAG, "Placing input method @" + (i+1)); if (w != null) { - mInputMethodTarget = w; + if (willMove) { + RuntimeException e = new RuntimeException(); + e.fillInStackTrace(); + if (DEBUG_INPUT_METHOD) Log.w(TAG, "Moving IM target from " + + mInputMethodTarget + " to " + w, e); + mInputMethodTarget = w; + if (w.mAppToken != null) { + setInputMethodAnimLayerAdjustment(w.mAppToken.animLayerAdjustment); + } else { + setInputMethodAnimLayerAdjustment(0); + } + } return i+1; } - mInputMethodTarget = null; + if (willMove) { + RuntimeException e = new RuntimeException(); + e.fillInStackTrace(); + if (DEBUG_INPUT_METHOD) Log.w(TAG, "Moving IM target from " + + mInputMethodTarget + " to null", e); + mInputMethodTarget = null; + setInputMethodAnimLayerAdjustment(0); + } return -1; } void addInputMethodWindowToListLocked(WindowState win) { - int pos = findDesiredInputMethodWindowIndexLocked(); + int pos = findDesiredInputMethodWindowIndexLocked(true); if (pos >= 0) { win.mTargetAppToken = mInputMethodTarget.mAppToken; mWindows.add(pos, win); @@ -775,6 +895,33 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo moveInputMethodDialogsLocked(pos); } + void setInputMethodAnimLayerAdjustment(int adj) { + if (DEBUG_LAYERS) Log.v(TAG, "Setting im layer adj to " + adj); + mInputMethodAnimLayerAdjustment = adj; + WindowState imw = mInputMethodWindow; + if (imw != null) { + imw.mAnimLayer = imw.mLayer + adj; + if (DEBUG_LAYERS) Log.v(TAG, "IM win " + imw + + " anim layer: " + imw.mAnimLayer); + int wi = imw.mChildWindows.size(); + while (wi > 0) { + wi--; + WindowState cw = (WindowState)imw.mChildWindows.get(wi); + cw.mAnimLayer = cw.mLayer + adj; + if (DEBUG_LAYERS) Log.v(TAG, "IM win " + cw + + " anim layer: " + cw.mAnimLayer); + } + } + int di = mInputMethodDialogs.size(); + while (di > 0) { + di --; + imw = mInputMethodDialogs.get(di); + imw.mAnimLayer = imw.mLayer + adj; + if (DEBUG_LAYERS) Log.v(TAG, "IM win " + imw + + " anim layer: " + imw.mAnimLayer); + } + } + private int tmpRemoveWindowLocked(int interestingPos, WindowState win) { int wpos = mWindows.indexOf(win); if (wpos >= 0) { @@ -806,29 +953,55 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } } + void logWindowList(String prefix) { + int N = mWindows.size(); + while (N > 0) { + N--; + Log.v(TAG, prefix + "#" + N + ": " + mWindows.get(N)); + } + } + void moveInputMethodDialogsLocked(int pos) { ArrayList dialogs = mInputMethodDialogs; + final int N = dialogs.size(); + if (DEBUG_INPUT_METHOD) Log.v(TAG, "Removing " + N + " dialogs w/pos=" + pos); for (int i=0; i= 0) { final AppWindowToken targetAppToken = mInputMethodTarget.mAppToken; - WindowState wp = (WindowState)mWindows.get(pos); - if (wp == mInputMethodWindow) { - pos++; + if (pos < mWindows.size()) { + WindowState wp = (WindowState)mWindows.get(pos); + if (wp == mInputMethodWindow) { + pos++; + } } + if (DEBUG_INPUT_METHOD) Log.v(TAG, "Adding " + N + " dialogs at pos=" + pos); for (int i=0; i= 0) { // In this case, the input method windows are to be placed // immediately above the window they are targeting. @@ -884,9 +1057,21 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } if (imWin != null) { + if (DEBUG_INPUT_METHOD) { + Log.v(TAG, "Moving IM from " + imPos); + logWindowList(" "); + } imPos = tmpRemoveWindowLocked(imPos, imWin); + if (DEBUG_INPUT_METHOD) { + Log.v(TAG, "List after moving with new pos " + imPos + ":"); + logWindowList(" "); + } imWin.mTargetAppToken = mInputMethodTarget.mAppToken; reAddWindowLocked(imPos, imWin); + if (DEBUG_INPUT_METHOD) { + Log.v(TAG, "List after moving IM to " + imPos + ":"); + logWindowList(" "); + } if (DN > 0) moveInputMethodDialogsLocked(imPos+1); } else { moveInputMethodDialogsLocked(imPos); @@ -897,9 +1082,14 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // because they aren't currently associated with a focus window. if (imWin != null) { + if (DEBUG_INPUT_METHOD) Log.v(TAG, "Moving IM from " + imPos); tmpRemoveWindowLocked(0, imWin); imWin.mTargetAppToken = null; reAddWindowToListInOrderLocked(imWin); + if (DEBUG_INPUT_METHOD) { + Log.v(TAG, "List with no IM target:"); + logWindowList(" "); + } if (DN > 0) moveInputMethodDialogsLocked(-1);; } else { moveInputMethodDialogsLocked(-1);; @@ -915,7 +1105,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } void adjustInputMethodDialogsLocked() { - moveInputMethodDialogsLocked(findDesiredInputMethodWindowIndexLocked()); + moveInputMethodDialogsLocked(findDesiredInputMethodWindowIndexLocked(true)); } public int addWindow(Session session, IWindow client, @@ -975,7 +1165,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo + attrs.token + ". Aborting."); return WindowManagerImpl.ADD_BAD_APP_TOKEN; } - token = new WindowToken(attrs.token, -1); + token = new WindowToken(attrs.token, -1, false); addToken = true; } else if (attrs.type >= FIRST_APPLICATION_WINDOW && attrs.type <= LAST_APPLICATION_WINDOW) { @@ -1053,8 +1243,6 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo addWindowToListInOrderLocked(win, true); } - Binder.restoreCallingIdentity(origId); - win.mEnterAnimationPending = true; mPolicy.getContentInsetHintLw(attrs, outContentInsets); @@ -1066,8 +1254,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo res |= WindowManagerImpl.ADD_FLAG_APP_VISIBLE; } + boolean focusChanged = false; if (win.canReceiveKeys()) { - if (updateFocusedWindowLocked(UPDATE_FOCUS_WILL_ASSIGN_LAYERS)) { + if ((focusChanged=updateFocusedWindowLocked(UPDATE_FOCUS_WILL_ASSIGN_LAYERS)) + == true) { imMayMove = false; } } @@ -1082,16 +1272,34 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo //dump(); + if (focusChanged) { + if (mCurrentFocus != null) { + mKeyWaiter.handleNewWindowLocked(mCurrentFocus); + } + } + if (localLOGV) Log.v( TAG, "New client " + client.asBinder() + ": window=" + win); } + // sendNewConfiguration() checks caller permissions so we must call it with + // privilege. updateOrientationFromAppTokens() clears and resets the caller + // identity anyway, so it's safe to just clear & restore around this whole + // block. + final long origId = Binder.clearCallingIdentity(); if (reportNewConfig) { - final long origId = Binder.clearCallingIdentity(); sendNewConfiguration(); - Binder.restoreCallingIdentity(origId); + } else { + // Update Orientation after adding a window, only if the window needs to be + // displayed right away + if (win.isVisibleOrAdding()) { + if (updateOrientationFromAppTokens(null) != null) { + sendNewConfiguration(); + } + } } + Binder.restoreCallingIdentity(origId); return res; } @@ -1125,7 +1333,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo + " inPendingTransaction=" + (win.mAppToken != null ? win.mAppToken.inPendingTransaction : false) + " mDisplayFrozen=" + mDisplayFrozen); - + // Visibility of the removed window. Will be used later to update orientation later on. + boolean wasVisible = false; // First, see if we need to run an animation. If we do, we have // to hold off on removing the window until the animation is done. // If the display is frozen, just remove immediately, since the @@ -1133,7 +1342,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (win.mSurface != null && !mDisplayFrozen) { // If we are not currently running the exit animation, we // need to see about starting one. - if (win.isVisibleLw()) { + if (wasVisible=win.isWinVisibleLw()) { + int transit = WindowManagerPolicy.TRANSIT_EXIT; if (win.getAttrs().type == TYPE_APPLICATION_STARTING) { transit = WindowManagerPolicy.TRANSIT_PREVIEW_DONE; @@ -1161,6 +1371,12 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } removeWindowInnerLocked(session, win); + // Removing a visible window will effect the computed orientation + // So just update orientation if needed. + if (wasVisible && computeForcedAppOrientationLocked() + != mForcedAppOrientation) { + mH.sendMessage(mH.obtainMessage(H.COMPUTE_AND_SEND_NEW_CONFIGURATION)); + } updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL); Binder.restoreCallingIdentity(origId); } @@ -1169,6 +1385,12 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo mKeyWaiter.releasePendingPointerLocked(win.mSession); mKeyWaiter.releasePendingTrackballLocked(win.mSession); + win.mRemoved = true; + + if (mInputMethodTarget == win) { + moveInputMethodWindowsIfNeededLocked(false); + } + mPolicy.removeWindowLw(win); win.removeLocked(); @@ -1191,10 +1413,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo TAG, "**** Removing window " + win + ": count=" + token.windows.size()); if (token.windows.size() == 0) { - if (atoken != token) { + if (!token.explicit) { mTokenMap.remove(token.token); mTokenList.remove(token); - } else { + } else if (atoken != null) { atoken.firstWindowDrawn = false; } } @@ -1287,7 +1509,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo Surface outSurface) { boolean displayed = false; boolean inTouchMode; - + Configuration newConfig = null; long origId = Binder.clearCallingIdentity(); synchronized(mWindowMap) { @@ -1359,6 +1581,11 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo && !win.mCommitDrawPending && !mDisplayFrozen) { applyEnterAnimationLocked(win); } + if ((attrChanges&WindowManager.LayoutParams.FORMAT_CHANGED) != 0) { + // To change the format, we need to re-build the surface. + win.destroySurfaceLocked(); + displayed = true; + } try { Surface surface = win.createSurfaceLocked(); if (surface != null) { @@ -1393,7 +1620,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (win.getAttrs().type == TYPE_APPLICATION_STARTING) { transit = WindowManagerPolicy.TRANSIT_PREVIEW_DONE; } - if (win.isVisibleLw() && + if (win.isWinVisibleLw() && applyAnimationLocked(win, transit, false)) { win.mExiting = true; mKeyWaiter.finishedKey(session, client, true, @@ -1403,27 +1630,28 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // an exit. win.mExiting = true; } else { + if (mInputMethodWindow == win) { + mInputMethodWindow = null; + } win.destroySurfaceLocked(); } } } - if (mInputMethodWindow == win) { - mInputMethodWindow = null; - } outSurface.clear(); } - boolean assignLayers = false; - if (focusMayChange) { //System.out.println("Focus may change: " + win.mAttrs.getTitle()); if (updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES)) { - assignLayers = true; imMayMove = false; } //System.out.println("Relayout " + win + ": focus=" + mCurrentFocus); } + // updateFocusedWindowLocked() already assigned layers so we only need to + // reassign them at this point if the IM window state gets shuffled + boolean assignLayers = false; + if (imMayMove) { if (moveInputMethodWindowsIfNeededLocked(false)) { assignLayers = true; @@ -1435,6 +1663,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (assignLayers) { assignLayersLocked(); } + newConfig = updateOrientationFromAppTokensLocked(null); performLayoutAndPlaceSurfacesLocked(); if (win.mAppToken != null) { win.mAppToken.updateReportedVisibilityLocked(); @@ -1456,6 +1685,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo inTouchMode = mInTouchMode; } + if (newConfig != null) { + sendNewConfiguration(); + } + Binder.restoreCallingIdentity(origId); return (inTouchMode ? WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE : 0) @@ -1507,7 +1740,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo private boolean applyAnimationLocked(WindowState win, int transit, boolean isEntrance) { - if (win.mAnimating && win.mAnimationIsEntrance == isEntrance) { + if (win.mLocalAnimating && win.mAnimationIsEntrance == isEntrance) { // If we are trying to apply an animation, but already running // an animation of the same type, then just leave that one alone. return true; @@ -1553,6 +1786,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo Log.v(TAG, "Loaded animation " + a + " for " + win, e); } win.setAnimation(a); + win.mAnimationIsEntrance = isEntrance; } } else { win.clearAnimation(); @@ -1708,7 +1942,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo Log.w(TAG, "Attempted to add existing input method token: " + token); return; } - wtoken = new WindowToken(token, type); + wtoken = new WindowToken(token, type, true); mTokenMap.put(token, wtoken); mTokenList.add(wtoken); } @@ -1812,15 +2046,36 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } } - public Configuration updateOrientationFromAppTokens( - IBinder freezeThisOneIfNeeded) { - boolean changed = false; - synchronized(mWindowMap) { + public int getOrientationFromWindowsLocked() { + int pos = mWindows.size() - 1; + while (pos >= 0) { + WindowState wtoken = (WindowState) mWindows.get(pos); + pos--; + if (wtoken.mAppToken != null) { + // We hit an application window. so the orientation will be determined by the + // app window. No point in continuing further. + return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; + } + if (!wtoken.isVisibleLw()) { + continue; + } + int req = wtoken.mAttrs.screenOrientation; + if((req == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) || + (req == ActivityInfo.SCREEN_ORIENTATION_BEHIND)){ + continue; + } else { + return req; + } + } + return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; + } + + public int getOrientationFromAppTokensLocked() { int pos = mAppTokens.size() - 1; - int req = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; int curGroup = 0; int lastOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; boolean haveGroup = false; + boolean lastFullscreen = false; while (pos >= 0) { AppWindowToken wtoken = mAppTokens.get(pos); pos--; @@ -1835,13 +2090,21 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } else if (curGroup != wtoken.groupId) { // If we have hit a new application group, and the bottom // of the previous group didn't explicitly say to use - // the orientation behind it, then we'll stick with the + // the orientation behind it, and the last app was + // full screen, then we'll stick with the // user's orientation. - if (lastOrientation != ActivityInfo.SCREEN_ORIENTATION_BEHIND) { - break; + if (lastOrientation != ActivityInfo.SCREEN_ORIENTATION_BEHIND + && lastFullscreen) { + return lastOrientation; } } int or = wtoken.requestedOrientation; + // If this application is fullscreen, then just take whatever + // orientation it has and ignores whatever is under it. + lastFullscreen = wtoken.appFullscreen; + if (lastFullscreen) { + return or; + } // If this application has requested an explicit orientation, // then use it. if (or == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || @@ -1849,16 +2112,47 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo or == ActivityInfo.SCREEN_ORIENTATION_SENSOR || or == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR || or == ActivityInfo.SCREEN_ORIENTATION_USER) { - req = or; - break; + return or; } } + return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; + } + + public Configuration updateOrientationFromAppTokens( + IBinder freezeThisOneIfNeeded) { + Configuration config; + long ident = Binder.clearCallingIdentity(); + synchronized(mWindowMap) { + config = updateOrientationFromAppTokensLocked(freezeThisOneIfNeeded); + } + if (config != null) { + mLayoutNeeded = true; + performLayoutAndPlaceSurfacesLocked(); + } + Binder.restoreCallingIdentity(ident); + return config; + } + + /* + * The orientation is computed from non-application windows first. If none of + * the non-application windows specify orientation, the orientation is computed from + * application tokens. + * @see android.view.IWindowManager#updateOrientationFromAppTokens( + * android.os.IBinder) + */ + Configuration updateOrientationFromAppTokensLocked( + IBinder freezeThisOneIfNeeded) { + boolean changed = false; + long ident = Binder.clearCallingIdentity(); + try { + int req = computeForcedAppOrientationLocked(); + if (req != mForcedAppOrientation) { changed = true; mForcedAppOrientation = req; //send a message to Policy indicating orientation change to take //action like disabling/enabling sensors etc., - mPolicy.setCurrentOrientation(req); + mPolicy.setCurrentOrientationLw(req); } if (changed) { @@ -1873,19 +2167,24 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo ActivityInfo.CONFIG_ORIENTATION); } } - Configuration config = computeNewConfigurationLocked(); - if (config != null) { - mLayoutNeeded = true; - performLayoutAndPlaceSurfacesLocked(); - } - return config; + return computeNewConfiguration(); } } + } finally { + Binder.restoreCallingIdentity(ident); } return null; } + int computeForcedAppOrientationLocked() { + int req = getOrientationFromWindowsLocked(); + if (req == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) { + req = getOrientationFromAppTokensLocked(); + } + return req; + } + public void setAppOrientation(IApplicationToken token, int requestedOrientation) { if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS, "setAppOrientation()")) { @@ -2088,7 +2387,6 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES); - assignLayersLocked(); mLayoutNeeded = true; performLayoutAndPlaceSurfacesLocked(); Binder.restoreCallingIdentity(origId); @@ -2230,7 +2528,6 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (changed && performLayout) { mLayoutNeeded = true; updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES); - assignLayersLocked(); performLayoutAndPlaceSurfacesLocked(); } } @@ -2559,7 +2856,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo boolean added = false; for (int j=0; j= 0) { + if (!added && cwin.mSubLayer >= 0) { mWindows.add(index, win); index++; added = true; @@ -2611,7 +2908,6 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (DEBUG_REORDER) Log.v(TAG, "Final window list:"); if (DEBUG_REORDER) dumpWindowsLocked(); updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES); - assignLayersLocked(); mLayoutNeeded = true; performLayoutAndPlaceSurfacesLocked(); } @@ -2659,7 +2955,6 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES); - assignLayersLocked(); mLayoutNeeded = true; performLayoutAndPlaceSurfacesLocked(); @@ -2871,6 +3166,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo return KeyInputQueue.getKeycodeState(devid, sw); } + public boolean hasKeys(int[] keycodes, boolean[] keyExists) { + return KeyInputQueue.hasKeys(keycodes, keyExists); + } + public void enableScreenAfterBoot() { synchronized(mWindowMap) { if (mSystemBooted) { @@ -2987,18 +3286,19 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } else { mRequestedRotation = rotation; } - if (DEBUG_ORIENTATION) Log.v(TAG, "Overwriting rotation value from "+rotation); - rotation = mPolicy.rotationForOrientation(mForcedAppOrientation); - if (DEBUG_ORIENTATION) Log.v(TAG, "new rotation is set to "+rotation); + if (DEBUG_ORIENTATION) Log.v(TAG, "Overwriting rotation value from " + rotation); + rotation = mPolicy.rotationForOrientationLw(mForcedAppOrientation, + mRotation, mDisplayEnabled); + if (DEBUG_ORIENTATION) Log.v(TAG, "new rotation is set to " + rotation); changed = mDisplayEnabled && mRotation != rotation; if (changed) { - mRotation = rotation; if (DEBUG_ORIENTATION) Log.v(TAG, "Rotation changed to " + rotation + " from " + mRotation + " (forceApp=" + mForcedAppOrientation + ", req=" + mRequestedRotation + ")"); + mRotation = rotation; mWindowsFreezingScreen = true; mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT); mH.sendMessageDelayed(mH.obtainMessage(H.WINDOW_FREEZE_TIMEOUT), @@ -3298,21 +3598,18 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo return null; } + /* + * Instruct the Activity Manager to fetch the current configuration and broadcast + * that to config-changed listeners if appropriate. + */ void sendNewConfiguration() { - Configuration config; - synchronized (mWindowMap) { - config = computeNewConfigurationLocked(); - } - - if (config != null) { - try { - mActivityManager.updateConfiguration(config); - } catch (RemoteException e) { - } + try { + mActivityManager.updateConfiguration(null); + } catch (RemoteException e) { } } - Configuration computeNewConfigurationLocked() { + public Configuration computeNewConfiguration() { synchronized (mWindowMap) { if (mDisplay == null) { return null; @@ -3669,6 +3966,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo synchronized(mWindowMap) { mKeyWaiter.bindTargetWindowLocked(focus); } + + // NOSHIP extra state logging + mKeyWaiter.recordDispatchState(event, focus); + // END NOSHIP try { if (DEBUG_INPUT || DEBUG_FOCUS) { @@ -3812,6 +4113,58 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo * but not the other way around. */ final class KeyWaiter { + // NOSHIP debugging + public class DispatchState { + private KeyEvent event; + private WindowState focus; + private long time; + private WindowState lastWin; + private IBinder lastBinder; + private boolean finished; + private boolean gotFirstWindow; + private boolean eventDispatching; + private long timeToSwitch; + private boolean wasFrozen; + private boolean focusPaused; + private WindowState curFocus; + + DispatchState(KeyEvent theEvent, WindowState theFocus) { + focus = theFocus; + event = theEvent; + time = System.currentTimeMillis(); + // snapshot KeyWaiter state + lastWin = mLastWin; + lastBinder = mLastBinder; + finished = mFinished; + gotFirstWindow = mGotFirstWindow; + eventDispatching = mEventDispatching; + timeToSwitch = mTimeToSwitch; + wasFrozen = mWasFrozen; + curFocus = mCurrentFocus; + // cache the paused state at ctor time as well + if (theFocus == null || theFocus.mToken == null) { + Log.i(TAG, "focus " + theFocus + " mToken is null at event dispatch!"); + focusPaused = false; + } else { + focusPaused = theFocus.mToken.paused; + } + } + + public String toString() { + return "{{" + event + " to " + focus + " @ " + time + + " lw=" + lastWin + " lb=" + lastBinder + + " fin=" + finished + " gfw=" + gotFirstWindow + + " ed=" + eventDispatching + " tts=" + timeToSwitch + + " wf=" + wasFrozen + " fp=" + focusPaused + + " mcf=" + mCurrentFocus + "}}"; + } + }; + private DispatchState mDispatchState = null; + public void recordDispatchState(KeyEvent theEvent, WindowState theFocus) { + mDispatchState = new DispatchState(theEvent, theFocus); + } + // END NOSHIP + public static final int RETURN_NOTHING = 0; public static final int RETURN_PENDING_POINTER = 1; public static final int RETURN_PENDING_TRACKBALL = 2; @@ -3923,7 +4276,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo + " targetIsNew=" + targetIsNew + " paused=" + (targetWin != null ? targetWin.mToken.paused : false) - + " mFocusedApp=" + mFocusedApp); + + " mFocusedApp=" + mFocusedApp + + " mCurrentFocus=" + mCurrentFocus); targetApp = targetWin != null ? targetWin.mAppToken : mFocusedApp; @@ -3952,7 +4306,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo wait(curTimeout); if (DEBUG_INPUT) Log.v(TAG, "Finished waiting @" + SystemClock.uptimeMillis() + " startTime=" - + startTime + " switchTime=" + mTimeToSwitch); + + startTime + " switchTime=" + mTimeToSwitch + + " target=" + targetWin + " mLW=" + mLastWin + + " mLB=" + mLastBinder + " fin=" + mFinished + + " mCurrentFocus=" + mCurrentFocus); } catch (InterruptedException e) { } } @@ -3973,6 +4330,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo Log.w(TAG, "Key dispatching timed out sending to " + (targetWin != null ? targetWin.mAttrs.getTitle() : "")); + // NOSHIP debugging + Log.w(TAG, "Dispatch state: " + mDispatchState); + Log.w(TAG, "Current state: " + new DispatchState(nextKey, targetWin)); + // END NOSHIP //dump(); if (targetWin != null) { at = targetWin.getAppToken(); @@ -4355,7 +4716,6 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo newWindow.mToken.paused = false; mGotFirstWindow = true; - boolean doNotify = true; if ((newWindow.mAttrs.flags & FLAG_SYSTEM_ERROR) != 0) { if (DEBUG_INPUT) Log.v(TAG, @@ -4372,20 +4732,21 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo TAG, "Last win layer=" + mLastWin.mLayer + ", new win layer=" + newWindow.mLayer); if (newWindow.mLayer >= mLastWin.mLayer) { - if (!mLastWin.canReceiveKeys()) { - mLastWin.mToken.paused = false; - doFinishedKeyLocked(true); // does a notifyAll() - doNotify = false; - } - } else { - // the new window is lower; no need to wake key waiters - doNotify = false; + // The new window is above the old; finish pending input to the last + // window and start directing it to the new one. + mLastWin.mToken.paused = false; + doFinishedKeyLocked(true); // does a notifyAll() } + // Either the new window is lower, so there is no need to wake key waiters, + // or we just finished key input to the previous window, which implicitly + // notified the key waiters. In both cases, we don't need to issue the + // notification here. + return; } - if (doNotify) { - notifyAll(); - } + // Now that we've put a new window state in place, make the event waiter + // take notice and retarget its attentions. + notifyAll(); } } @@ -4478,8 +4839,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo KeyQ() { super(mContext); PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); - mHoldingScreen = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK - | PowerManager.ON_AFTER_RELEASE, "KEEP_SCREEN_ON_FLAG"); + mHoldingScreen = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, + "KEEP_SCREEN_ON_FLAG"); mHoldingScreen.setReferenceCounted(false); } @@ -4602,14 +4963,18 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (holding) { mHoldingScreen.acquire(); } else { - long curTime = SystemClock.uptimeMillis(); - mPowerManager.userActivity(curTime, false, LocalPowerManager.OTHER_EVENT); + mPolicy.screenOnStoppedLw(); mHoldingScreen.release(); } } } }; + public boolean detectSafeMode() { + mSafeMode = mPolicy.detectSafeMode(); + return mSafeMode; + } + public void systemReady() { mPolicy.systemReady(); } @@ -4923,6 +5288,19 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } } + public boolean performHapticFeedback(IWindow window, int effectId, + boolean always) { + synchronized(mWindowMap) { + long ident = Binder.clearCallingIdentity(); + try { + return mPolicy.performHapticFeedbackLw( + windowForClientLocked(this, window), effectId, always); + } finally { + Binder.restoreCallingIdentity(ident); + } + } + } + void windowAddedLocked() { if (mSurfaceSession == null) { if (localLOGV) Log.v( @@ -5083,9 +5461,11 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // Currently running animation. boolean mAnimating; + boolean mLocalAnimating; Animation mAnimation; boolean mAnimationIsEntrance; boolean mHasTransformation; + boolean mHasLocalTransformation; final Transformation mTransformation = new Transformation(); // This is set after IWindowSession.relayout() has been called at @@ -5125,6 +5505,9 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // been updated for the new orientation. boolean mOrientationChanging; + // Is this window now (or just being) removed? + boolean mRemoved; + WindowState(Session s, IWindow c, WindowToken token, WindowState attachedWindow, WindowManager.LayoutParams a, int viewVisibility) { @@ -5292,6 +5675,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo return mFrame; } + public Rect getShownFrameLw() { + return mShownFrame; + } + public Rect getDisplayFrameLw() { return mDisplayFrame; } @@ -5344,6 +5731,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (localLOGV) Log.v( TAG, "Setting animation in " + this + ": " + anim); mAnimating = false; + mLocalAnimating = false; mAnimation = anim; mAnimation.restrictDuration(MAX_ANIMATION_DURATION); mAnimation.scaleCurrentDuration(mWindowAnimationScale); @@ -5352,6 +5740,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo public void clearAnimation() { if (mAnimation != null) { mAnimating = true; + mLocalAnimating = false; mAnimation = null; } } @@ -5580,13 +5969,15 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (!mDrawPending && !mCommitDrawPending && mAnimation != null) { mHasTransformation = true; - if (!mAnimating) { + mHasLocalTransformation = true; + if (!mLocalAnimating) { if (DEBUG_ANIM) Log.v( TAG, "Starting animation in " + this + " @ " + currentTime + ": ww=" + mFrame.width() + " wh=" + mFrame.height() + " dw=" + dw + " dh=" + dh + " scale=" + mWindowAnimationScale); mAnimation.initialize(mFrame.width(), mFrame.height(), dw, dh); mAnimation.setStartTime(currentTime); + mLocalAnimating = true; mAnimating = true; } mTransformation.clear(); @@ -5595,9 +5986,6 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (DEBUG_ANIM) Log.v( TAG, "Stepped animation in " + this + ": more=" + more + ", xform=" + mTransformation); - if (mAppToken != null && mAppToken.hasTransformation) { - mTransformation.compose(mAppToken.transformation); - } if (more) { // we're not done! return true; @@ -5608,10 +5996,19 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo mAnimation = null; //WindowManagerService.this.dump(); } - if (mAppToken != null && mAppToken.hasTransformation) { + mHasLocalTransformation = false; + if ((!mLocalAnimating || mAnimationIsEntrance) && mAppToken != null + && mAppToken.hasTransformation) { + // When our app token is animating, we kind-of pretend like + // we are as well. Note the mLocalAnimating mAnimationIsEntrance + // part of this check means that we will only do this if + // our window is not currently exiting, or it is not + // locally animating itself. The idea being that one that + // is exiting and doing a local animation should be removed + // once that animation is done. mAnimating = true; mHasTransformation = true; - mTransformation.set(mAppToken.transformation); + mTransformation.clear(); return false; } else if (mHasTransformation) { // Little trick to get through the path below to act like @@ -5624,10 +6021,11 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // If the display is frozen, and there is a pending animation, // clear it and make sure we run the cleanup code. mAnimating = true; + mLocalAnimating = true; mAnimation = null; } - if (!mAnimating) { + if (!mAnimating && !mLocalAnimating) { return false; } @@ -5637,9 +6035,16 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo + (mAppToken != null ? mAppToken.reportedVisible : false)); mAnimating = false; + mLocalAnimating = false; mAnimation = null; mAnimLayer = mLayer; + if (mIsImWindow) { + mAnimLayer += mInputMethodAnimLayerAdjustment; + } + if (DEBUG_LAYERS) Log.v(TAG, "Stepping win " + this + + " anim layer: " + mAnimLayer); mHasTransformation = false; + mHasLocalTransformation = false; mPolicyVisibility = mPolicyVisibilityAfterAnim; mTransformation.clear(); if (mHasDrawn @@ -5714,10 +6119,15 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } void computeShownFrameLocked() { - final boolean selfTransformation = mHasTransformation; - final boolean attachedTransformation = (mAttachedWindow != null - && mAttachedWindow.mHasTransformation); - if (selfTransformation || attachedTransformation) { + final boolean selfTransformation = mHasLocalTransformation; + Transformation attachedTransformation = + (mAttachedWindow != null && mAttachedWindow.mHasLocalTransformation) + ? mAttachedWindow.mTransformation : null; + Transformation appTransformation = + (mAppToken != null && mAppToken.hasTransformation) + ? mAppToken.transformation : null; + if (selfTransformation || attachedTransformation != null + || appTransformation != null) { // cache often used attributes locally final Rect frame = mFrame; final float tmpFloats[] = mTmpFloats; @@ -5728,8 +6138,11 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (selfTransformation) { tmpMatrix.preConcat(mTransformation.getMatrix()); } - if (attachedTransformation) { - tmpMatrix.preConcat(mAttachedWindow.mTransformation.getMatrix()); + if (attachedTransformation != null) { + tmpMatrix.preConcat(attachedTransformation.getMatrix()); + } + if (appTransformation != null) { + tmpMatrix.preConcat(appTransformation.getMatrix()); } // "convert" it into SurfaceFlinger's format @@ -5755,15 +6168,19 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // transforming since it is more important to have that // animation be smooth. mShownAlpha = mAlpha; - if (false && (!PixelFormat.formatHasAlpha(mAttrs.format) + if (!mLimitedAlphaCompositing + || (!PixelFormat.formatHasAlpha(mAttrs.format) || (isIdentityMatrix(mDsDx, mDtDx, mDsDy, mDtDy) && x == frame.left && y == frame.top))) { //Log.i(TAG, "Applying alpha transform"); if (selfTransformation) { mShownAlpha *= mTransformation.getAlpha(); } - if (attachedTransformation) { - mShownAlpha *= mAttachedWindow.mTransformation.getAlpha(); + if (attachedTransformation != null) { + mShownAlpha *= attachedTransformation.getAlpha(); + } + if (appTransformation != null) { + mShownAlpha *= appTransformation.getAlpha(); } } else { //Log.i(TAG, "Not applying alpha transform"); @@ -5787,7 +6204,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo /** * Is this window visible? It is not visible if there is no * surface, or we are in the process of running an exit animation - * that will remove the surface. + * that will remove the surface, or its app token has been hidden. */ public boolean isVisibleLw() { final AppWindowToken atoken = mAppToken; @@ -5796,6 +6213,18 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo && !mExiting && !mDestroying; } + /** + * Is this window visible, ignoring its app token? It is not visible + * if there is no surface, or we are in the process of running an exit animation + * that will remove the surface. + */ + public boolean isWinVisibleLw() { + final AppWindowToken atoken = mAppToken; + return mSurface != null && mPolicyVisibility && !mAttachedHidden + && (atoken == null || !atoken.hiddenRequested || atoken.animating) + && !mExiting && !mDestroying; + } + /** * The same as isVisible(), but follows the current hidden state of * the associated app token, not the pending requested hidden state. @@ -5877,10 +6306,16 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } public boolean fillsScreenLw(int screenWidth, int screenHeight, - boolean shownFrame) { + boolean shownFrame, boolean onlyOpaque) { if (mSurface == null) { return false; } + if (mAppToken != null && !mAppToken.appFullscreen) { + return false; + } + if (onlyOpaque && mAttrs.format != PixelFormat.OPAQUE) { + return false; + } final Rect frame = shownFrame ? mShownFrame : mFrame; if (frame.left <= 0 && frame.top <= 0 && frame.right >= screenWidth @@ -5944,21 +6379,23 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo return mHasDrawn; } - public void showLw(boolean doAnimation) { + public boolean showLw(boolean doAnimation) { if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim) { - mSurfacesChanged = true; mPolicyVisibility = true; mPolicyVisibilityAfterAnim = true; if (doAnimation) { applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_ENTER, true); } requestAnimationLocked(0); + return true; } + return false; } - public void hideLw(boolean doAnimation) { - if (mPolicyVisibility || mPolicyVisibilityAfterAnim) { - mSurfacesChanged = true; + public boolean hideLw(boolean doAnimation) { + boolean current = doAnimation ? mPolicyVisibilityAfterAnim + : mPolicyVisibility; + if (current) { if (doAnimation) { applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_EXIT, false); if (mAnimation == null) { @@ -5968,10 +6405,13 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (doAnimation) { mPolicyVisibilityAfterAnim = false; } else { + mPolicyVisibilityAfterAnim = false; mPolicyVisibility = false; } requestAnimationLocked(0); + return true; } + return false; } void dump(PrintWriter pw, String prefix) { @@ -6020,6 +6460,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo pw.println(prefix + "mShownAlpha=" + mShownAlpha + " mAlpha=" + mAlpha + " mLastAlpha=" + mLastAlpha); pw.println(prefix + "mAnimating=" + mAnimating + + " mLocalAnimating=" + mLocalAnimating + " mAnimationIsEntrance=" + mAnimationIsEntrance + " mAnimation=" + mAnimation); pw.println(prefix + "XForm: has=" + mHasTransformation @@ -6030,7 +6471,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo + " mHasDrawn=" + mHasDrawn); pw.println(prefix + "mExiting=" + mExiting + " mRemoveOnExit=" + mRemoveOnExit - + " mDestroying=" + mDestroying); + + " mDestroying=" + mDestroying + + " mRemoved=" + mRemoved); pw.println(prefix + "mOrientationChanging=" + mOrientationChanging + " mAppFreezing=" + mAppFreezing); } @@ -6039,7 +6481,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo public String toString() { return "Window{" + Integer.toHexString(System.identityHashCode(this)) - + " " + mAttrs.getTitle() + "}"; + + " " + mAttrs.getTitle() + " paused=" + mToken.paused + "}"; } } @@ -6054,6 +6496,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // The type of window this token is for, as per WindowManager.LayoutParams. final int windowType; + // Set if this token was explicitly added by a client, so should + // not be removed when all windows are removed. + final boolean explicit; + // If this is an AppWindowToken, this is non-null. AppWindowToken appWindowToken; @@ -6069,9 +6515,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // Temporary for finding which tokens no longer have visible windows. boolean hasVisible; - WindowToken(IBinder _token, int type) { + WindowToken(IBinder _token, int type, boolean _explicit) { token = _token; windowType = type; + explicit = _explicit; } void dump(PrintWriter pw, String prefix) { @@ -6151,7 +6598,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo boolean firstWindowDrawn; AppWindowToken(IApplicationToken _token) { - super(_token.asBinder(), WindowManager.LayoutParams.TYPE_APPLICATION); + super(_token.asBinder(), + WindowManager.LayoutParams.TYPE_APPLICATION, true); appWindowToken = this; appToken = _token; } @@ -6198,17 +6646,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo for (int i=0; i 0) { - di --; - imw = mInputMethodDialogs.get(di); - imw.mAnimLayer = imw.mLayer + adj; - } + setInputMethodAnimLayerAdjustment(adj); } } } @@ -6295,7 +6736,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo clearAnimation(); animating = false; - + if (mInputMethodTarget != null && mInputMethodTarget.mAppToken == this) { + moveInputMethodWindowsIfNeededLocked(true); + } + if (DEBUG_ANIM) Log.v( TAG, "Animation done in " + this + ": reportedVisible=" + reportedVisible); @@ -6503,6 +6947,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo public static final int FORCE_GC = 15; public static final int ENABLE_SCREEN = 16; public static final int APP_FREEZE_TIMEOUT = 17; + public static final int COMPUTE_AND_SEND_NEW_CONFIGURATION = 18; private Session mLastReportedHold; @@ -6519,6 +6964,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo synchronized(mWindowMap) { lastFocus = mLastFocus; newFocus = mCurrentFocus; + if (lastFocus == newFocus) { + // Focus is not changing, so nothing to do. + return; + } mLastFocus = newFocus; //Log.i(TAG, "Focus moving from " + lastFocus // + " to " + newFocus); @@ -6829,6 +7278,13 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo break; } + case COMPUTE_AND_SEND_NEW_CONFIGURATION: { + if (updateOrientationFromAppTokens(null) != null) { + sendNewConfiguration(); + } + break; + } + } } } @@ -6848,12 +7304,15 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo synchronized (mWindowMap) { // The focus for the client is the window immediately below // where we would place the input method window. - int idx = findDesiredInputMethodWindowIndexLocked(); + int idx = findDesiredInputMethodWindowIndexLocked(false); + WindowState imFocus; if (idx > 0) { - WindowState imFocus = (WindowState)mWindows.get(idx-1); - if (imFocus != null && imFocus.mSession.mClient != null && - imFocus.mSession.mClient.asBinder() == client.asBinder()) { - return true; + imFocus = (WindowState)mWindows.get(idx-1); + if (imFocus != null) { + if (imFocus.mSession.mClient != null && + imFocus.mSession.mClient.asBinder() == client.asBinder()) { + return true; + } } } } @@ -6888,13 +7347,6 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } private final void assignLayersLocked() { - if (mInLayout) { - if (Config.DEBUG) { - throw new RuntimeException("Recursive call!"); - } - return; - } - int N = mWindows.size(); int curBaseLayer = 0; int curLayer = 0; @@ -6916,6 +7368,11 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } else { w.mAnimLayer = w.mLayer; } + if (w.mIsImWindow) { + w.mAnimLayer += mInputMethodAnimLayerAdjustment; + } + if (DEBUG_LAYERS) Log.v(TAG, "Assign layer " + w + ": " + + w.mAnimLayer); //System.out.println( // "Assigned layer " + curLayer + " to " + w.mClient.asBinder()); } @@ -6927,6 +7384,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (Config.DEBUG) { throw new RuntimeException("Recursive call!"); } + Log.w(TAG, "performLayoutAndPlaceSurfacesLocked called while in layout"); return; } @@ -6999,7 +7457,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo WindowState win = (WindowState) mWindows.get(i); boolean gone = win.mViewVisibility == View.GONE - || !win.mRelayoutCalled; + || !win.mRelayoutCalled + || win.mToken.hidden; // If this view is GONE, then skip it -- keep the current // frame, and let the caller know so they can ignore it @@ -7073,6 +7532,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo boolean orientationChangeComplete = true; Session holdScreen = null; + float screenBrightness = -1; boolean focusDisplayed = false; boolean animating = false; @@ -7285,6 +7745,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // This has changed the visibility of windows, so perform // a new layout to get them all up-to-date. mLayoutNeeded = true; + moveInputMethodWindowsIfNeededLocked(true); performLayoutLockedInner(); updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES); @@ -7297,12 +7758,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo final boolean someoneLosingFocus = mLosingFocus.size() != 0; - mSurfacesChanged = false; boolean obscured = false; boolean blurring = false; boolean dimming = false; boolean covered = false; - int tint = 0; for (i=N-1; i>=0; i--) { WindowState w = (WindowState)mWindows.get(i); @@ -7558,9 +8017,13 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // Update effect. if (!obscured) { - if (w.mSurface != null && - (attrFlags&FLAG_KEEP_SCREEN_ON) != 0) { - holdScreen = w.mSession; + if (w.mSurface != null) { + if ((attrFlags&FLAG_KEEP_SCREEN_ON) != 0) { + holdScreen = w.mSession; + } + if (w.mAttrs.screenBrightness >= 0 && screenBrightness < 0) { + screenBrightness = w.mAttrs.screenBrightness; + } } if (w.isFullscreenOpaque(dw, dh)) { // This window completely covers everything behind it, @@ -7619,6 +8082,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo // the user. duration *= DIM_DURATION_MULTIPLIER; } + if (duration < 1) { + // Don't divide by zero + duration = 1; + } mDimTargetAlpha = target; mDimDeltaPerMs = (mDimTargetAlpha-mDimCurrentAlpha) / duration; @@ -7673,7 +8140,10 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo mDimCurrentAlpha += mDimDeltaPerMs * (currentTime-mLastDimAnimTime); boolean more = true; - if (mDimDeltaPerMs > 0) { + if (mDisplayFrozen) { + // If the display is frozen, there is no reason to animate. + more = false; + } else if (mDimDeltaPerMs > 0) { if (mDimCurrentAlpha > mDimTargetAlpha) { more = false; } @@ -7767,6 +8237,9 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo i--; WindowState win = mDestroySurface.get(i); win.mDestroying = false; + if (mInputMethodWindow == win) { + mInputMethodWindow = null; + } win.destroySurfaceLocked(); } while (i > 0); mDestroySurface.clear(); @@ -7796,6 +8269,12 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo requestAnimationLocked(currentTime+(1000/60)-SystemClock.uptimeMillis()); } mQueue.setHoldScreenLocked(holdScreen != null); + if (screenBrightness < 0 || screenBrightness > 1.0f) { + mPowerManager.setScreenBrightnessOverride(-1); + } else { + mPowerManager.setScreenBrightnessOverride((int) + (screenBrightness * Power.BRIGHTNESS_ON)); + } if (holdScreen != mHoldingScreenOn) { mHoldingScreenOn = holdScreen; Message m = mH.obtainMessage(H.HOLD_SCREEN_CHANGED, holdScreen); @@ -7811,7 +8290,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo } /** - * Have the surface flinger show a surface, robustly dealing wit + * Have the surface flinger show a surface, robustly dealing with * error conditions. In particular, if there is not enough memory * to show the surface, then we will try to get rid of other surfaces * in order to succeed. @@ -7925,31 +8404,33 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo if (mCurrentFocus != newFocus) { // This check makes sure that we don't already have the focus // change message pending. - if (mLastFocus == mCurrentFocus) { - mH.sendEmptyMessage(H.REPORT_FOCUS_CHANGE); - } + mH.removeMessages(H.REPORT_FOCUS_CHANGE); + mH.sendEmptyMessage(H.REPORT_FOCUS_CHANGE); if (localLOGV) Log.v( TAG, "Changing focus from " + mCurrentFocus + " to " + newFocus); final WindowState oldFocus = mCurrentFocus; mCurrentFocus = newFocus; mLosingFocus.remove(newFocus); - if (newFocus != null) { - mKeyWaiter.handleNewWindowLocked(newFocus); - } final WindowState imWindow = mInputMethodWindow; if (newFocus != imWindow && oldFocus != imWindow) { - moveInputMethodWindowsIfNeededLocked( + if (moveInputMethodWindowsIfNeededLocked( mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS && - mode != UPDATE_FOCUS_WILL_PLACE_SURFACES); - mLayoutNeeded = true; + mode != UPDATE_FOCUS_WILL_PLACE_SURFACES)) { + mLayoutNeeded = true; + } if (mode == UPDATE_FOCUS_PLACING_SURFACES) { performLayoutLockedInner(); - } else if (mode != UPDATE_FOCUS_WILL_PLACE_SURFACES) { - mLayoutNeeded = true; - performLayoutAndPlaceSurfacesLocked(); + } else if (mode == UPDATE_FOCUS_WILL_PLACE_SURFACES) { + // Client will do the layout, but we need to assign layers + // for handleNewWindowLocked() below. + assignLayersLocked(); } } + + if (newFocus != null && mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS) { + mKeyWaiter.handleNewWindowLocked(newFocus); + } return true; } return false; @@ -8029,6 +8510,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo return; } + mScreenFrozenLock.acquire(); + long now = SystemClock.uptimeMillis(); //Log.i(TAG, "Freezing, gc pending: " + mFreezeGcPending + ", now " + now); if (mFreezeGcPending != 0) { @@ -8084,6 +8567,8 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo mH.removeMessages(H.FORCE_GC); mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC), 2000); + + mScreenFrozenLock.release(); } @Override @@ -8218,13 +8703,14 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo pw.println(" mSystemBooted=" + mSystemBooted + " mDisplayEnabled=" + mDisplayEnabled); pw.println(" mLayoutNeeded=" + mLayoutNeeded - + " mSurfacesChanged=" + mSurfacesChanged + " mBlurShown=" + mBlurShown); pw.println(" mDimShown=" + mDimShown + " current=" + mDimCurrentAlpha + " target=" + mDimTargetAlpha + " delta=" + mDimDeltaPerMs + " lastAnimTime=" + mLastDimAnimTime); + pw.println(" mInputMethodAnimLayerAdjustment=" + + mInputMethodAnimLayerAdjustment); pw.println(" mDisplayFrozen=" + mDisplayFrozen + " mWindowsFreezingScreen=" + mWindowsFreezingScreen + " mAppsFreezingScreen=" + mAppsFreezingScreen); @@ -8249,7 +8735,7 @@ public class WindowManagerService extends IWindowManager.Stub implements Watchdo + " mLastBinder=" + mKeyWaiter.mLastBinder); pw.println(" mFinished=" + mKeyWaiter.mFinished + " mGotFirstWindow=" + mKeyWaiter.mGotFirstWindow - + " mEventDispatching" + mKeyWaiter.mEventDispatching + + " mEventDispatching=" + mKeyWaiter.mEventDispatching + " mTimeToSwitch=" + mKeyWaiter.mTimeToSwitch); } } diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java index 361c7f7b02d3fe7fbdd4cb0fe329f05f224f2cc7..9d720d1a4896de265c6a3c9edb260b8fac6c6764 100644 --- a/services/java/com/android/server/am/ActivityManagerService.java +++ b/services/java/com/android/server/am/ActivityManagerService.java @@ -48,6 +48,7 @@ import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; +import android.content.pm.ConfigurationInfo; import android.content.pm.IPackageDataObserver; import android.content.pm.IPackageManager; import android.content.pm.InstrumentationInfo; @@ -96,6 +97,7 @@ import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; +import java.lang.IllegalStateException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; @@ -157,7 +159,12 @@ public final class ActivityManagerService extends ActivityManagerNative implemen static final int LOG_AM_BROADCAST_DISCARD_APP = 30025; static final int LOG_AM_CREATE_SERVICE = 30030; static final int LOG_AM_DESTROY_SERVICE = 30031; - + static final int LOG_AM_PROCESS_CRASHED_TOO_MUCH = 30032; + static final int LOG_AM_DROP_PROCESS = 30033; + static final int LOG_AM_SERVICE_CRASHED_TOO_MUCH = 30034; + static final int LOG_AM_SCHEDULE_SERVICE_RESTART = 30035; + static final int LOG_AM_PROVIDER_LOST_PROCESS = 30036; + static final int LOG_BOOT_PROGRESS_AMS_READY = 3040; static final int LOG_BOOT_PROGRESS_ENABLE_SCREEN = 3050; @@ -197,6 +204,10 @@ public final class ActivityManagerService extends ActivityManagerNative implemen */ static final int LAUNCH_TIMEOUT = 10*1000; + // How long we wait for a launched process to attach to the activity manager + // before we decide it's never going to come up for real. + static final int PROC_START_TIMEOUT = 10*1000; + // How long we wait until giving up on the last activity telling us it // is idle. static final int IDLE_TIMEOUT = 10*1000; @@ -252,6 +263,11 @@ public final class ActivityManagerService extends ActivityManagerNative implemen final int HIDDEN_APP_MAX_ADJ; static int HIDDEN_APP_MIN_ADJ; + // This is a process holding the home application -- we want to try + // avoiding killing it, even if it would normally be in the background, + // because the user interacts with it so much. + final int HOME_APP_ADJ; + // This is a process holding a secondary server -- killing it will not // have much of an impact as far as the user is concerned. Value set in // system/rootdir/init.rc on startup. @@ -279,6 +295,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // Corresponding memory levels for above adjustments. final int EMPTY_APP_MEM; final int HIDDEN_APP_MEM; + final int HOME_APP_MEM; final int SECONDARY_SERVER_MEM; final int VISIBLE_APP_MEM; final int FOREGROUND_APP_MEM; @@ -349,6 +366,13 @@ public final class ActivityManagerService extends ActivityManagerNative implemen */ HistoryRecord mFocusedActivity = null; + /** + * This is the last activity that we put into the paused state. This is + * used to determine if we need to do an activity transition while sleeping, + * when we normally hold the top activity paused. + */ + HistoryRecord mLastPausedActivity = null; + /** * List of activities that are waiting for a new activity * to become visible before completing whatever operation they are @@ -468,6 +492,12 @@ public final class ActivityManagerService extends ActivityManagerNative implemen final ArrayList mProcessesToGc = new ArrayList(); + /** + * This is the process holding what we currently consider to be + * the "home" activity. + */ + private ProcessRecord mHomeProcess; + /** * List of running activities, sorted by recent usage. * The first entry in the list is the least recently used. @@ -631,6 +661,11 @@ public final class ActivityManagerService extends ActivityManagerNative implemen * any user id that can impact battery performance. */ final BatteryStatsService mBatteryStatsService; + + /** + * information about component usage + */ + final UsageStatsService mUsageStatsService; /** * Current configuration information. HistoryRecord objects are given @@ -799,6 +834,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen static final int DESTROY_TIMEOUT_MSG = 17; static final int SERVICE_ERROR_MSG = 18; static final int RESUME_TOP_ACTIVITY_MSG = 19; + static final int PROC_START_TIMEOUT_MSG = 20; AlertDialog mUidAlert; @@ -840,17 +876,18 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } } break; case SHOW_NOT_RESPONDING_MSG: { - HashMap data = (HashMap) msg.obj; - // This needs to be *un*synchronized to avoid deadlock. - Checkin.logEvent(mContext.getContentResolver(), - Checkin.Events.Tag.SYSTEM_APP_NOT_RESPONDING, - (String)data.get("info")); synchronized (ActivityManagerService.this) { + HashMap data = (HashMap) msg.obj; ProcessRecord proc = (ProcessRecord)data.get("app"); if (proc != null && proc.anrDialog != null) { Log.e(TAG, "App already has anr dialog: " + proc); return; } + + broadcastIntentLocked(null, null, new Intent("android.intent.action.ANR"), + null, null, 0, null, null, null, + false, false, MY_PID, Process.SYSTEM_UID); + Dialog d = new AppNotRespondingDialog(ActivityManagerService.this, mContext, proc, (HistoryRecord)data.get("activity")); d.show(); @@ -981,6 +1018,12 @@ public final class ActivityManagerService extends ActivityManagerNative implemen resumeTopActivityLocked(null); } } + case PROC_START_TIMEOUT_MSG: { + ProcessRecord app = (ProcessRecord)msg.obj; + synchronized (ActivityManagerService.this) { + processStartTimedOutLocked(app); + } + } } } }; @@ -1053,6 +1096,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen m.mLaunchingActivity.setReferenceCounted(false); m.mBatteryStatsService.publish(context); + m.mUsageStatsService.publish(context); synchronized (thr) { thr.mReady = true; @@ -1186,8 +1230,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen procs = service.mLRUProcesses; } } - pw.println("Applications Memory Usage (kB):"); - dumpApplicationMemoryUsage(fd, pw, procs, " "); + dumpApplicationMemoryUsage(fd, pw, procs, " ", args); } } @@ -1224,6 +1267,9 @@ public final class ActivityManagerService extends ActivityManagerNative implemen systemDir, "batterystats.bin").toString()); mBatteryStatsService.getActiveStatistics().readLocked(); mBatteryStatsService.getActiveStatistics().writeLocked(); + + mUsageStatsService = new UsageStatsService( new File( + systemDir, "usagestats.bin").toString()); mConfiguration.makeDefault(); mProcessStats.init(); @@ -1238,6 +1284,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen Integer.valueOf(SystemProperties.get("ro.VISIBLE_APP_ADJ")); SECONDARY_SERVER_ADJ = Integer.valueOf(SystemProperties.get("ro.SECONDARY_SERVER_ADJ")); + HOME_APP_ADJ = + Integer.valueOf(SystemProperties.get("ro.HOME_APP_ADJ")); HIDDEN_APP_MIN_ADJ = Integer.valueOf(SystemProperties.get("ro.HIDDEN_APP_MIN_ADJ")); CONTENT_PROVIDER_ADJ = @@ -1251,6 +1299,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen Integer.valueOf(SystemProperties.get("ro.VISIBLE_APP_MEM"))*PAGE_SIZE; SECONDARY_SERVER_MEM = Integer.valueOf(SystemProperties.get("ro.SECONDARY_SERVER_MEM"))*PAGE_SIZE; + HOME_APP_MEM = + Integer.valueOf(SystemProperties.get("ro.HOME_APP_MEM"))*PAGE_SIZE; HIDDEN_APP_MEM = Integer.valueOf(SystemProperties.get("ro.HIDDEN_APP_MEM"))*PAGE_SIZE; EMPTY_APP_MEM = @@ -1519,9 +1569,14 @@ public final class ActivityManagerService extends ActivityManagerNative implemen System.identityHashCode(r), r.task.taskId, r.shortComponentName); } + if (r.isHomeActivity) { + mHomeProcess = app; + } app.thread.scheduleLaunchActivity(new Intent(r.intent), r, r.info, r.icicle, results, newIntents, !andResume, isNextTransitionForward()); + // Update usage stats for launched activity + updateUsageStats(r, true); } catch (RemoteException e) { if (r.launchFailed) { // This is the second time we failed -- finish activity @@ -1668,6 +1723,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (app.pid > 0 && app.pid != MY_PID) { synchronized (mPidsSelfLocked) { mPidsSelfLocked.remove(app.pid); + mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); } app.pid = 0; } @@ -1760,6 +1816,9 @@ public final class ActivityManagerService extends ActivityManagerNative implemen app.removed = false; synchronized (mPidsSelfLocked) { this.mPidsSelfLocked.put(pid, app); + Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); + msg.obj = app; + mHandler.sendMessageDelayed(msg, PROC_START_TIMEOUT); } } else { app.pid = 0; @@ -1775,7 +1834,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } } - private final void startPausingLocked(boolean userLeaving) { + private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) { if (mPausingActivity != null) { RuntimeException e = new RuntimeException(); Log.e(TAG, "Trying to pause when pause is already pending for " @@ -1791,6 +1850,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (DEBUG_PAUSE) Log.v(TAG, "Start pausing: " + prev); mResumedActivity = null; mPausingActivity = prev; + mLastPausedActivity = prev; prev.state = ActivityState.PAUSING; prev.task.touchActiveTime(); @@ -1804,13 +1864,16 @@ public final class ActivityManagerService extends ActivityManagerNative implemen prev.shortComponentName); prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving, prev.configChangeFlags); + updateUsageStats(prev, false); } catch (Exception e) { // Ignore exception, if process died other code will cleanup. Log.w(TAG, "Exception thrown during pause", e); mPausingActivity = null; + mLastPausedActivity = null; } } else { mPausingActivity = null; + mLastPausedActivity = null; } // If we are not going to sleep, we want to ensure the device is @@ -1827,9 +1890,15 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (mPausingActivity != null) { // Have the window manager pause its key dispatching until the new - // activity has started... - prev.pauseKeyDispatchingLocked(); - + // activity has started. If we're pausing the activity just because + // the screen is being turned off and the UI is sleeping, don't interrupt + // key dispatch; the same activity will pick it up again on wakeup. + if (!uiSleeping) { + prev.pauseKeyDispatchingLocked(); + } else { + if (DEBUG_PAUSE) Log.v(TAG, "Key dispatch not paused for screen off"); + } + // Schedule a pause timeout in case the app doesn't respond. // We don't give it much time because this directly impacts the // responsiveness seen by the user. @@ -1848,6 +1917,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen private final void completePauseLocked() { HistoryRecord prev = mPausingActivity; if (DEBUG_PAUSE) Log.v(TAG, "Complete pause: " + prev); + if (prev != null) { if (prev.finishing) { if (DEBUG_PAUSE) Log.v(TAG, "Executing finish of activity: " + prev); @@ -1966,7 +2036,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // First: if this is not the current activity being started, make // sure it matches the current configuration. if (r != starting && doThisProcess) { - ensureActivityConfigurationLocked(r); + ensureActivityConfigurationLocked(r, 0); } if (r.app == null || r.app.thread == null) { @@ -2085,6 +2155,14 @@ public final class ActivityManagerService extends ActivityManagerNative implemen ensureActivitiesVisibleLocked(r, starting, null, configChanges); } } + + private void updateUsageStats(HistoryRecord resumedComponent, boolean resumed) { + if (resumed) { + mUsageStatsService.noteResumeComponent(resumedComponent.realActivity); + } else { + mUsageStatsService.notePauseComponent(resumedComponent.realActivity); + } + } /** * Ensure that the top activity in the stack is resumed. @@ -2134,7 +2212,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (app == null || app.instrumentationClass == null) { intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); startActivityLocked(null, intent, null, null, 0, aInfo, - null, null, 0, 0, 0, false); + null, null, 0, 0, 0, false, false); } } return true; @@ -2148,6 +2226,15 @@ public final class ActivityManagerService extends ActivityManagerNative implemen return false; } + // If we are sleeping, and there is no resumed activity, and the top + // activity is paused, well that is the state we want. + if (mSleeping && mLastPausedActivity == next && next.state == ActivityState.PAUSED) { + // Make sure we have executed any pending transitions, since there + // should be nothing left to do at this point. + mWindowManager.executeAppTransition(); + return false; + } + // The activity may be waiting for stop, but that is no longer // appropriate for it. mStoppingActivities.remove(next); @@ -2166,7 +2253,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // can be resumed... if (mResumedActivity != null) { if (DEBUG_SWITCH) Log.v(TAG, "Skip resume: need to start pausing"); - startPausingLocked(userLeaving); + startPausingLocked(userLeaving, false); return true; } @@ -2267,6 +2354,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // Do over! mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG); } + mWindowManager.executeAppTransition(); return true; } @@ -2290,6 +2378,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen EventLog.writeEvent(LOG_AM_RESUME_ACTIVITY, System.identityHashCode(next), next.task.taskId, next.shortComponentName); + updateUsageStats(next, true); next.app.thread.scheduleResumeActivity(next, isNextTransitionForward()); @@ -2453,9 +2542,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // We don't want to reuse the previous starting preview if: // (1) The current activity is in a different task. if (prev.task != r.task) prev = null; - // (2) The current activity is not the first in the task. - else if (!prev.frontOfTask) prev = null; - // (3) The current activity is already displayed. + // (2) The current activity is already displayed. else if (prev.nowVisible) prev = null; } mWindowManager.setAppStartingWindow( @@ -2536,6 +2623,40 @@ public final class ActivityManagerService extends ActivityManagerNative implemen return null; } + /** + * Find the activity in the history stack within the given task. Returns + * the index within the history at which it's found, or < 0 if not found. + */ + private final int findActivityInHistoryLocked(HistoryRecord r, int task) { + int i = mHistory.size(); + while (i > 0) { + i--; + HistoryRecord candidate = (HistoryRecord)mHistory.get(i); + if (candidate.task.taskId != task) { + break; + } + if (candidate.realActivity.equals(r.realActivity)) { + return i; + } + } + + return -1; + } + + /** + * Reorder the history stack so that the activity at the given index is + * brought to the front. + */ + private final HistoryRecord moveActivityToFrontLocked(int where) { + HistoryRecord newTop = (HistoryRecord)mHistory.remove(where); + int top = mHistory.size(); + HistoryRecord oldTop = (HistoryRecord)mHistory.get(top-1); + mHistory.add(top, newTop); + oldTop.frontOfTask = false; + newTop.frontOfTask = true; + return newTop; + } + /** * Deliver a new Intent to an existing activity, so that its onNewIntent() * method will be called at the proper time. @@ -2550,8 +2671,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen r.app.thread.scheduleNewIntent(ar, r); sent = true; } catch (Exception e) { - Log.w(TAG, - "Exception thrown sending new intent to " + r, e); + Log.w(TAG, "Exception thrown sending new intent to " + r, e); } } if (!sent) { @@ -2573,7 +2693,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen Uri[] grantedUriPermissions, int grantedMode, ActivityInfo aInfo, IBinder resultTo, String resultWho, int requestCode, - int callingPid, int callingUid, boolean onlyIfNeeded) { + int callingPid, int callingUid, boolean onlyIfNeeded, + boolean componentSpecified) { Log.i(TAG, "Starting activity: " + intent); HistoryRecord sourceRecord = null; @@ -2688,7 +2809,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen HistoryRecord r = new HistoryRecord(this, callerApp, callingUid, intent, resolvedType, aInfo, mConfiguration, - resultRecord, resultWho, requestCode); + resultRecord, resultWho, requestCode, componentSpecified); r.startTime = SystemClock.uptimeMillis(); HistoryRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP) @@ -2969,6 +3090,19 @@ public final class ActivityManagerService extends ActivityManagerNative implemen resumeTopActivityLocked(null); return START_DELIVERED_TO_TOP; } + } else if (!addingToTask && + (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) { + // In this case, we are launching an activity in our own task + // that may already be running somewhere in the history, and + // we want to shuffle it to the front of the stack if so. + int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId); + if (where >= 0) { + HistoryRecord top = moveActivityToFrontLocked(where); + logStartActivity(LOG_AM_NEW_INTENT, r, top.task); + deliverNewIntentLocked(top, r.intent); + resumeTopActivityLocked(null); + return START_DELIVERED_TO_TOP; + } } // An existing activity is starting this new activity, so we want // to keep the new one in the same task as the one that is starting @@ -3009,6 +3143,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen throw new IllegalArgumentException("File descriptors passed in Intent"); } + final boolean componentSpecified = intent.getComponent() != null; + // Don't modify the client's object! intent = new Intent(intent); @@ -3048,7 +3184,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen int res = startActivityLocked(caller, intent, resolvedType, grantedUriPermissions, grantedMode, aInfo, resultTo, resultWho, requestCode, -1, -1, - onlyIfNeeded); + onlyIfNeeded, componentSpecified); Binder.restoreCallingIdentity(origId); return res; } @@ -3138,7 +3274,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // those are not yet exposed to user code, so there is no need. int res = startActivityLocked(r.app.thread, intent, r.resolvedType, null, 0, aInfo, resultTo, resultWho, - requestCode, -1, r.launchedFromUid, false); + requestCode, -1, r.launchedFromUid, false, false); Binder.restoreCallingIdentity(origId); r.finishing = wasFinishing; @@ -3152,6 +3288,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen final int startActivityInPackage(int uid, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, boolean onlyIfNeeded) { + final boolean componentSpecified = intent.getComponent() != null; + // Don't modify the client's object! intent = new Intent(intent); @@ -3182,7 +3320,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen synchronized(this) { return startActivityLocked(null, intent, resolvedType, null, 0, aInfo, resultTo, resultWho, requestCode, -1, uid, - onlyIfNeeded); + onlyIfNeeded, componentSpecified); } } @@ -3388,7 +3526,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (mPausingActivity == null) { if (DEBUG_PAUSE) Log.v(TAG, "Finish needs to pause: " + r); if (DEBUG_USER_LEAVING) Log.v(TAG, "finish() => pause with userLeaving=false"); - startPausingLocked(false); + startPausingLocked(false, false); } } else if (r.state != ActivityState.PAUSING) { @@ -3522,9 +3660,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen r.app.thread.scheduleSendResult(r, list); return; } catch (Exception e) { - Log.w(TAG, - "Exception thrown sending result to " + r, - e); + Log.w(TAG, "Exception thrown sending result to " + r, e); } } @@ -3710,8 +3846,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen r.configChangeFlags = 0; if (!mLRUActivities.remove(r)) { - Log.w(TAG, "Activity " + r - + " being finished, but not in LRU list"); + Log.w(TAG, "Activity " + r + " being finished, but not in LRU list"); } return removedFromHistory; @@ -3753,6 +3888,9 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (DEBUG_PAUSE) Log.v(TAG, "App died while pausing: " + mPausingActivity); mPausingActivity = null; } + if (mLastPausedActivity != null && mLastPausedActivity.app == app) { + mLastPausedActivity = null; + } // Remove this application's activities from active lists. removeHistoryRecordsForAppLocked(mLRUActivities, app); @@ -3958,9 +4096,6 @@ public final class ActivityManagerService extends ActivityManagerNative implemen info.append("\nCPU usage:\n"); info.append(processInfo); } - info.append("\n/proc/meminfo:\n"); - info.append(readFile("/proc/meminfo")); - Log.i(TAG, info.toString()); // The application is not responding. Dump as many thread traces as we can. @@ -4012,7 +4147,6 @@ public final class ActivityManagerService extends ActivityManagerNative implemen msg.what = SHOW_NOT_RESPONDING_MSG; msg.obj = map; map.put("app", app); - map.put("info", info.toString()); if (activity != null) { map.put("activity", activity); } @@ -4142,21 +4276,21 @@ public final class ActivityManagerService extends ActivityManagerNative implemen long callingId = Binder.clearCallingIdentity(); try { IPackageManager pm = ActivityThread.getPackageManager(); + int pkgUid = -1; synchronized(this) { - int pkgUid = -1; try { pkgUid = pm.getPackageUid(packageName); } catch (RemoteException e) { } if (pkgUid == -1) { - Log.w(TAG, "Invalid packageName:"+packageName); + Log.w(TAG, "Invalid packageName:" + packageName); return false; } if (uid == pkgUid || checkComponentPermission( android.Manifest.permission.CLEAR_APP_USER_DATA, pid, uid, -1) == PackageManager.PERMISSION_GRANTED) { - uninstallPackageLocked(packageName, pkgUid, false); + restartPackageLocked(packageName, pkgUid); } else { throw new SecurityException(pid+" does not have permission:"+ android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" + @@ -4167,6 +4301,12 @@ public final class ActivityManagerService extends ActivityManagerNative implemen try { //clear application user data pm.clearApplicationUserData(packageName, observer); + Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, + Uri.fromParts("package", packageName, null)); + intent.putExtra(Intent.EXTRA_UID, pkgUid); + broadcastIntentLocked(null, null, intent, + null, null, 0, null, null, null, + false, false, MY_PID, Process.SYSTEM_UID); } catch (RemoteException e) { } } finally { @@ -4188,25 +4328,48 @@ public final class ActivityManagerService extends ActivityManagerNative implemen long callingId = Binder.clearCallingIdentity(); try { + IPackageManager pm = ActivityThread.getPackageManager(); + int pkgUid = -1; synchronized(this) { - uninstallPackageLocked(packageName, -1, false); - broadcastIntentLocked(null, null, - new Intent(Intent.ACTION_PACKAGE_RESTARTED, - Uri.fromParts("package", packageName, null)), - null, null, 0, null, null, null, - false, false, MY_PID, Process.SYSTEM_UID); + try { + pkgUid = pm.getPackageUid(packageName); + } catch (RemoteException e) { + } + if (pkgUid == -1) { + Log.w(TAG, "Invalid packageName: " + packageName); + return; + } + restartPackageLocked(packageName, pkgUid); } } finally { Binder.restoreCallingIdentity(callingId); } } + private void restartPackageLocked(final String packageName, int uid) { + uninstallPackageLocked(packageName, uid, false); + Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, + Uri.fromParts("package", packageName, null)); + intent.putExtra(Intent.EXTRA_UID, uid); + broadcastIntentLocked(null, null, intent, + null, null, 0, null, null, null, + false, false, MY_PID, Process.SYSTEM_UID); + } + private final void uninstallPackageLocked(String name, int uid, boolean callerWillRestart) { if (Config.LOGD) Log.d(TAG, "Uninstalling process " + name); int i, N; + final String procNamePrefix = name + ":"; + if (uid < 0) { + try { + uid = ActivityThread.getPackageManager().getPackageUid(name); + } catch (RemoteException e) { + } + } + Iterator> badApps = mProcessCrashTimes.getMap().values().iterator(); while (badApps.hasNext()) { SparseArray ba = badApps.next(); @@ -4217,14 +4380,6 @@ public final class ActivityManagerService extends ActivityManagerNative implemen ArrayList procs = new ArrayList(); - final String procNamePrefix = name + ":"; - if (uid < 0) { - try { - uid = ActivityThread.getPackageManager().getPackageUid(name); - } catch (RemoteException e) { - } - } - // Remove all processes this package may have touched: all with the // same UID (except for the system or root user), and all whose name // matches the package name. @@ -4294,6 +4449,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen int pid = app.pid; synchronized (mPidsSelfLocked) { mPidsSelfLocked.remove(pid); + mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); } handleAppDiedLocked(app, true); mLRUProcesses.remove(app); @@ -4313,6 +4469,31 @@ public final class ActivityManagerService extends ActivityManagerNative implemen return needRestart; } + private final void processStartTimedOutLocked(ProcessRecord app) { + final int pid = app.pid; + boolean gone = false; + synchronized (mPidsSelfLocked) { + ProcessRecord knownApp = mPidsSelfLocked.get(pid); + if (knownApp != null && knownApp.thread == null) { + mPidsSelfLocked.remove(pid); + gone = true; + } + } + + if (gone) { + Log.w(TAG, "Process " + app + " failed to attach"); + mProcessNames.remove(app.processName, app.info.uid); + Process.killProcess(pid); + if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) { + Log.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); + mPendingBroadcast = null; + scheduleBroadcastsLocked(); + } + } else { + Log.w(TAG, "Spurious process start timeout - pid not known for " + app); + } + } + private final boolean attachApplicationLocked(IApplicationThread thread, int pid) { @@ -4334,6 +4515,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (app == null) { Log.w(TAG, "No pending application record for pid " + pid + " (IApplicationThread " + thread + "); dropping process"); + EventLog.writeEvent(LOG_AM_DROP_PROCESS, pid); if (pid > 0 && pid != MY_PID) { Process.killProcess(pid); } else { @@ -4375,6 +4557,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen app.foregroundServices = false; app.debugging = false; + mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); + List providers = generateApplicationProvidersLocked(app); if (localLOGV) Log.v( @@ -5523,9 +5707,9 @@ public final class ActivityManagerService extends ActivityManagerNative implemen public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { outInfo.availMem = Process.getFreeMemory(); - outInfo.threshold = SECONDARY_SERVER_MEM; + outInfo.threshold = HOME_APP_MEM; outInfo.lowMemory = outInfo.availMem < - (SECONDARY_SERVER_MEM + ((HIDDEN_APP_MEM-SECONDARY_SERVER_MEM)/2)); + (HOME_APP_MEM + ((HIDDEN_APP_MEM-HOME_APP_MEM)/2)); } // ========================================================= @@ -6490,10 +6674,10 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (caller != null) { r = getRecordForAppLocked(caller); if (r == null) { - throw new SecurityException( - "Unable to find app for caller " + caller - + " (pid=" + Binder.getCallingPid() - + ") when getting content provider " + name); + throw new SecurityException( + "Unable to find app for caller " + caller + + " (pid=" + Binder.getCallingPid() + + ") when getting content provider " + name); } } @@ -6650,6 +6834,10 @@ public final class ActivityManagerService extends ActivityManagerNative implemen + cpi.applicationInfo.packageName + "/" + cpi.applicationInfo.uid + " for provider " + name + ": launching app became null"); + EventLog.writeEvent(LOG_AM_PROVIDER_LOST_PROCESS, + cpi.applicationInfo.packageName, + cpi.applicationInfo.uid, name); + return null; } try { cpr.wait(); @@ -6755,9 +6943,6 @@ public final class ActivityManagerService extends ActivityManagerNative implemen ContentProviderRecord dst = (ContentProviderRecord)r.pubProviders.get(src.info.name); if (dst != null) { - dst.provider = src.provider; - dst.app = r; - mProvidersByClass.put(dst.info.name, dst); String names[] = dst.info.authority.split(";"); for (int j = 0; j < names.length; j++) { @@ -6774,6 +6959,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } } synchronized (dst) { + dst.provider = src.provider; + dst.app = r; dst.notifyAll(); } updateOomAdjLocked(r); @@ -6904,7 +7091,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (mPausingActivity == null) { if (DEBUG_PAUSE) Log.v(TAG, "Sleep needs to pause..."); if (DEBUG_USER_LEAVING) Log.v(TAG, "Sleep => pause with userLeaving=false"); - startPausingLocked(false); + startPausingLocked(false, true); } } } @@ -7226,6 +7413,11 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } } + public boolean testIsSystemReady() { + // no need to synchronize(this) just to read & return the value + return mSystemReady; + } + public void systemReady() { // In the simulator, startRunning will never have been called, which // normally sets a few crucial variables. Do it here instead. @@ -7405,6 +7597,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // This process loses! Log.w(TAG, "Process " + app.info.processName + " has crashed too many times: killing!"); + EventLog.writeEvent(LOG_AM_PROCESS_CRASHED_TOO_MUCH, + app.info.processName, app.info.uid); killServicesLocked(app, false); for (int i=mHistory.size()-1; i>=0; i--) { HistoryRecord r = (HistoryRecord)mHistory.get(i); @@ -7628,6 +7822,24 @@ public final class ActivityManagerService extends ActivityManagerNative implemen ActivityManager.RunningAppProcessInfo currApp = new ActivityManager.RunningAppProcessInfo(app.processName, app.pid, app.getPackageList()); + int adj = app.curAdj; + if (adj >= CONTENT_PROVIDER_ADJ) { + currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY; + } else if (adj >= HIDDEN_APP_MIN_ADJ) { + currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND; + currApp.lru = adj - HIDDEN_APP_MIN_ADJ + 1; + } else if (adj >= HOME_APP_ADJ) { + currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND; + currApp.lru = 0; + } else if (adj >= SECONDARY_SERVER_ADJ) { + currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE; + } else if (adj >= VISIBLE_APP_ADJ) { + currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE; + } else { + currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND; + } + //Log.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance + // + " lru=" + currApp.lru); if (runList == null) { runList = new ArrayList(); } @@ -7679,6 +7891,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen pw.println(" mPausingActivity: " + mPausingActivity); pw.println(" mResumedActivity: " + mResumedActivity); pw.println(" mFocusedActivity: " + mFocusedActivity); + pw.println(" mLastPausedActivity: " + mLastPausedActivity); if (mRecentTasks.size() > 0) { pw.println(" "); @@ -7816,6 +8029,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen pw.println(" "); pw.println(" Total persistent processes: " + numPers); + pw.println(" mHomeProcess: " + mHomeProcess); pw.println(" mConfiguration: " + mConfiguration); pw.println(" mStartRunning=" + mStartRunning + " mSystemReady=" + mSystemReady @@ -8176,28 +8390,53 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } private static final void dumpApplicationMemoryUsage(FileDescriptor fd, - PrintWriter pw, List list, String prefix) { + PrintWriter pw, List list, String prefix, String[] args) { + final boolean isCheckinRequest = scanArgs(args, "-c"); + long uptime = SystemClock.uptimeMillis(); + long realtime = SystemClock.elapsedRealtime(); + + if (isCheckinRequest) { + // short checkin version + pw.println(uptime + "," + realtime); + pw.flush(); + } else { + pw.println("Applications Memory Usage (kB):"); + pw.println("Uptime: " + uptime + " Realtime: " + realtime); + } for (int i = list.size() - 1 ; i >= 0 ; i--) { ProcessRecord r = (ProcessRecord)list.get(i); if (r.thread != null) { - pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **"); - pw.flush(); - - Parcel data = Parcel.obtain(); - Parcel reply = Parcel.obtain(); + if (!isCheckinRequest) { + pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **"); + pw.flush(); + } try { - data.writeFileDescriptor(fd); - r.thread.asBinder().transact(IBinder.DUMP_TRANSACTION, data, reply, 0); - + r.thread.asBinder().dump(fd, args); } catch (RemoteException e) { - pw.println("Got RemoteException!"); - pw.flush(); + if (!isCheckinRequest) { + pw.println("Got RemoteException!"); + pw.flush(); + } } + } + } + } - data.recycle(); - reply.recycle(); + /** + * Searches array of arguments for the specified string + * @param args array of argument strings + * @param value value to search for + * @return true if the value is contained in the array + */ + private static boolean scanArgs(String[] args, String value) { + if (args != null) { + for (String arg : args) { + if (value.equals(arg)) { + return true; + } } } + return false; } private final int indexOfTokenLocked(IBinder token, boolean required) { @@ -8295,6 +8534,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if (sr.crashCount >= 2) { Log.w(TAG, "Service crashed " + sr.crashCount + " times, stopping: " + sr); + EventLog.writeEvent(LOG_AM_SERVICE_CRASHED_TOO_MUCH, + sr.crashCount, sr.shortName, app.pid); bringDownServiceLocked(sr, true); } else if (!allowRestart) { bringDownServiceLocked(sr, true); @@ -8313,7 +8554,10 @@ public final class ActivityManagerService extends ActivityManagerNative implemen private final void removeDyingProviderLocked(ProcessRecord proc, ContentProviderRecord cpr) { - cpr.launchingApp = null; + synchronized (cpr) { + cpr.launchingApp = null; + cpr.notifyAll(); + } mProvidersByClass.remove(cpr.info.name); String names[] = cpr.info.authority.split(";"); @@ -8395,6 +8639,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen break; } } + } else { + i = NL; } if (i >= NL) { @@ -8467,8 +8713,12 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } mProcessesOnHold.remove(app); + if (app == mHomeProcess) { + mHomeProcess = null; + } + if (restart) { - // We have component that still need to be running in the + // We have components that still need to be running in the // process, so re-launch it. mProcessNames.put(app.processName, app.info.uid, app); startProcessLocked(app, "restart", app.processName); @@ -8476,6 +8726,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // Goodbye! synchronized (mPidsSelfLocked) { mPidsSelfLocked.remove(app.pid); + mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); } app.pid = 0; } @@ -8818,6 +9069,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay; Log.w(TAG, "Scheduling restart of crashed service " + r.shortName + " in " + r.restartDelay + "ms"); + EventLog.writeEvent(LOG_AM_SCHEDULE_SERVICE_RESTART, + r.shortName, r.restartDelay); Message msg = Message.obtain(); msg.what = SERVICE_ERROR_MSG; @@ -9120,6 +9373,36 @@ public final class ActivityManagerService extends ActivityManagerNative implemen return 0; } + public IBinder peekService(Intent service, String resolvedType) { + // Refuse possible leaked file descriptors + if (service != null && service.hasFileDescriptors() == true) { + throw new IllegalArgumentException("File descriptors passed in Intent"); + } + + IBinder ret = null; + + synchronized(this) { + ServiceLookupResult r = findServiceLocked(service, resolvedType); + + if (r != null) { + // r.record is null if findServiceLocked() failed the caller permission check + if (r.record == null) { + throw new SecurityException( + "Permission Denial: Accessing service " + r.record.name + + " from pid=" + Binder.getCallingPid() + + ", uid=" + Binder.getCallingUid() + + " requires " + r.permission); + } + IntentBindRecord ib = r.record.bindings.get(r.record.intent); + if (ib != null) { + ret = ib.binder; + } + } + } + + return ret; + } + public boolean stopServiceToken(ComponentName className, IBinder token, int startId) { synchronized(this) { @@ -9928,6 +10211,20 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } synchronized(this) { + if (!mSystemReady) { + // if the caller really truly claims to know what they're doing, go + // ahead and allow the broadcast without launching any receivers + int flags = intent.getFlags(); + if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { + intent = new Intent(intent); + intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); + } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0){ + Log.e(TAG, "Attempt to launch receivers of broadcast intent " + intent + + " before boot completion"); + throw new IllegalStateException("Cannot broadcast before boot completed"); + } + } + final ProcessRecord callerApp = getRecordForAppLocked(caller); final int callingPid = Binder.getCallingPid(); final int callingUid = Binder.getCallingUid(); @@ -10639,6 +10936,22 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // ========================================================= // CONFIGURATION // ========================================================= + + public ConfigurationInfo getDeviceConfigurationInfo() { + ConfigurationInfo config = new ConfigurationInfo(); + synchronized (this) { + config.reqTouchScreen = mConfiguration.touchscreen; + config.reqKeyboardType = mConfiguration.keyboard; + config.reqNavigation = mConfiguration.navigation; + if (mConfiguration.navigation != Configuration.NAVIGATION_NONAV) { + config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV; + } + if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED) { + config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD; + } + } + return config; + } public Configuration getConfiguration() { Configuration ci; @@ -10653,6 +10966,11 @@ public final class ActivityManagerService extends ActivityManagerNative implemen "updateConfiguration()"); synchronized(this) { + if (values == null && mWindowManager != null) { + // sentinel: fetch the current configuration from the window manager + values = mWindowManager.computeNewConfiguration(); + } + final long origId = Binder.clearCallingIdentity(); updateConfigurationLocked(values, null); Binder.restoreCallingIdentity(origId); @@ -10718,7 +11036,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } if (starting != null) { - kept = ensureActivityConfigurationLocked(starting); + kept = ensureActivityConfigurationLocked(starting, changes); if (kept) { // If this didn't result in the starting activity being // destroyed, then we need to make sure at this point that all @@ -10775,7 +11093,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen * for whatever reason. Ensures the HistoryRecord is updated with the * correct configuration and all other bookkeeping is handled. */ - private final boolean ensureActivityConfigurationLocked(HistoryRecord r) { + private final boolean ensureActivityConfigurationLocked(HistoryRecord r, + int globalChanges) { if (DEBUG_SWITCH) Log.i(TAG, "Ensuring correct configuration: " + r); // Short circuit: if the two configurations are the exact same @@ -10822,7 +11141,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen if ((changes&(~r.info.configChanges)) != 0) { // Aha, the activity isn't handling the change, so DIE DIE DIE. r.configChangeFlags |= changes; - r.startFreezingScreenLocked(r.app, changes); + r.startFreezingScreenLocked(r.app, globalChanges); if (r.app == null || r.app.thread == null) { if (DEBUG_SWITCH) Log.i(TAG, "Switch is destroying non-running " + r); destroyActivityLocked(r, true); @@ -10903,9 +11222,8 @@ public final class ActivityManagerService extends ActivityManagerNative implemen app.isForeground = false; - // Right now there are three interesting states: it is - // either the foreground app, background with activities, - // or background without activities. + // Determine the importance of the process, starting with most + // important to least, and assign an appropriate OOM adjustment. int adj; int N; if (app == TOP_APP || app.instrumentationClass != null @@ -10925,6 +11243,10 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } else if (app.foregroundServices || app.forcingToForeground != null) { // The user is aware of this app, so make it visible. adj = VISIBLE_APP_ADJ; + } else if (app == mHomeProcess) { + // This process is hosting what we currently consider to be the + // home app, so we don't want to let it go into the background. + adj = HOME_APP_ADJ; } else if ((N=app.activities.size()) != 0) { // This app is in the background with paused activities. adj = hiddenAdj; @@ -10940,7 +11262,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen adj = EMPTY_APP_ADJ; } - // By default, we use the computed adjusted. It may be changed if + // By default, we use the computed adjustment. It may be changed if // there are applications dependent on our services or providers, but // this gives us a baseline and makes sure we don't get into an // infinite recursion. @@ -11461,7 +11783,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen // We can finish this one if we have its icicle saved and // it is not persistent. - if ((r.haveState || !r.stateNotNeeded) + if ((r.haveState || !r.stateNotNeeded) && !r.visible && r.stopped && !r.persistent && !r.finishing) { final int origSize = mLRUActivities.size(); destroyActivityLocked(r, true); @@ -11501,6 +11823,56 @@ public final class ActivityManagerService extends ActivityManagerNative implemen } } + public boolean profileControl(String process, boolean start, + String path) throws RemoteException { + + synchronized (this) { + // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to + // its own permission. + if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) + != PackageManager.PERMISSION_GRANTED) { + throw new SecurityException("Requires permission " + + android.Manifest.permission.SET_ACTIVITY_WATCHER); + } + + ProcessRecord proc = null; + try { + int pid = Integer.parseInt(process); + synchronized (mPidsSelfLocked) { + proc = mPidsSelfLocked.get(pid); + } + } catch (NumberFormatException e) { + } + + if (proc == null) { + HashMap> all + = mProcessNames.getMap(); + SparseArray procs = all.get(process); + if (procs != null && procs.size() > 0) { + proc = procs.valueAt(0); + } + } + + if (proc == null || proc.thread == null) { + throw new IllegalArgumentException("Unknown process: " + process); + } + + boolean isSecure = "1".equals(SystemProperties.get(SYSTEM_SECURE, "0")); + if (isSecure) { + if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { + throw new SecurityException("Process not debuggable: " + proc); + } + } + + try { + proc.thread.profilerControl(start, path); + return true; + } catch (RemoteException e) { + throw new IllegalStateException("Process disappeared"); + } + } + } + /** In this method we try to acquire our lock to make sure that we have not deadlocked */ public void monitor() { synchronized (this) { } diff --git a/services/java/com/android/server/am/BaseErrorDialog.java b/services/java/com/android/server/am/BaseErrorDialog.java index 4f62f6200dfa727bdf6842b90e613e3460849d40..bed2768eb5586800cfc80732c8409430548ac964 100644 --- a/services/java/com/android/server/am/BaseErrorDialog.java +++ b/services/java/com/android/server/am/BaseErrorDialog.java @@ -31,6 +31,8 @@ class BaseErrorDialog extends AlertDialog { super(context, com.android.internal.R.style.Theme_Dialog_AppError); getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, + WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); getWindow().setTitle("Error Dialog"); setIcon(R.drawable.ic_dialog_alert); } diff --git a/services/java/com/android/server/am/BatteryStatsService.java b/services/java/com/android/server/am/BatteryStatsService.java index bf1bc8c6a02f59d9f9d6b9af807c54bfcbe0aa11..27d0401292e532082cef871a66630c3be2153522 100644 --- a/services/java/com/android/server/am/BatteryStatsService.java +++ b/services/java/com/android/server/am/BatteryStatsService.java @@ -22,8 +22,10 @@ import com.android.internal.os.BatteryStatsImpl; import android.content.Context; import android.os.Binder; import android.os.IBinder; +import android.os.Parcel; import android.os.Process; import android.os.ServiceManager; +import android.util.PrintWriterPrinter; import java.io.FileDescriptor; import java.io.PrintWriter; @@ -58,14 +60,23 @@ public final class BatteryStatsService extends IBatteryStats.Stub { /** * @return the current statistics object, which may be modified - * to reflect events that affect battery usage. + * to reflect events that affect battery usage. You must lock the + * stats object before doing anything with it. */ public BatteryStatsImpl getActiveStatistics() { return mStats; } - public BatteryStatsImpl getStatistics() { - return mStats; + public byte[] getStatistics() { + mContext.enforceCallingPermission( + android.Manifest.permission.BATTERY_STATS, null); + //Log.i("foo", "SENDING BATTERY INFO:"); + //mStats.dumpLocked(new LogPrinter(Log.INFO, "foo")); + Parcel out = Parcel.obtain(); + mStats.writeToParcel(out, 0); + byte[] data = out.marshall(); + out.recycle(); + return data; } public void noteStartWakelock(int uid, String name, int type) { @@ -95,6 +106,48 @@ public final class BatteryStatsService extends IBatteryStats.Stub { mStats.getUidStatsLocked(uid).noteStopSensor(sensor); } } + + public void noteStartGps(int uid) { + enforceCallingPermission(); + synchronized (mStats) { + mStats.noteStartGps(uid); + } + } + + public void noteStopGps(int uid) { + enforceCallingPermission(); + synchronized (mStats) { + mStats.noteStopGps(uid); + } + } + + public void noteScreenOn() { + enforceCallingPermission(); + synchronized (mStats) { + mStats.noteScreenOnLocked(); + } + } + + public void noteScreenOff() { + enforceCallingPermission(); + synchronized (mStats) { + mStats.noteScreenOffLocked(); + } + } + + public void notePhoneOn() { + enforceCallingPermission(); + synchronized (mStats) { + mStats.notePhoneOnLocked(); + } + } + + public void notePhoneOff() { + enforceCallingPermission(); + synchronized (mStats) { + mStats.notePhoneOffLocked(); + } + } public boolean isOnBattery() { return mStats.isOnBattery(); @@ -106,10 +159,14 @@ public final class BatteryStatsService extends IBatteryStats.Stub { } public long getAwakeTimeBattery() { + mContext.enforceCallingOrSelfPermission( + android.Manifest.permission.BATTERY_STATS, null); return mStats.getAwakeTimeBattery(); } public long getAwakeTimePlugged() { + mContext.enforceCallingOrSelfPermission( + android.Manifest.permission.BATTERY_STATS, null); return mStats.getAwakeTimePlugged(); } @@ -117,14 +174,24 @@ public final class BatteryStatsService extends IBatteryStats.Stub { if (Binder.getCallingPid() == Process.myPid()) { return; } - mContext.enforcePermission(android.Manifest.permission.BATTERY_STATS, + mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS, Binder.getCallingPid(), Binder.getCallingUid(), null); } @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - synchronized (this) { - mStats.dumpLocked(fd, pw, args); + synchronized (mStats) { + boolean isCheckin = false; + if (args != null) { + for (String arg : args) { + if ("-c".equals(arg)) { + isCheckin = true; + break; + } + } + } + if (isCheckin) mStats.dumpCheckinLocked(pw, args); + else mStats.dumpLocked(new PrintWriterPrinter(pw)); } } } diff --git a/services/java/com/android/server/am/HistoryRecord.java b/services/java/com/android/server/am/HistoryRecord.java index b370b1cdb6e8ef4b0c9a029393501c876712dd8a..0f62471ed7d312538271cca50acd4c2e9a6e61c9 100644 --- a/services/java/com/android/server/am/HistoryRecord.java +++ b/services/java/com/android/server/am/HistoryRecord.java @@ -23,6 +23,7 @@ import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.pm.ActivityInfo; +import android.content.pm.ApplicationInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.os.Bundle; @@ -54,6 +55,8 @@ class HistoryRecord extends IApplicationToken.Stub { final String taskAffinity; // as per ActivityInfo.taskAffinity final boolean stateNotNeeded; // As per ActivityInfo.flags final boolean fullscreen; // covers the full screen? + final boolean componentSpecified; // did caller specifiy an explicit component? + final boolean isHomeActivity; // do we consider this to be a home activity? final String baseDir; // where activity source (resources etc) located final String resDir; // where public activity source (public resources etc) located final String dataDir; // where activity data should go @@ -101,8 +104,8 @@ class HistoryRecord extends IApplicationToken.Stub { pw.println(prefix + this); pw.println(prefix + "packageName=" + packageName + " processName=" + processName); - pw.println(prefix + "app=" + app); - pw.println(prefix + "launchedFromUid=" + launchedFromUid); + pw.println(prefix + "launchedFromUid=" + launchedFromUid + + " app=" + app); pw.println(prefix + intent); pw.println(prefix + "frontOfTask=" + frontOfTask + " task=" + task); pw.println(prefix + "taskAffinity=" + taskAffinity); @@ -111,6 +114,9 @@ class HistoryRecord extends IApplicationToken.Stub { pw.println(prefix + "labelRes=0x" + Integer.toHexString(labelRes) + " icon=0x" + Integer.toHexString(icon) + " theme=0x" + Integer.toHexString(theme)); + pw.println(prefix + "stateNotNeeded=" + stateNotNeeded + + " componentSpecified=" + componentSpecified + + " isHomeActivity=" + isHomeActivity); pw.println(prefix + "configuration=" + configuration); pw.println(prefix + "resultTo=" + resultTo + " resultWho=" + resultWho + " resultCode=" + requestCode); @@ -139,13 +145,15 @@ class HistoryRecord extends IApplicationToken.Stub { HistoryRecord(ActivityManagerService _service, ProcessRecord _caller, int _launchedFromUid, Intent _intent, String _resolvedType, ActivityInfo aInfo, Configuration _configuration, - HistoryRecord _resultTo, String _resultWho, int _reqCode) { + HistoryRecord _resultTo, String _resultWho, int _reqCode, + boolean _componentSpecified) { service = _service; info = aInfo; launchedFromUid = _launchedFromUid; intent = _intent; shortComponentName = _intent.getComponent().flattenToShortString(); resolvedType = _resolvedType; + componentSpecified = _componentSpecified; configuration = _configuration; resultTo = _resultTo; resultWho = _resultWho; @@ -184,6 +192,11 @@ class HistoryRecord extends IApplicationToken.Stub { dataDir = aInfo.applicationInfo.dataDir; nonLocalizedLabel = aInfo.nonLocalizedLabel; labelRes = aInfo.labelRes; + if (nonLocalizedLabel == null && labelRes == 0) { + ApplicationInfo app = aInfo.applicationInfo; + nonLocalizedLabel = app.nonLocalizedLabel; + labelRes = app.labelRes; + } icon = aInfo.getIconResource(); theme = aInfo.getThemeResource(); if ((aInfo.flags&ActivityInfo.FLAG_MULTIPROCESS) != 0 @@ -210,6 +223,29 @@ class HistoryRecord extends IApplicationToken.Stub { && !ent.array.getBoolean( com.android.internal.R.styleable.Window_windowIsTranslucent, false); + if (!_componentSpecified || _launchedFromUid == Process.myUid() + || _launchedFromUid == 0) { + // If we know the system has determined the component, then + // we can consider this to be a home activity... + if (Intent.ACTION_MAIN.equals(_intent.getAction()) && + _intent.hasCategory(Intent.CATEGORY_HOME) && + _intent.getCategories().size() == 1 && + _intent.getData() == null && + _intent.getType() == null && + (intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 && + !"android".equals(realActivity.getClassName())) { + // This sure looks like a home activity! + // Note the last check is so we don't count the resolver + // activity as being home... really, we don't care about + // doing anything special with something that comes from + // the core framework package. + isHomeActivity = true; + } else { + isHomeActivity = false; + } + } else { + isHomeActivity = false; + } } else { realActivity = null; taskAffinity = null; @@ -220,6 +256,7 @@ class HistoryRecord extends IApplicationToken.Stub { processName = null; packageName = null; fullscreen = true; + isHomeActivity = false; } } diff --git a/services/java/com/android/server/am/UsageStatsService.java b/services/java/com/android/server/am/UsageStatsService.java new file mode 100755 index 0000000000000000000000000000000000000000..3922f39f52ba0a37dcdf3d829700180b3db6f8c2 --- /dev/null +++ b/services/java/com/android/server/am/UsageStatsService.java @@ -0,0 +1,532 @@ +/* + * Copyright (C) 2006-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. + */ + +package com.android.server.am; + +import com.android.internal.app.IUsageStats; +import android.content.ComponentName; +import android.content.Context; +import android.os.Binder; +import android.os.IBinder; +import com.android.internal.os.PkgUsageStats; +import android.os.Parcel; +import android.os.Process; +import android.os.ServiceManager; +import android.os.SystemClock; +import android.util.Log; +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * This service collects the statistics associated with usage + * of various components, like when a particular package is launched or + * paused and aggregates events like number of time a component is launched + * total duration of a component launch. + */ +public final class UsageStatsService extends IUsageStats.Stub { + public static final String SERVICE_NAME = "usagestats"; + private static final boolean localLOGV = false; + private static final String TAG = "UsageStats"; + static IUsageStats sService; + private Context mContext; + // structure used to maintain statistics since the last checkin. + final private Map mStats; + // Lock to update package stats. Methods suffixed by SLOCK should invoked with + // this lock held + final Object mStatsLock; + // Lock to write to file. Methods suffixed by FLOCK should invoked with + // this lock held. + final Object mFileLock; + // Order of locks is mFileLock followed by mStatsLock to avoid deadlocks + private String mResumedPkg; + private File mFile; + //private File mBackupFile; + private long mLastWriteRealTime; + private int _FILE_WRITE_INTERVAL = 30*60*1000; //ms + private static final String _PREFIX_DELIMIT="."; + private String mFilePrefix; + private Calendar mCal; + private static final int _MAX_NUM_FILES = 10; + private long mLastTime; + + private class PkgUsageStatsExtended { + int mLaunchCount; + long mUsageTime; + long mPausedTime; + long mResumedTime; + + PkgUsageStatsExtended() { + mLaunchCount = 0; + mUsageTime = 0; + } + void updateResume() { + mLaunchCount ++; + mResumedTime = SystemClock.elapsedRealtime(); + } + void updatePause() { + mPausedTime = SystemClock.elapsedRealtime(); + mUsageTime += (mPausedTime - mResumedTime); + } + void clear() { + mLaunchCount = 0; + mUsageTime = 0; + } + } + + UsageStatsService(String fileName) { + mStats = new HashMap(); + mStatsLock = new Object(); + mFileLock = new Object(); + mFilePrefix = fileName; + mCal = Calendar.getInstance(); + // Update current stats which are binned by date + String uFileName = getCurrentDateStr(mFilePrefix); + mFile = new File(uFileName); + readStatsFromFile(); + mLastWriteRealTime = SystemClock.elapsedRealtime(); + mLastTime = new Date().getTime(); + } + + /* + * Utility method to convert date into string. + */ + private String getCurrentDateStr(String prefix) { + mCal.setTime(new Date()); + StringBuilder sb = new StringBuilder(); + if (prefix != null) { + sb.append(prefix); + sb.append("."); + } + int mm = mCal.get(Calendar.MONTH) - Calendar.JANUARY +1; + if (mm < 10) { + sb.append("0"); + } + sb.append(mm); + int dd = mCal.get(Calendar.DAY_OF_MONTH); + if (dd < 10) { + sb.append("0"); + } + sb.append(dd); + sb.append(mCal.get(Calendar.YEAR)); + return sb.toString(); + } + + private Parcel getParcelForFile(File file) throws IOException { + FileInputStream stream = new FileInputStream(file); + byte[] raw = readFully(stream); + Parcel in = Parcel.obtain(); + in.unmarshall(raw, 0, raw.length); + in.setDataPosition(0); + stream.close(); + return in; + } + + private void readStatsFromFile() { + File newFile = mFile; + synchronized (mFileLock) { + try { + if (newFile.exists()) { + readStatsFLOCK(newFile); + } else { + // Check for file limit before creating a new file + checkFileLimitFLOCK(); + newFile.createNewFile(); + } + } catch (IOException e) { + Log.w(TAG,"Error : " + e + " reading data from file:" + newFile); + } + } + } + + private void readStatsFLOCK(File file) throws IOException { + Parcel in = getParcelForFile(file); + while (in.dataAvail() > 0) { + String pkgName = in.readString(); + PkgUsageStatsExtended pus = new PkgUsageStatsExtended(); + pus.mLaunchCount = in.readInt(); + pus.mUsageTime = in.readLong(); + synchronized (mStatsLock) { + mStats.put(pkgName, pus); + } + } + } + + private ArrayList getUsageStatsFileListFLOCK() { + File dir = getUsageFilesDir(); + if (dir == null) { + Log.w(TAG, "Couldnt find writable directory for usage stats file"); + return null; + } + // Check if there are too many files in the system and delete older files + String fList[] = dir.list(); + if (fList == null) { + return null; + } + File pre = new File(mFilePrefix); + String filePrefix = pre.getName(); + // file name followed by dot + int prefixLen = filePrefix.length()+1; + ArrayList fileList = new ArrayList(); + for (String file : fList) { + int index = file.indexOf(filePrefix); + if (index == -1) { + continue; + } + if (file.endsWith(".bak")) { + continue; + } + fileList.add(file); + } + return fileList; + } + + private File getUsageFilesDir() { + if (mFilePrefix == null) { + return null; + } + File pre = new File(mFilePrefix); + return new File(pre.getParent()); + } + + private void checkFileLimitFLOCK() { + File dir = getUsageFilesDir(); + if (dir == null) { + Log.w(TAG, "Couldnt find writable directory for usage stats file"); + return; + } + // Get all usage stats output files + ArrayList fileList = getUsageStatsFileListFLOCK(); + if (fileList == null) { + // Strange but we dont have to delete any thing + return; + } + int count = fileList.size(); + if (count <= _MAX_NUM_FILES) { + return; + } + // Sort files + Collections.sort(fileList); + count -= _MAX_NUM_FILES; + // Delete older files + for (int i = 0; i < count; i++) { + String fileName = fileList.get(i); + File file = new File(dir, fileName); + Log.i(TAG, "Deleting file : "+fileName); + file.delete(); + } + } + + private void writeStatsToFile() { + synchronized (mFileLock) { + long currTime = new Date().getTime(); + boolean dayChanged = ((currTime - mLastTime) >= (24*60*60*1000)); + long currRealTime = SystemClock.elapsedRealtime(); + if (((currRealTime-mLastWriteRealTime) < _FILE_WRITE_INTERVAL) && + (!dayChanged)) { + // wait till the next update + return; + } + // Get the most recent file + String todayStr = getCurrentDateStr(mFilePrefix); + // Copy current file to back up + File backupFile = new File(mFile.getPath() + ".bak"); + mFile.renameTo(backupFile); + try { + checkFileLimitFLOCK(); + mFile.createNewFile(); + // Write mStats to file + writeStatsFLOCK(); + mLastWriteRealTime = currRealTime; + mLastTime = currTime; + if (dayChanged) { + // clear stats + synchronized (mStats) { + mStats.clear(); + } + mFile = new File(todayStr); + } + // Delete the backup file + if (backupFile != null) { + backupFile.delete(); + } + } catch (IOException e) { + Log.w(TAG, "Failed writing stats to file:" + mFile); + if (backupFile != null) { + backupFile.renameTo(mFile); + } + } + } + } + + private void writeStatsFLOCK() throws IOException { + FileOutputStream stream = new FileOutputStream(mFile); + Parcel out = Parcel.obtain(); + writeStatsToParcelFLOCK(out); + stream.write(out.marshall()); + out.recycle(); + stream.flush(); + stream.close(); + } + + private void writeStatsToParcelFLOCK(Parcel out) { + synchronized (mStatsLock) { + Set keys = mStats.keySet(); + for (String key : keys) { + PkgUsageStatsExtended pus = mStats.get(key); + out.writeString(key); + out.writeInt(pus.mLaunchCount); + out.writeLong(pus.mUsageTime); + } + } + } + + public void publish(Context context) { + mContext = context; + ServiceManager.addService(SERVICE_NAME, asBinder()); + } + + public static IUsageStats getService() { + if (sService != null) { + return sService; + } + IBinder b = ServiceManager.getService(SERVICE_NAME); + sService = asInterface(b); + return sService; + } + + public void noteResumeComponent(ComponentName componentName) { + enforceCallingPermission(); + String pkgName; + if ((componentName == null) || + ((pkgName = componentName.getPackageName()) == null)) { + return; + } + if ((mResumedPkg != null) && (mResumedPkg.equalsIgnoreCase(pkgName))) { + // Moving across activities in same package. just return + return; + } + if (localLOGV) Log.i(TAG, "started component:"+pkgName); + synchronized (mStatsLock) { + PkgUsageStatsExtended pus = mStats.get(pkgName); + if (pus == null) { + pus = new PkgUsageStatsExtended(); + mStats.put(pkgName, pus); + } + pus.updateResume(); + } + mResumedPkg = pkgName; + } + + public void notePauseComponent(ComponentName componentName) { + enforceCallingPermission(); + String pkgName; + if ((componentName == null) || + ((pkgName = componentName.getPackageName()) == null)) { + return; + } + if ((mResumedPkg == null) || (!pkgName.equalsIgnoreCase(mResumedPkg))) { + Log.w(TAG, "Something wrong here, Didn't expect "+pkgName+" to be paused"); + return; + } + if (localLOGV) Log.i(TAG, "paused component:"+pkgName); + synchronized (mStatsLock) { + PkgUsageStatsExtended pus = mStats.get(pkgName); + if (pus == null) { + // Weird some error here + Log.w(TAG, "No package stats for pkg:"+pkgName); + return; + } + pus.updatePause(); + } + // Persist data to file + writeStatsToFile(); + } + + public void enforceCallingPermission() { + if (Binder.getCallingPid() == Process.myPid()) { + return; + } + mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS, + Binder.getCallingPid(), Binder.getCallingUid(), null); + } + + public PkgUsageStats getPkgUsageStats(ComponentName componentName) { + mContext.enforceCallingOrSelfPermission( + android.Manifest.permission.PACKAGE_USAGE_STATS, null); + String pkgName; + if ((componentName == null) || + ((pkgName = componentName.getPackageName()) == null)) { + return null; + } + synchronized (mStatsLock) { + PkgUsageStatsExtended pus = mStats.get(pkgName); + if (pus == null) { + return null; + } + return new PkgUsageStats(pkgName, pus.mLaunchCount, pus.mUsageTime); + } + } + + public PkgUsageStats[] getAllPkgUsageStats() { + mContext.enforceCallingOrSelfPermission( + android.Manifest.permission.PACKAGE_USAGE_STATS, null); + synchronized (mStatsLock) { + Set keys = mStats.keySet(); + int size = keys.size(); + if (size <= 0) { + return null; + } + PkgUsageStats retArr[] = new PkgUsageStats[size]; + int i = 0; + for (String key: keys) { + PkgUsageStatsExtended pus = mStats.get(key); + retArr[i] = new PkgUsageStats(key, pus.mLaunchCount, pus.mUsageTime); + i++; + } + return retArr; + } + } + + static byte[] readFully(FileInputStream stream) throws java.io.IOException { + int pos = 0; + int avail = stream.available(); + byte[] data = new byte[avail]; + while (true) { + int amt = stream.read(data, pos, data.length-pos); + if (amt <= 0) { + return data; + } + pos += amt; + avail = stream.available(); + if (avail > data.length-pos) { + byte[] newData = new byte[pos+avail]; + System.arraycopy(data, 0, newData, 0, pos); + data = newData; + } + } + } + + private void collectDumpInfoFLOCK(PrintWriter pw, String[] args) { + List fileList = getUsageStatsFileListFLOCK(); + if (fileList == null) { + return; + } + final boolean isCheckinRequest = scanArgs(args, "-c"); + Collections.sort(fileList); + File usageFile = new File(mFilePrefix); + String dirName = usageFile.getParent(); + File dir = new File(dirName); + String filePrefix = usageFile.getName(); + // file name followed by dot + int prefixLen = filePrefix.length()+1; + String todayStr = getCurrentDateStr(null); + for (String file : fileList) { + File dFile = new File(dir, file); + String dateStr = file.substring(prefixLen); + try { + Parcel in = getParcelForFile(dFile); + collectDumpInfoFromParcelFLOCK(in, pw, dateStr, isCheckinRequest); + if (isCheckinRequest && !todayStr.equalsIgnoreCase(dateStr)) { + // Delete old file after collecting info only for checkin requests + dFile.delete(); + } + } catch (FileNotFoundException e) { + Log.w(TAG, "Failed with "+e+" when collecting dump info from file : " + file); + return; + } catch (IOException e) { + Log.w(TAG, "Failed with "+e+" when collecting dump info from file : "+file); + } + } + } + + private void collectDumpInfoFromParcelFLOCK(Parcel in, PrintWriter pw, + String date, boolean isCheckinRequest) { + StringBuilder sb = new StringBuilder(); + sb.append("Date:"); + sb.append(date); + boolean first = true; + while (in.dataAvail() > 0) { + String pkgName = in.readString(); + int launchCount = in.readInt(); + long usageTime = in.readLong(); + if (isCheckinRequest) { + if (!first) { + sb.append(","); + } + sb.append(pkgName); + sb.append(","); + sb.append(launchCount); + sb.append(","); + sb.append(usageTime); + sb.append("ms"); + } else { + if (first) { + sb.append("\n"); + } + sb.append("pkg="); + sb.append(pkgName); + sb.append(", launchCount="); + sb.append(launchCount); + sb.append(", usageTime="); + sb.append(usageTime); + sb.append(" ms\n"); + } + first = false; + } + pw.write(sb.toString()); + } + + /** + * Searches array of arguments for the specified string + * @param args array of argument strings + * @param value value to search for + * @return true if the value is contained in the array + */ + private static boolean scanArgs(String[] args, String value) { + if (args != null) { + for (String arg : args) { + if (value.equals(arg)) { + return true; + } + } + } + return false; + } + + @Override + /* + * The data persisted to file is parsed and the stats are computed. + */ + protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { + synchronized (mFileLock) { + collectDumpInfoFLOCK(pw, args); + } + } + +} diff --git a/services/java/com/android/server/status/AnimatedImageView.java b/services/java/com/android/server/status/AnimatedImageView.java index 36492da68e88e4f445a344904548abcb86abbe29..cd581c41e1039a0f674e9b8fa46a4b6fb65fb5a6 100644 --- a/services/java/com/android/server/status/AnimatedImageView.java +++ b/services/java/com/android/server/status/AnimatedImageView.java @@ -42,6 +42,7 @@ public class AnimatedImageView extends ImageView { } @Override + @android.view.RemotableViewMethod public void setImageResource(int resid) { super.setImageResource(resid); updateAnim(); diff --git a/services/java/com/android/server/status/StatusBarPolicy.java b/services/java/com/android/server/status/StatusBarPolicy.java index 00ff7bec1961d83fe723c66a22939a00a71ab77c..84332278887f2e651089332fa0640bb78a0b67e3 100644 --- a/services/java/com/android/server/status/StatusBarPolicy.java +++ b/services/java/com/android/server/status/StatusBarPolicy.java @@ -72,6 +72,11 @@ public class StatusBarPolicy { private static final int EVENT_DATA_ACTIVITY = 3; private static final int EVENT_BATTERY_CLOSE = 4; + // indices into mBatteryThresholds + private static final int BATTERY_THRESHOLD_CLOSE_WARNING = 0; + private static final int BATTERY_THRESHOLD_WARNING = 1; + private static final int BATTERY_THRESHOLD_EMPTY = 2; + private Context mContext; private StatusBarService mService; private Handler mHandler = new StatusBarHandler(); @@ -88,7 +93,7 @@ public class StatusBarPolicy { private boolean mBatteryPlugged; private int mBatteryLevel; private int mBatteryThreshold = 0; // index into mBatteryThresholds - private int[] mBatteryThresholds = new int[] { 15, -1 }; + private int[] mBatteryThresholds = new int[] { 20, 15, -1 }; private AlertDialog mLowBatteryDialog; private TextView mBatteryLevelTextView; private View mBatteryView; @@ -157,6 +162,7 @@ public class StatusBarPolicy { private IconData mBluetoothData; private int mBluetoothHeadsetState; private int mBluetoothA2dpState; + private boolean mBluetoothEnabled; // wifi private static final int[] sWifiSignalImages = new int[] { @@ -233,7 +239,7 @@ public class StatusBarPolicy { } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION) || action.equals(AudioManager.VIBRATE_SETTING_CHANGED_ACTION)) { - updateVolume(intent); + updateVolume(); } else if (action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) { updateSimState(intent); @@ -286,7 +292,16 @@ public class StatusBarPolicy { mBluetoothData = IconData.makeIcon("bluetooth", null, com.android.internal.R.drawable.stat_sys_data_bluetooth, 0, 0); mBluetoothIcon = service.addIcon(mBluetoothData, null); - updateBluetooth(null); + BluetoothDevice bluetooth = + (BluetoothDevice) mContext.getSystemService(Context.BLUETOOTH_SERVICE); + if (bluetooth != null) { + mBluetoothEnabled = bluetooth.isEnabled(); + } else { + mBluetoothEnabled = false; + } + mBluetoothA2dpState = BluetoothA2dp.STATE_DISCONNECTED; + mBluetoothHeadsetState = BluetoothHeadset.STATE_DISCONNECTED; + mService.setIconVisibility(mBluetoothIcon, mBluetoothEnabled); // Gps status mGpsEnabledIconData = IconData.makeIcon("gps", @@ -316,6 +331,7 @@ public class StatusBarPolicy { null, com.android.internal.R.drawable.stat_sys_ringer_silent, 0, 0); mVolumeIcon = service.addIcon(mVolumeData, null); service.setIconVisibility(mVolumeIcon, false); + updateVolume(); IntentFilter filter = new IntentFilter(); @@ -419,9 +435,14 @@ public class StatusBarPolicy { } } */ + if (false) { + Log.d(TAG, "plugged=" + plugged + " oldPlugged=" + oldPlugged + " level=" + level + + " mBatteryThreshold=" + mBatteryThreshold + " oldThreshold=" + oldThreshold); + } if (!plugged - && ((oldPlugged && level <= mBatteryThresholds[0]) - || (mBatteryThreshold > oldThreshold))) { + && ((oldPlugged && level < mBatteryThresholds[BATTERY_THRESHOLD_WARNING]) + || (mBatteryThreshold > oldThreshold + && mBatteryThreshold > BATTERY_THRESHOLD_WARNING))) { // Broadcast the low battery warning mContext.sendBroadcast(new Intent(Intent.ACTION_BATTERY_LOW)); @@ -438,6 +459,13 @@ public class StatusBarPolicy { mBatteryShowLowOnEndCall = true; } } + } else if (mBatteryThreshold == BATTERY_THRESHOLD_CLOSE_WARNING) { + if (SHOW_LOW_BATTERY_WARNING) { + if (mLowBatteryDialog != null) { + mLowBatteryDialog.dismiss(); + mBatteryShowLowOnEndCall = false; + } + } } } @@ -745,9 +773,7 @@ public class StatusBarPolicy { } } - private final void updateVolume(Intent intent) { - // This can be called from two different received intents, so don't use extras. - + private final void updateVolume() { AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); final int ringerMode = audioManager.getRingerMode(); final boolean visible = ringerMode == AudioManager.RINGER_MODE_SILENT || @@ -767,30 +793,17 @@ public class StatusBarPolicy { } private final void updateBluetooth(Intent intent) { - boolean visible = false; - if (intent == null) { // Initialize - BluetoothDevice bluetooth = - (BluetoothDevice) mContext.getSystemService(Context.BLUETOOTH_SERVICE); - if (bluetooth != null) { - visible = bluetooth.isEnabled(); - } - mService.setIconVisibility(mBluetoothIcon, visible); - return; - } - int iconId = com.android.internal.R.drawable.stat_sys_data_bluetooth; - String action = intent.getAction(); + String action = intent.getAction(); if (action.equals(BluetoothIntent.DISABLED_ACTION)) { - visible = false; + mBluetoothEnabled = false; } else if (action.equals(BluetoothIntent.ENABLED_ACTION)) { - visible = true; + mBluetoothEnabled = true; } else if (action.equals(BluetoothIntent.HEADSET_STATE_CHANGED_ACTION)) { - visible = true; mBluetoothHeadsetState = intent.getIntExtra(BluetoothIntent.HEADSET_STATE, BluetoothHeadset.STATE_ERROR); } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) { - visible = true; mBluetoothA2dpState = intent.getIntExtra(BluetoothA2dp.SINK_STATE, BluetoothA2dp.STATE_DISCONNECTED); } else { @@ -805,7 +818,7 @@ public class StatusBarPolicy { mBluetoothData.iconId = iconId; mService.updateIcon(mBluetoothIcon, mBluetoothData, null); - mService.setIconVisibility(mBluetoothIcon, visible); + mService.setIconVisibility(mBluetoothIcon, mBluetoothEnabled); } private final void updateWifi(Intent intent) { diff --git a/services/java/com/android/server/status/StatusBarService.java b/services/java/com/android/server/status/StatusBarService.java index 3b6e354b6b48a16be97102748473ccb1b4f89731..5442e1d425bed184913a1c0a0425431106be52ef 100644 --- a/services/java/com/android/server/status/StatusBarService.java +++ b/services/java/com/android/server/status/StatusBarService.java @@ -27,6 +27,7 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; @@ -175,11 +176,11 @@ public class StatusBarService extends IStatusBar.Stub WindowManager.LayoutParams mExpandedParams; ScrollView mScrollView; View mNotificationLinearLayout; - View mOngoingTitle; + TextView mOngoingTitle; LinearLayout mOngoingItems; - View mLatestTitle; + TextView mLatestTitle; LinearLayout mLatestItems; - View mNoNotificationsTitle; + TextView mNoNotificationsTitle; TextView mSpnLabel; TextView mPlmnLabel; TextView mClearButton; @@ -269,11 +270,11 @@ public class StatusBarService extends IStatusBar.Stub mExpandedDialog = new ExpandedDialog(context); mExpandedView = expanded; - mOngoingTitle = expanded.findViewById(R.id.ongoingTitle); + mOngoingTitle = (TextView)expanded.findViewById(R.id.ongoingTitle); mOngoingItems = (LinearLayout)expanded.findViewById(R.id.ongoingItems); - mLatestTitle = expanded.findViewById(R.id.latestTitle); + mLatestTitle = (TextView)expanded.findViewById(R.id.latestTitle); mLatestItems = (LinearLayout)expanded.findViewById(R.id.latestItems); - mNoNotificationsTitle = expanded.findViewById(R.id.noNotificationsTitle); + mNoNotificationsTitle = (TextView)expanded.findViewById(R.id.noNotificationsTitle); mClearButton = (TextView)expanded.findViewById(R.id.clear_all_button); mClearButton.setOnClickListener(mClearButtonListener); mSpnLabel = (TextView)expanded.findViewById(R.id.spnLabel); @@ -322,9 +323,11 @@ public class StatusBarService extends IStatusBar.Stub } public void systemReady() { + final StatusBarView view = mStatusBarView; WindowManager.LayoutParams lp = new WindowManager.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, - 25, + view.getContext().getResources().getDimensionPixelSize( + com.android.internal.R.dimen.status_bar_height), WindowManager.LayoutParams.TYPE_STATUS_BAR, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING, @@ -333,7 +336,7 @@ public class StatusBarService extends IStatusBar.Stub lp.setTitle("StatusBar"); lp.windowAnimations = R.style.Animation_StatusBar; - WindowManagerImpl.getDefault().addView(mStatusBarView, lp); + WindowManagerImpl.getDefault().addView(view, lp); } // ================================================================================ @@ -1324,80 +1327,89 @@ public class StatusBarService extends IStatusBar.Stub } protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) + != PackageManager.PERMISSION_GRANTED) { + pw.println("Permission Denial: can't dump StatusBar from from pid=" + + Binder.getCallingPid() + + ", uid=" + Binder.getCallingUid()); + return; + } + synchronized (mQueue) { - pw.println("mExpanded=" + mExpanded + pw.println("Current Status Bar state:"); + pw.println(" mExpanded=" + mExpanded + ", mExpandedVisible=" + mExpandedVisible); - pw.println("mTicking=" + mTicking); - pw.println("mTracking=" + mTracking); - pw.println("mAnimating=" + mAnimating + pw.println(" mTicking=" + mTicking); + pw.println(" mTracking=" + mTracking); + pw.println(" mAnimating=" + mAnimating + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel + ", mAnimAccel=" + mAnimAccel); - pw.println("mCurAnimationTime=" + mCurAnimationTime + pw.println(" mCurAnimationTime=" + mCurAnimationTime + " mAnimLastTime=" + mAnimLastTime); - pw.println("mDisplayHeight=" + mDisplayHeight + pw.println(" mDisplayHeight=" + mDisplayHeight + " mAnimatingReveal=" + mAnimatingReveal + " mViewDelta=" + mViewDelta); - pw.println("mDisplayHeight=" + mDisplayHeight); + pw.println(" mDisplayHeight=" + mDisplayHeight); final int N = mQueue.size(); - pw.println("mQueue.size=" + N); + pw.println(" mQueue.size=" + N); for (int i=0; iGetIntArrayElements(keyCodes, NULL); + uint8_t* flags = env->GetBooleanArrayElements(outFlags, NULL); + size_t numCodes = env->GetArrayLength(keyCodes); + if (numCodes == env->GetArrayLength(outFlags)) { + gLock.lock(); + if (gHub != NULL) ret = gHub->hasKeys(numCodes, codes, flags); + gLock.unlock(); + } + + env->ReleaseBooleanArrayElements(outFlags, flags, 0); + env->ReleaseIntArrayElements(keyCodes, codes, 0); + return ret; +} // ---------------------------------------------------------------------------- @@ -233,6 +252,8 @@ static JNINativeMethod gInputMethods[] = { (void*) android_server_KeyInputQueue_getKeycodeState }, { "getKeycodeState", "(II)I", (void*) android_server_KeyInputQueue_getKeycodeStateDevice }, + { "hasKeys", "([I[Z)Z", + (void*) android_server_KeyInputQueue_hasKeys }, }; int register_android_server_KeyInputQueue(JNIEnv* env) diff --git a/core/jni/server/com_android_server_SensorService.cpp b/services/jni/com_android_server_SensorService.cpp similarity index 100% rename from core/jni/server/com_android_server_SensorService.cpp rename to services/jni/com_android_server_SensorService.cpp diff --git a/core/jni/server/com_android_server_SystemServer.cpp b/services/jni/com_android_server_SystemServer.cpp similarity index 100% rename from core/jni/server/com_android_server_SystemServer.cpp rename to services/jni/com_android_server_SystemServer.cpp diff --git a/core/jni/server/onload.cpp b/services/jni/onload.cpp similarity index 100% rename from core/jni/server/onload.cpp rename to services/jni/onload.cpp diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java index 374a7032cdd24714c9befd6359fa7f269378be24..c5b1b737335943db728f00f5ca2f8a55e70d8757 100644 --- a/telephony/java/android/telephony/TelephonyManager.java +++ b/telephony/java/android/telephony/TelephonyManager.java @@ -252,10 +252,7 @@ public class TelephonyManager { */ public List getNeighboringCellInfo() { try { - ITelephony tel = getITelephony(); - if (tel != null) { - return tel.getNeighboringCellInfo(); - } + return getITelephony().getNeighboringCellInfo(); } catch (RemoteException ex) { } return null; @@ -683,7 +680,8 @@ public class TelephonyManager { public void listen(PhoneStateListener listener, int events) { String pkgForDebug = mContext != null ? mContext.getPackageName() : ""; try { - mRegistry.listen(pkgForDebug, listener.callback, events, true); + Boolean notifyNow = (getITelephony() != null); + mRegistry.listen(pkgForDebug, listener.callback, events, notifyNow); } catch (RemoteException ex) { // system process dead } diff --git a/telephony/java/android/telephony/gsm/SmsMessage.java b/telephony/java/android/telephony/gsm/SmsMessage.java index f79b0a0001ee9953e7863f92046213f0ba7599f6..c2e0165d9bc67fc81ccb25b71ae851ee69fac331 100644 --- a/telephony/java/android/telephony/gsm/SmsMessage.java +++ b/telephony/java/android/telephony/gsm/SmsMessage.java @@ -467,7 +467,7 @@ public class SmsMessage { * units remaining until the next message. int[3] is the encoding * type that should be used for the message. */ - public static int[] calculateLength(String messageBody, boolean use7bitOnly) { + public static int[] calculateLength(CharSequence messageBody, boolean use7bitOnly) { int ret[] = new int[4]; try { @@ -502,6 +502,25 @@ public class SmsMessage { return ret; } + /** + * Calculates the number of SMS's required to encode the message body and + * the number of characters remaining until the next message, given the + * current encoding. + * + * @param messageBody the message to encode + * @param use7bitOnly if true, characters that are not part of the GSM + * alphabet are counted as a single space char. If false, a + * messageBody containing non-GSM alphabet characters is calculated + * for 16-bit encoding. + * @return an int[4] with int[0] being the number of SMS's required, int[1] + * the number of code units used, and int[2] is the number of code + * units remaining until the next message. int[3] is the encoding + * type that should be used for the message. + */ + public static int[] calculateLength(String messageBody, boolean use7bitOnly) { + return calculateLength((CharSequence)messageBody, use7bitOnly); + } + /** * Get an SMS-SUBMIT PDU for a destination address and a message @@ -541,7 +560,12 @@ public class SmsMessage { // TP-Data-Coding-Scheme // Default encoding, uncompressed - bo.write(0x00); + // To test writing messages to the SIM card, change this value 0x00 to 0x12, which + // means "bits 1 and 0 contain message class, and the class is 2". Note that this + // takes effect for the sender. In other words, messages sent by the phone with this + // change will end up on the receiver's SIM card. You can then send messages to + // yourself (on a phone with this change) and they'll end up on the SIM card. + bo.write(0x00); // (no TP-Validity-Period) diff --git a/telephony/java/com/android/internal/telephony/Connection.java b/telephony/java/com/android/internal/telephony/Connection.java index d53d4ab1887d58b34f742dbc0411c691ce1fb5d1..d83381054ea5206aa2f548c0de56f124209a2950 100644 --- a/telephony/java/com/android/internal/telephony/Connection.java +++ b/telephony/java/com/android/internal/telephony/Connection.java @@ -37,7 +37,10 @@ public abstract class Connection OUT_OF_SERVICE, /* out of service */ SIM_ERROR, /* No SIM, SIM locked, or other SIM error */ CALL_BARRED, /* call was blocked by call barrring */ - FDN_BLOCKED /* call was blocked by fixed dial number */ + FDN_BLOCKED, /* call was blocked by fixed dial number */ + CS_RESTRICTED, /* call was blocked by restricted all voice access */ + CS_RESTRICTED_NORMAL,/* call was blocked by restricted normal voice access */ + CS_RESTRICTED_EMERGENCY/* call was blocked by restricted emergency voice access */ } Object userData; diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl index 4957366fbeb813acd37aa88597ba968cb1e4e99d..2b4195ba15e19939b67dc4612aef54b7b0b898f4 100644 --- a/telephony/java/com/android/internal/telephony/ITelephony.aidl +++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl @@ -38,7 +38,7 @@ interface ITelephony { void dial(String number); /** - * Place a call to the numer. + * Place a call to the specified number. * @param number the number to be called. */ void call(String number); @@ -72,6 +72,36 @@ interface ITelephony { */ boolean endCall(); + /** + * Answer the currently-ringing call. + * + * If there's already a current active call, that call will be + * automatically put on hold. If both lines are currently in use, the + * current active call will be ended. + * + * TODO: provide a flag to let the caller specify what policy to use + * if both lines are in use. (The current behavior is hardwired to + * "answer incoming, end ongoing", which is how the CALL button + * is specced to behave.) + * + * TODO: this should be a oneway call (especially since it's called + * directly from the key queue thread). + */ + void answerRingingCall(); + + /** + * Silence the ringer if an incoming call is currently ringing. + * (If vibrating, stop the vibrator also.) + * + * It's safe to call this if the ringer has already been silenced, or + * even if there's no incoming call. (If so, this method will do nothing.) + * + * TODO: this should be a oneway call too (see above). + * (Actually *all* the methods here that return void can + * probably be oneway.) + */ + void silenceRinger(); + /** * Check if we are in either an active or holding call * @return true if the phone state is OFFHOOK. diff --git a/telephony/java/com/android/internal/telephony/Phone.java b/telephony/java/com/android/internal/telephony/Phone.java index 9a36bc147d348bfeb1f2738c06c86ab057dc9eac..05e61f290a47c884d5bddbd2dd4650efde97d903 100644 --- a/telephony/java/com/android/internal/telephony/Phone.java +++ b/telephony/java/com/android/internal/telephony/Phone.java @@ -138,8 +138,11 @@ public interface Phone { static final String REASON_PDP_RESET = "pdpReset"; static final String REASON_VOICE_CALL_ENDED = "2GVoiceCallEnded"; static final String REASON_VOICE_CALL_STARTED = "2GVoiceCallStarted"; - - // Used for band mode selction methods + static final String REASON_PS_RESTRICT_ENABLED = "psRestrictEnabled"; + static final String REASON_PS_RESTRICT_DISABLED = "psRestrictDisabled"; + static final String REASON_SIM_LOADED = "simLoaded"; + + // Used for band mode selection methods static final int BM_UNSPECIFIED = 0; // selected by baseband automatically static final int BM_EURO_BAND = 1; // GSM-900 / DCS-1800 / WCDMA-IMT-2000 static final int BM_US_BAND = 2; // GSM-850 / PCS-1900 / WCDMA-850 / WCDMA-PCS-1900 diff --git a/telephony/java/com/android/internal/telephony/WapPushOverSms.java b/telephony/java/com/android/internal/telephony/WapPushOverSms.java new file mode 100644 index 0000000000000000000000000000000000000000..2b70162aaf7615f104b4087bbc8d55709264dc4c --- /dev/null +++ b/telephony/java/com/android/internal/telephony/WapPushOverSms.java @@ -0,0 +1,227 @@ +/* + * 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. + */ + +package com.android.internal.telephony; + +import android.content.Context; +import android.content.Intent; +import android.os.PowerManager; +import android.provider.Telephony.Sms.Intents; +import android.util.Config; +import android.util.Log; +import com.android.internal.telephony.gsm.SimUtils; + + +/** + * WAP push handler class. + * + * @hide + */ +public class WapPushOverSms { + private static final String LOG_TAG = "WAP PUSH"; + + private final Context mContext; + private WspTypeDecoder pduDecoder; + private PowerManager.WakeLock mWakeLock; + + /** + * Hold the wake lock for 5 seconds, which should be enough time for + * any receiver(s) to grab its own wake lock. + */ + private final int WAKE_LOCK_TIMEOUT = 5000; + + public WapPushOverSms(Phone phone) { + mContext = phone.getContext(); + createWakelock(); + } + + /** + * Dispatches inbound messages that are in the WAP PDU format. See + * wap-230-wsp-20010705-a section 8 for details on the WAP PDU format. + * + * @param pdu The WAP PDU, made up of one or more SMS PDUs + */ + public void dispatchWapPdu(byte[] pdu) { + + if (Config.LOGD) Log.d(LOG_TAG, "Rx: " + SimUtils.bytesToHexString(pdu)); + + int index = 0; + int transactionId = pdu[index++] & 0xFF; + int pduType = pdu[index++] & 0xFF; + int headerLength = 0; + + if ((pduType != WspTypeDecoder.PDU_TYPE_PUSH) && + (pduType != WspTypeDecoder.PDU_TYPE_CONFIRMED_PUSH)) { + if (Config.LOGD) Log.w(LOG_TAG, "Received non-PUSH WAP PDU. Type = " + pduType); + return; + } + + pduDecoder = new WspTypeDecoder(pdu); + + /** + * Parse HeaderLen(unsigned integer). + * From wap-230-wsp-20010705-a section 8.1.2 + * The maximum size of a uintvar is 32 bits. + * So it will be encoded in no more than 5 octets. + */ + if (pduDecoder.decodeUintvarInteger(index) == false) { + if (Config.LOGD) Log.w(LOG_TAG, "Received PDU. Header Length error."); + return; + } + headerLength = (int)pduDecoder.getValue32(); + index += pduDecoder.getDecodedDataLength(); + + int headerStartIndex = index; + + /** + * Parse Content-Type. + * From wap-230-wsp-20010705-a section 8.4.2.24 + * + * Content-type-value = Constrained-media | Content-general-form + * Content-general-form = Value-length Media-type + * Media-type = (Well-known-media | Extension-Media) *(Parameter) + * Value-length = Short-length | (Length-quote Length) + * Short-length = (octet <= WAP_PDU_SHORT_LENGTH_MAX) + * Length-quote = (WAP_PDU_LENGTH_QUOTE) + * Length = Uintvar-integer + */ + if (pduDecoder.decodeContentType(index) == false) { + if (Config.LOGD) Log.w(LOG_TAG, "Received PDU. Header Content-Type error."); + return; + } + int binaryContentType; + String mimeType = pduDecoder.getValueString(); + if (mimeType == null) { + binaryContentType = (int)pduDecoder.getValue32(); + switch (binaryContentType) { + case WspTypeDecoder.CONTENT_TYPE_B_DRM_RIGHTS_XML: + mimeType = WspTypeDecoder.CONTENT_MIME_TYPE_B_DRM_RIGHTS_XML; + break; + case WspTypeDecoder.CONTENT_TYPE_B_DRM_RIGHTS_WBXML: + mimeType = WspTypeDecoder.CONTENT_MIME_TYPE_B_DRM_RIGHTS_WBXML; + break; + case WspTypeDecoder.CONTENT_TYPE_B_PUSH_SI: + mimeType = WspTypeDecoder.CONTENT_MIME_TYPE_B_PUSH_SI; + break; + case WspTypeDecoder.CONTENT_TYPE_B_PUSH_SL: + mimeType = WspTypeDecoder.CONTENT_MIME_TYPE_B_PUSH_SL; + break; + case WspTypeDecoder.CONTENT_TYPE_B_PUSH_CO: + mimeType = WspTypeDecoder.CONTENT_MIME_TYPE_B_PUSH_CO; + break; + case WspTypeDecoder.CONTENT_TYPE_B_MMS: + mimeType = WspTypeDecoder.CONTENT_MIME_TYPE_B_MMS; + break; + default: + if (Config.LOGD) { + Log.w(LOG_TAG, + "Received PDU. Unsupported Content-Type = " + binaryContentType); + } + return; + } + } else { + if (mimeType.equals(WspTypeDecoder.CONTENT_MIME_TYPE_B_DRM_RIGHTS_XML)) { + binaryContentType = WspTypeDecoder.CONTENT_TYPE_B_DRM_RIGHTS_XML; + } else if (mimeType.equals(WspTypeDecoder.CONTENT_MIME_TYPE_B_DRM_RIGHTS_WBXML)) { + binaryContentType = WspTypeDecoder.CONTENT_TYPE_B_DRM_RIGHTS_WBXML; + } else if (mimeType.equals(WspTypeDecoder.CONTENT_MIME_TYPE_B_PUSH_SI)) { + binaryContentType = WspTypeDecoder.CONTENT_TYPE_B_PUSH_SI; + } else if (mimeType.equals(WspTypeDecoder.CONTENT_MIME_TYPE_B_PUSH_SL)) { + binaryContentType = WspTypeDecoder.CONTENT_TYPE_B_PUSH_SL; + } else if (mimeType.equals(WspTypeDecoder.CONTENT_MIME_TYPE_B_PUSH_CO)) { + binaryContentType = WspTypeDecoder.CONTENT_TYPE_B_PUSH_CO; + } else if (mimeType.equals(WspTypeDecoder.CONTENT_MIME_TYPE_B_MMS)) { + binaryContentType = WspTypeDecoder.CONTENT_TYPE_B_MMS; + } else { + if (Config.LOGD) Log.w(LOG_TAG, "Received PDU. Unknown Content-Type = " + mimeType); + return; + } + } + index += pduDecoder.getDecodedDataLength(); + + int dataIndex = headerStartIndex + headerLength; + boolean dispatchedByApplication = false; + switch (binaryContentType) { + case WspTypeDecoder.CONTENT_TYPE_B_PUSH_CO: + dispatchWapPdu_PushCO(pdu, transactionId, pduType); + dispatchedByApplication = true; + break; + case WspTypeDecoder.CONTENT_TYPE_B_MMS: + dispatchWapPdu_MMS(pdu, transactionId, pduType, dataIndex); + dispatchedByApplication = true; + break; + default: + break; + } + if (dispatchedByApplication == false) { + dispatchWapPdu_default(pdu, transactionId, pduType, mimeType, dataIndex); + } + } + + private void dispatchWapPdu_default( + byte[] pdu, int transactionId, int pduType, String mimeType, int dataIndex) { + byte[] data; + + data = new byte[pdu.length - dataIndex]; + System.arraycopy(pdu, dataIndex, data, 0, data.length); + + Intent intent = new Intent(Intents.WAP_PUSH_RECEIVED_ACTION); + intent.setType(mimeType); + intent.putExtra("transactionId", transactionId); + intent.putExtra("pduType", pduType); + intent.putExtra("data", data); + + sendBroadcast(intent, "android.permission.RECEIVE_WAP_PUSH"); + } + + private void dispatchWapPdu_PushCO(byte[] pdu, int transactionId, int pduType) { + Intent intent = new Intent(Intents.WAP_PUSH_RECEIVED_ACTION); + intent.setType(WspTypeDecoder.CONTENT_MIME_TYPE_B_PUSH_CO); + intent.putExtra("transactionId", transactionId); + intent.putExtra("pduType", pduType); + intent.putExtra("data", pdu); + + sendBroadcast(intent, "android.permission.RECEIVE_WAP_PUSH"); + } + + private void dispatchWapPdu_MMS(byte[] pdu, int transactionId, int pduType, int dataIndex) { + byte[] data; + + data = new byte[pdu.length - dataIndex]; + System.arraycopy(pdu, dataIndex, data, 0, data.length); + + Intent intent = new Intent(Intents.WAP_PUSH_RECEIVED_ACTION); + intent.setType(WspTypeDecoder.CONTENT_MIME_TYPE_B_MMS); + intent.putExtra("transactionId", transactionId); + intent.putExtra("pduType", pduType); + intent.putExtra("data", data); + + sendBroadcast(intent, "android.permission.RECEIVE_MMS"); + } + + private void createWakelock() { + PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); + mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WapPushOverSms"); + mWakeLock.setReferenceCounted(true); + } + + private void sendBroadcast(Intent intent, String permission) { + // Hold a wake lock for WAKE_LOCK_TIMEOUT seconds, enough to give any + // receivers time to take their own wake locks. + mWakeLock.acquire(WAKE_LOCK_TIMEOUT); + mContext.sendBroadcast(intent, permission); + } +} diff --git a/telephony/java/com/android/internal/telephony/WspTypeDecoder.java b/telephony/java/com/android/internal/telephony/WspTypeDecoder.java new file mode 100644 index 0000000000000000000000000000000000000000..2984fa8a576cd6ab1d7c62d027a476a52f6585cc --- /dev/null +++ b/telephony/java/com/android/internal/telephony/WspTypeDecoder.java @@ -0,0 +1,344 @@ +/* + * 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. + */ + +package com.android.internal.telephony; + + +/** + * Implement the WSP data type decoder. + * + * @hide + */ +public class WspTypeDecoder { + + private static final int WAP_PDU_SHORT_LENGTH_MAX = 30; + private static final int WAP_PDU_LENGTH_QUOTE = 31; + + public static final int PDU_TYPE_PUSH = 0x06; + public static final int PDU_TYPE_CONFIRMED_PUSH = 0x07; + + public static final int CONTENT_TYPE_B_DRM_RIGHTS_XML = 0x4a; + public static final int CONTENT_TYPE_B_DRM_RIGHTS_WBXML = 0x4b; + public static final int CONTENT_TYPE_B_PUSH_SI = 0x2e; + public static final int CONTENT_TYPE_B_PUSH_SL = 0x30; + public static final int CONTENT_TYPE_B_PUSH_CO = 0x32; + public static final int CONTENT_TYPE_B_MMS = 0x3e; + + public static final String CONTENT_MIME_TYPE_B_DRM_RIGHTS_XML = + "application/vnd.oma.drm.rights+xml"; + public static final String CONTENT_MIME_TYPE_B_DRM_RIGHTS_WBXML = + "application/vnd.oma.drm.rights+wbxml"; + public static final String CONTENT_MIME_TYPE_B_PUSH_SI = "application/vnd.wap.sic"; + public static final String CONTENT_MIME_TYPE_B_PUSH_SL = "application/vnd.wap.slc"; + public static final String CONTENT_MIME_TYPE_B_PUSH_CO = "application/vnd.wap.coc"; + public static final String CONTENT_MIME_TYPE_B_MMS = "application/vnd.wap.mms-message"; + + public static final int PARAMETER_ID_X_WAP_APPLICATION_ID = 0x2f; + + + byte[] wspData; + int dataLength; + long unsigned32bit; + String stringValue; + + public WspTypeDecoder(byte[] pdu) { + wspData = pdu; + } + + /** + * Decode the "Text-string" type for WSP pdu + * + * @param startIndex The starting position of the "Text-string" in this pdu + * + * @return false when error(not a Text-string) occur + * return value can be retrieved by getValueString() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeTextString(int startIndex) { + int index = startIndex; + while (wspData[index] != 0) { + index++; + } + dataLength = index - startIndex + 1; + if (wspData[startIndex] == 127) { + stringValue = new String(wspData, startIndex+1, dataLength - 2); + } else { + stringValue = new String(wspData, startIndex, dataLength - 1); + } + return true; + } + + /** + * Decode the "Short-integer" type for WSP pdu + * + * @param startIndex The starting position of the "Short-integer" in this pdu + * + * @return false when error(not a Short-integer) occur + * return value can be retrieved by getValue32() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeShortInteger(int startIndex) { + if ((wspData[startIndex] & 0x80) == 0) { + return false; + } + unsigned32bit = wspData[startIndex] & 0x7f; + dataLength = 1; + return true; + } + + /** + * Decode the "Long-integer" type for WSP pdu + * + * @param startIndex The starting position of the "Long-integer" in this pdu + * + * @return false when error(not a Long-integer) occur + * return value can be retrieved by getValue32() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeLongInteger(int startIndex) { + int lengthMultiOctet = wspData[startIndex] & 0xff; + + if (lengthMultiOctet > WAP_PDU_SHORT_LENGTH_MAX) { + return false; + } + unsigned32bit = 0; + for (int i=1; i<=lengthMultiOctet; i++) { + unsigned32bit = (unsigned32bit << 8) | (wspData[startIndex+i] & 0xff); + } + dataLength = 1+lengthMultiOctet; + return true; + } + + /** + * Decode the "Integer-Value" type for WSP pdu + * + * @param startIndex The starting position of the "Integer-Value" in this pdu + * + * @return false when error(not a Integer-Value) occur + * return value can be retrieved by getValue32() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeIntegerValue(int startIndex) { + if (decodeShortInteger(startIndex) == true) { + return true; + } + return decodeLongInteger(startIndex); + } + + /** + * Decode the "Uintvar-integer" type for WSP pdu + * + * @param startIndex The starting position of the "Uintvar-integer" in this pdu + * + * @return false when error(not a Uintvar-integer) occur + * return value can be retrieved by getValue32() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeUintvarInteger(int startIndex) { + int index = startIndex; + + unsigned32bit = 0; + while ((wspData[index] & 0x80) != 0) { + if ((index - startIndex) >= 4) { + return false; + } + unsigned32bit = (unsigned32bit << 7) | (wspData[index] & 0x7f); + index++; + } + unsigned32bit = (unsigned32bit << 7) | (wspData[index] & 0x7f); + dataLength = index - startIndex + 1; + return true; + } + + /** + * Decode the "Value-length" type for WSP pdu + * + * @param startIndex The starting position of the "Value-length" in this pdu + * + * @return false when error(not a Value-length) occur + * return value can be retrieved by getValue32() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeValueLength(int startIndex) { + if ((wspData[startIndex] & 0xff) > WAP_PDU_LENGTH_QUOTE) { + return false; + } + if (wspData[startIndex] < WAP_PDU_LENGTH_QUOTE) { + unsigned32bit = wspData[startIndex]; + dataLength = 1; + } else { + decodeUintvarInteger(startIndex+1); + dataLength ++; + } + return true; + } + + /** + * Decode the "Extension-media" type for WSP pdu + * + * @param startIndex The starting position of the "Extension-media" in this pdu + * + * @return false when error(not a Extension-media) occur + * return value can be retrieved by getValueString() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeExtensionMedia(int startIndex) { + int index = startIndex; + while (wspData[index] != 0) { + index++; + } + dataLength = index - startIndex + 1; + stringValue = new String(wspData, startIndex, dataLength - 1); + return true; + } + + /** + * Decode the "Constrained-encoding" type for WSP pdu + * + * @param startIndex The starting position of the "Constrained-encoding" in this pdu + * + * @return false when error(not a Constrained-encoding) occur + * return value can be retrieved first by getValueString() and second by getValue32() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeConstrainedEncoding(int startIndex) { + if (decodeShortInteger(startIndex) == true) { + stringValue = null; + return true; + } + return decodeExtensionMedia(startIndex); + } + + /** + * Decode the "Content-type" type for WSP pdu + * + * @param startIndex The starting position of the "Content-type" in this pdu + * + * @return false when error(not a Content-type) occur + * return value can be retrieved first by getValueString() and second by getValue32() + * method length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeContentType(int startIndex) { + int mediaPrefixLength; + long mediaFieldLength; + + if (decodeValueLength(startIndex) == false) { + return decodeConstrainedEncoding(startIndex); + } + mediaPrefixLength = getDecodedDataLength(); + mediaFieldLength = getValue32(); + if (decodeIntegerValue(startIndex + mediaPrefixLength) == true) { + dataLength += mediaPrefixLength; + stringValue = null; + return true; + } + if (decodeExtensionMedia(startIndex + mediaPrefixLength) == true) { + dataLength += mediaPrefixLength; + return true; + } + return false; + } + + /** + * Decode the "Content length" type for WSP pdu + * + * @param startIndex The starting position of the "Content length" in this pdu + * + * @return false when error(not a Content length) occur + * return value can be retrieved by getValue32() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeContentLength(int startIndex) { + return decodeIntegerValue(startIndex); + } + + /** + * Decode the "Content location" type for WSP pdu + * + * @param startIndex The starting position of the "Content location" in this pdu + * + * @return false when error(not a Content location) occur + * return value can be retrieved by getValueString() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeContentLocation(int startIndex) { + return decodeTextString(startIndex); + } + + /** + * Decode the "X-Wap-Application-Id" type for WSP pdu + * + * @param startIndex The starting position of the "X-Wap-Application-Id" in this pdu + * + * @return false when error(not a X-Wap-Application-Id) occur + * return value can be retrieved first by getValueString() and second by getValue32() + * method length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeXWapApplicationId(int startIndex) { + if (decodeIntegerValue(startIndex) == true) { + stringValue = null; + return true; + } + return decodeTextString(startIndex); + } + + /** + * Decode the "X-Wap-Content-URI" type for WSP pdu + * + * @param startIndex The starting position of the "X-Wap-Content-URI" in this pdu + * + * @return false when error(not a X-Wap-Content-URI) occur + * return value can be retrieved by getValueString() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeXWapContentURI(int startIndex) { + return decodeTextString(startIndex); + } + + /** + * Decode the "X-Wap-Initiator-URI" type for WSP pdu + * + * @param startIndex The starting position of the "X-Wap-Initiator-URI" in this pdu + * + * @return false when error(not a X-Wap-Initiator-URI) occur + * return value can be retrieved by getValueString() method + * length of data in pdu can be retrieved by getValue32() method + */ + public boolean decodeXWapInitiatorURI(int startIndex) { + return decodeTextString(startIndex); + } + + /** + * The data length of latest operation. + */ + public int getDecodedDataLength() { + return dataLength; + } + + /** + * The 32-bits result of latest operation. + */ + public long getValue32() { + return unsigned32bit; + } + + /** + * The String result of latest operation. + */ + public String getValueString() { + return stringValue; + } +} diff --git a/telephony/java/com/android/internal/telephony/gsm/BaseCommands.java b/telephony/java/com/android/internal/telephony/gsm/BaseCommands.java index 58a5bba4850302e857876e6ad091365d64d95f6d..8e14b4339ff24eeaca17e2e224b06f14c9e627c4 100644 --- a/telephony/java/com/android/internal/telephony/gsm/BaseCommands.java +++ b/telephony/java/com/android/internal/telephony/gsm/BaseCommands.java @@ -67,6 +67,8 @@ public abstract class BaseCommands implements CommandsInterface protected Registrant mSimRefreshRegistrant; /** Registrant for handling RING notifications */ protected Registrant mRingRegistrant; + /** Registrant for handling RESTRICTED STATE changed notification */ + protected Registrant mRestrictedStateRegistrant; public BaseCommands(Context context) { mContext = context; // May be null (if so we won't log statistics) @@ -279,6 +281,12 @@ public abstract class BaseCommands implements CommandsInterface mRingRegistrant = new Registrant (h, what, obj); } + public void + setOnRestrictedStateChanged(Handler h, int what, Object obj) + { + mRestrictedStateRegistrant = new Registrant (h, what, obj); + } + //***** Protected Methods /** * Store new RadioState and send notification based on the changes diff --git a/telephony/java/com/android/internal/telephony/gsm/CallTracker.java b/telephony/java/com/android/internal/telephony/gsm/CallTracker.java index afd11c47094d11ca0c21a995f4ece02806528209..2d716bb54b538b5929990b86fab0ae111ae702fa 100644 --- a/telephony/java/com/android/internal/telephony/gsm/CallTracker.java +++ b/telephony/java/com/android/internal/telephony/gsm/CallTracker.java @@ -51,10 +51,7 @@ public final class CallTracker extends Handler private static final boolean REPEAT_POLLING = false; private static final boolean DBG_POLL = false; - - // Event Log Tags - private static final int EVENT_LOG_CALL_DROP = 50106; - + //***** Constants static final int POLL_DELAY_MSEC = 250; @@ -62,17 +59,17 @@ public final class CallTracker extends Handler static final int MAX_CONNECTIONS_PER_CALL = 5; // only 5 connections allowed per call //***** Instance Variables - + GSMConnection connections[] = new GSMConnection[MAX_CONNECTIONS]; RegistrantList voiceCallEndedRegistrants = new RegistrantList(); RegistrantList voiceCallStartedRegistrants = new RegistrantList(); // connections dropped durin last poll - ArrayList droppedDuringPoll - = new ArrayList(MAX_CONNECTIONS); + ArrayList droppedDuringPoll + = new ArrayList(MAX_CONNECTIONS); - GSMCall ringingCall = new GSMCall(this); + GSMCall ringingCall = new GSMCall(this); // A call that is ringing or (call) waiting GSMCall foregroundCall = new GSMCall(this); GSMCall backgroundCall = new GSMCall(this); @@ -172,13 +169,13 @@ public final class CallTracker extends Handler // for the newly dialed connection switchWaitingOrHoldingAndActive(); - // Fake local state so that + // Fake local state so that // a) foregroundCall is empty for the newly dialed connection // b) hasNonHangupStateChanged remains false in the // next poll, so that we don't clear a failed dialing call fakeHoldForegroundBeforeDial(); - } - + } + if (foregroundCall.getState() != Call.State.IDLE) { //we should have failed in !canDial() above before we get here throw new CallStateException("cannot dial in current state"); @@ -194,22 +191,22 @@ public final class CallTracker extends Handler pendingMO.cause = Connection.DisconnectCause.INVALID_NUMBER; // handlePollCalls() will notice this call not present - // and will mark it as dropped. + // and will mark it as dropped. pollCallsWhenSafe(); } else { // Always unmute when initiating a new call setMute(false); - cm.dial(pendingMO.address, clirMode, obtainCompleteMessage()); + cm.dial(pendingMO.address, clirMode, obtainCompleteMessage()); } updatePhoneState(); phone.notifyCallStateChanged(); - + return pendingMO; } - + Connection dial (String dialString) throws CallStateException { @@ -222,7 +219,7 @@ public final class CallTracker extends Handler // FIXME if SWITCH fails, should retry with ANSWER // in case the active/holding call disappeared and this // is no longer call waiting - + if (ringingCall.getState() == Call.State.INCOMING) { Log.i("phone", "acceptCall: incoming..."); // Always unmute when answering a new call @@ -270,7 +267,7 @@ public final class CallTracker extends Handler { cm.explicitCallTransfer(obtainCompleteMessage(EVENT_ECT_RESULT)); } - + void clearDisconnected() { @@ -280,7 +277,7 @@ public final class CallTracker extends Handler phone.notifyCallStateChanged(); } - boolean + boolean canConference() { return foregroundCall.getState() == Call.State.ACTIVE @@ -312,13 +309,13 @@ public final class CallTracker extends Handler } //***** Private Instance Methods - + private void internalClearDisconnected() { ringingCall.clearDisconnected(); foregroundCall.clearDisconnected(); - backgroundCall.clearDisconnected(); + backgroundCall.clearDisconnected(); } /** @@ -364,7 +361,7 @@ public final class CallTracker extends Handler /** * Obtain a complete message that indicates that this operation * does not require polling of getCurrentCalls(). However, if other - * operations that do need getCurrentCalls() are pending or are + * operations that do need getCurrentCalls() are pending or are * scheduled while this operation is pending, the invocatoin * of getCurrentCalls() will be postponed until this * operation is also complete. @@ -382,20 +379,20 @@ public final class CallTracker extends Handler operationComplete() { pendingOperations--; - + if (DBG_POLL) log("operationComplete: pendingOperations=" + pendingOperations + ", needsPoll=" + needsPoll); if (pendingOperations == 0 && needsPoll) { lastRelevantPoll = obtainMessage(EVENT_POLL_CALLS_RESULT); - cm.getCurrentCalls(lastRelevantPoll); + cm.getCurrentCalls(lastRelevantPoll); } else if (pendingOperations < 0) { // this should never happen Log.e(LOG_TAG,"CallTracker.pendingOperations < 0"); pendingOperations = 0; } } - + private void pollCallsWhenSafe() { @@ -403,10 +400,10 @@ public final class CallTracker extends Handler if (checkNoOperationsPending()) { lastRelevantPoll = obtainMessage(EVENT_POLL_CALLS_RESULT); - cm.getCurrentCalls(lastRelevantPoll); + cm.getCurrentCalls(lastRelevantPoll); } } - + private void pollCallsAfterDelay() { @@ -428,7 +425,7 @@ public final class CallTracker extends Handler updatePhoneState() { Phone.State oldState = state; - + if (ringingCall.isRinging()) { state = Phone.State.RINGING; } else if (pendingMO != null || @@ -436,7 +433,7 @@ public final class CallTracker extends Handler state = Phone.State.OFFHOOK; } else { state = Phone.State.IDLE; - } + } if (state == Phone.State.IDLE && oldState != state) { voiceCallEndedRegistrants.notifyRegistrants( @@ -475,7 +472,7 @@ public final class CallTracker extends Handler boolean needsPollDelay = false; boolean unknownConnectionAppeared = false; - for (int i = 0, curDC = 0, dcSize = polledCalls.size() + for (int i = 0, curDC = 0, dcSize = polledCalls.size() ; i < connections.length; i++) { GSMConnection conn = connections[i]; DriverCall dc = null; @@ -532,7 +529,7 @@ public final class CallTracker extends Handler // which is neither a ringing call or one we created. // Either we've crashed and re-attached to an existing // call, or something else (eg, SIM) initiated the call. - + Log.i(LOG_TAG,"Phantom call appeared " + dc); // If it's a connected call, set the connect time so that @@ -549,8 +546,8 @@ public final class CallTracker extends Handler hasNonHangupStateChanged = true; } else if (conn != null && dc == null) { // Connection missing in CLCC response that we were - // tracking. - droppedDuringPoll.add(conn); + // tracking. + droppedDuringPoll.add(conn); // Dropped connections are removed from the CallTracker // list but kept in the GSMCall list connections[i] = null; @@ -558,7 +555,7 @@ public final class CallTracker extends Handler // Connection in CLCC response does not match what // we were tracking. Assume dropped call and new call - droppedDuringPoll.add(conn); + droppedDuringPoll.add(conn); connections[i] = new GSMConnection (phone.getContext(), dc, this, i); if (connections[i].getCall() == ringingCall) { @@ -594,11 +591,11 @@ public final class CallTracker extends Handler // This is the first poll after an ATD. // We expect the pending call to appear in the list // If it does not, we land here - if (pendingMO != null) { - Log.d(LOG_TAG,"Pending MO dropped before poll fg state:" + if (pendingMO != null) { + Log.d(LOG_TAG,"Pending MO dropped before poll fg state:" + foregroundCall.getState()); - droppedDuringPoll.add(pendingMO); + droppedDuringPoll.add(pendingMO); pendingMO = null; hangupPendingMO = false; } @@ -619,7 +616,7 @@ public final class CallTracker extends Handler if (conn.cause == Connection.DisconnectCause.LOCAL) { cause = Connection.DisconnectCause.INCOMING_REJECTED; } else { - cause = Connection.DisconnectCause.INCOMING_MISSED; + cause = Connection.DisconnectCause.INCOMING_MISSED; } if (Phone.DEBUG_PHONE) { @@ -690,7 +687,7 @@ public final class CallTracker extends Handler dumpState() { List l; - + Log.i(LOG_TAG,"Phone State:" + state); Log.i(LOG_TAG,"Ringing call: " + ringingCall.toString()); @@ -722,7 +719,7 @@ public final class CallTracker extends Handler hangup (GSMConnection conn) throws CallStateException { if (conn.owner != this) { - throw new CallStateException ("Connection " + conn + throw new CallStateException ("Connection " + conn + "does not belong to CallTracker " + this); } @@ -731,14 +728,14 @@ public final class CallTracker extends Handler // GSM index assigned yet if (Phone.DEBUG_PHONE) log("hangup: set hangupPendingMO to true"); - hangupPendingMO = true; + hangupPendingMO = true; } else { - try { + try { cm.hangupConnection (conn.getGSMIndex(), obtainCompleteMessage()); } catch (CallStateException ex) { // Ignore "connection not found" // Call may have hung up already - Log.w(LOG_TAG,"CallTracker WARN: hangup() on absent connection " + Log.w(LOG_TAG,"CallTracker WARN: hangup() on absent connection " + conn); } } @@ -750,16 +747,16 @@ public final class CallTracker extends Handler separate (GSMConnection conn) throws CallStateException { if (conn.owner != this) { - throw new CallStateException ("Connection " + conn + throw new CallStateException ("Connection " + conn + "does not belong to CallTracker " + this); } try { - cm.separateConnection (conn.getGSMIndex(), + cm.separateConnection (conn.getGSMIndex(), obtainCompleteMessage(EVENT_SEPARATE_RESULT)); } catch (CallStateException ex) { // Ignore "connection not found" // Call may have hung up already - Log.w(LOG_TAG,"CallTracker WARN: separate() on absent connection " + Log.w(LOG_TAG,"CallTracker WARN: separate() on absent connection " + conn); } } @@ -772,14 +769,14 @@ public final class CallTracker extends Handler desiredMute = mute; cm.setMute(desiredMute, null); } - + /*package*/ boolean getMute() { return desiredMute; } - + //***** Called from GSMCall /* package */ void @@ -886,11 +883,11 @@ public final class CallTracker extends Handler //****** Overridden from Handler - public void + public void handleMessage (Message msg) { AsyncResult ar; - + switch (msg.what) { case EVENT_POLL_CALLS_RESULT: ar = (AsyncResult)msg.obj; @@ -924,7 +921,7 @@ public final class CallTracker extends Handler int causeCode; ar = (AsyncResult)msg.obj; - operationComplete(); + operationComplete(); if (ar.exception != null) { // An exception occurred...just treat the disconnect @@ -936,7 +933,7 @@ public final class CallTracker extends Handler causeCode = ((int[])ar.result)[0]; } // Log the causeCode if its not normal - if (causeCode == CallFailCause.NO_CIRCUIT_AVAIL || + if (causeCode == CallFailCause.NO_CIRCUIT_AVAIL || causeCode == CallFailCause.TEMPORARY_FAILURE || causeCode == CallFailCause.SWITCHING_CONGESTION || causeCode == CallFailCause.CHANNEL_NOT_AVAIL || @@ -946,12 +943,12 @@ public final class CallTracker extends Handler int cid = -1; GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); if (loc != null) cid = loc.getCid(); - - EventLog.List val = new EventLog.List(causeCode, cid, + + EventLog.List val = new EventLog.List(causeCode, cid, TelephonyManager.getDefault().getNetworkType()); - EventLog.writeEvent(EVENT_LOG_CALL_DROP, val); + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_CALL_DROP, val); } - + for (int i = 0, s = droppedDuringPoll.size() ; i < s ; i++ ) { diff --git a/telephony/java/com/android/internal/telephony/gsm/CommandsInterface.java b/telephony/java/com/android/internal/telephony/gsm/CommandsInterface.java index c7b08d215381bf3c747467a7854350287c809b2f..791579835cde9e1dbacd4bd197bc71390f34921e 100644 --- a/telephony/java/com/android/internal/telephony/gsm/CommandsInterface.java +++ b/telephony/java/com/android/internal/telephony/gsm/CommandsInterface.java @@ -282,6 +282,17 @@ public interface CommandsInterface */ void setOnCallRing(Handler h, int what, Object obj); + /** + * Sets the handler for RESTRICTED_STATE changed notification, + * eg, for Domain Specific Access Control + * unlike the register* methods, there's only one signal strength handler + * + * AsyncResult.result is an int[1] + * response.obj.result[0] is a bitmask of RIL_RESTRICTED_STATE_* values + */ + + void setOnRestrictedStateChanged(Handler h, int what, Object obj); + /** * Sets the handler for Supplementary Service Notifications. * Unlike the register* methods, there's only one notification handler diff --git a/telephony/java/com/android/internal/telephony/gsm/DataConnectionTracker.java b/telephony/java/com/android/internal/telephony/gsm/DataConnectionTracker.java index b0b8cdca421486b3945cc33561d19077ea52a09b..30b1be89a75f5af4566616cc724ef3e3ad91a557 100644 --- a/telephony/java/com/android/internal/telephony/gsm/DataConnectionTracker.java +++ b/telephony/java/com/android/internal/telephony/gsm/DataConnectionTracker.java @@ -16,11 +16,6 @@ package com.android.internal.telephony.gsm; -import static com.android.internal.telephony.TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE; -import static com.android.internal.telephony.gsm.ServiceStateTracker.DATA_ACCESS_EDGE; -import static com.android.internal.telephony.gsm.ServiceStateTracker.DATA_ACCESS_GPRS; -import static com.android.internal.telephony.gsm.ServiceStateTracker.DATA_ACCESS_UMTS; -import static com.android.internal.telephony.gsm.ServiceStateTracker.DATA_ACCESS_UNKNOWN; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; @@ -31,6 +26,8 @@ import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; +import android.net.NetworkInfo; +import android.net.wifi.WifiManager; import android.os.AsyncResult; import android.os.Handler; import android.os.INetStatService; @@ -50,13 +47,10 @@ import android.telephony.gsm.GsmCellLocation; import android.text.TextUtils; import android.util.EventLog; import android.util.Log; -import android.util.EventLog.List; import com.android.internal.telephony.Phone; import com.android.internal.telephony.gsm.PdpConnection.PdpFailCause; -import android.net.wifi.WifiManager; -import android.net.NetworkInfo; - + import java.io.IOException; import java.util.ArrayList; @@ -128,7 +122,8 @@ final class DataConnectionTracker extends Handler Handler mDataConnectionTracker = null; private ContentResolver mResolver; - int txPkts, rxPkts, sentSinceLastRecv, netStatPollPeriod; + long txPkts, rxPkts, sentSinceLastRecv; + int netStatPollPeriod; private int mNoRecvPollCount = 0; private boolean mPingTestActive = false; // Count of PDP reset attempts; reset when we see incoming, @@ -161,7 +156,7 @@ final class DataConnectionTracker extends Handler /** CID of active PDP */ int cidActive; - + /** Currently requested APN type */ private String mRequestedApnType = Phone.APN_TYPE_DEFAULT; @@ -177,11 +172,14 @@ final class DataConnectionTracker extends Handler private boolean[] dataEnabled = new boolean[APN_NUM_TYPES]; - // wifi connection status will be updated by sticky intent + /** wifi connection status will be updated by sticky intent */ private boolean mIsWifiConnected = false; /** Intent sent when the reconnect alarm fires. */ private PendingIntent mReconnectIntent = null; + + /** Is packet service restricted by network */ + private boolean mIsPsRestricted = false; //***** Constants @@ -201,9 +199,9 @@ final class DataConnectionTracker extends Handler private static final int POLL_NETSTAT_SLOW_MILLIS = 5000; /** Default ping deadline, in seconds. */ - private final int DEFAULT_PING_DEADLINE = 5; + private static final int DEFAULT_PING_DEADLINE = 5; /** Default max failure count before attempting to network re-registration. */ - private final int DEFAULT_MAX_PDP_RESET_FAIL = 3; + private static final int DEFAULT_MAX_PDP_RESET_FAIL = 3; /** * After detecting a potential connection problem, this is the max number @@ -232,13 +230,6 @@ final class DataConnectionTracker extends Handler private static final String INTENT_RECONNECT_ALARM_EXTRA_REASON = "reason"; - //***** Tag IDs for EventLog - private static final int EVENT_LOG_RADIO_RESET_COUNTDOWN_TRIGGERED = 50101; - private static final int EVENT_LOG_RADIO_RESET = 50102; - private static final int EVENT_LOG_PDP_RESET = 50103; - private static final int EVENT_LOG_REREGISTER_NETWORK = 50104; - private static final int EVENT_LOG_RADIO_PDP_SETUP_FAIL = 50105; - //***** Event Codes static final int EVENT_DATA_SETUP_COMPLETE = 1; static final int EVENT_RADIO_AVAILABLE = 3; @@ -261,6 +252,8 @@ final class DataConnectionTracker extends Handler static final int EVENT_START_NETSTAT_POLL = 27; static final int EVENT_START_RECOVERY = 28; static final int EVENT_APN_CHANGED = 29; + static final int EVENT_PS_RESTRICT_ENABLED = 30; + static final int EVENT_PS_RESTRICT_DISABLED = 31; BroadcastReceiver mIntentReceiver = new BroadcastReceiver () { @@ -319,6 +312,8 @@ final class DataConnectionTracker extends Handler phone.mSST.registerForGprsDetached(this, EVENT_GPRS_DETACHED, null); phone.mSST.registerForRoamingOn(this, EVENT_ROAMING_ON, null); phone.mSST.registerForRoamingOff(this, EVENT_ROAMING_OFF, null); + phone.mSST.registerForPsRestrictedEnabled(this, EVENT_PS_RESTRICT_ENABLED, null); + phone.mSST.registerForPsRestrictedDisabled(this, EVENT_PS_RESTRICT_DISABLED, null); this.netstat = INetStatService.Stub.asInterface(ServiceManager.getService("netstat")); @@ -486,6 +481,7 @@ final class DataConnectionTracker extends Handler * 2. registered to gprs service * 3. user doesn't explicitly disable data service * 4. wifi is not on + * 5. packet service is not restricted * * @return false while no data connection if all above requirements are met. */ @@ -495,12 +491,13 @@ final class DataConnectionTracker extends Handler if (phone.mSIMRecords.getRecordsLoaded() && phone.mSST.getCurrentGprsState() == ServiceState.STATE_IN_SERVICE && (!roaming || getDataOnRoamingEnabled()) && - !mIsWifiConnected ) { + !mIsWifiConnected && + !mIsPsRestricted ) { return (state == State.CONNECTED); } return true; } - + private boolean isApnTypeActive(String type) { // TODO: to support simultaneous, mActiveApn can be a List instead. return mActiveApn != null && mActiveApn.canHandleType(type); @@ -537,7 +534,7 @@ final class DataConnectionTracker extends Handler Log.d(LOG_TAG, "dataEnabled[DEFAULT_APN]=" + dataEnabled[APN_DEFAULT_ID] + " dataEnabled[MMS_APN]=" + dataEnabled[APN_MMS_ID]); } - + /** * Prevent mobile data connections from being established, * or once again allow mobile data connections. If the state @@ -570,6 +567,14 @@ final class DataConnectionTracker extends Handler return true; } + /** + * Simply tear down data connections due to radio off + * and don't setup again. + */ + public void cleanConnectionBeforeRadioOff() { + cleanUpConnection(true, Phone.REASON_RADIO_TURNED_OFF); + } + /** * Report the current state of data connectivity (enabled or disabled) for * the default APN. @@ -605,7 +610,7 @@ final class DataConnectionTracker extends Handler //Retrieve the data roaming setting from the shared preferences. public boolean getDataOnRoamingEnabled() { try { - return Settings.Secure.getInt(phone.getContext().getContentResolver(), + return Settings.Secure.getInt(phone.getContext().getContentResolver(), Settings.Secure.DATA_ROAMING) > 0; } catch (SettingNotFoundException snfe) { return false; @@ -636,7 +641,7 @@ final class DataConnectionTracker extends Handler stopNetStatPoll(); phone.notifyDataConnection(Phone.REASON_GPRS_DETACHED); } - + private void onGprsAttached() { if (state == State.CONNECTED) { startNetStatPoll(); @@ -654,6 +659,8 @@ final class DataConnectionTracker extends Handler { if (DBG) log("***trySetupData due to " + (reason == null ? "(unspecified)" : reason)); + Log.d(LOG_TAG, "[DSAC DEB] " + "trySetupData with mIsPsRestricted=" + mIsPsRestricted); + if (phone.getSimulatedRadioControl() != null) { // Assume data is connected on the simulator // FIXME this can be improved @@ -670,9 +677,9 @@ final class DataConnectionTracker extends Handler if ((state == State.IDLE || state == State.SCANNING) && (gprsState == ServiceState.STATE_IN_SERVICE || noAutoAttach) && phone.mSIMRecords.getRecordsLoaded() - && ( phone.mSST.isConcurrentVoiceAndData() || - phone.getState() == Phone.State.IDLE ) - && isDataAllowed()) { + && phone.getState() == Phone.State.IDLE + && isDataAllowed() + && !mIsPsRestricted ) { if (state == State.IDLE) { waitingApns = buildWaitingApns(); @@ -699,7 +706,8 @@ final class DataConnectionTracker extends Handler " phoneState=" + phone.getState() + " dataEnabled=" + getAnyDataEnabled() + " roaming=" + roaming + - " dataOnRoamingEnable=" + getDataOnRoamingEnabled()); + " dataOnRoamingEnable=" + getDataOnRoamingEnabled() + + " ps restricted=" + mIsPsRestricted); return false; } } @@ -746,7 +754,7 @@ final class DataConnectionTracker extends Handler * IDLE before the code below runs. If we didn't check * for that, future calls to trySetupData would fail, * and we would never get out of the DISCONNECTING state. - */ + */ if (!tearDown) { setState(State.IDLE); phone.notifyDataConnection(reason); @@ -888,6 +896,9 @@ final class DataConnectionTracker extends Handler isConnected = (state != State.IDLE && state != State.FAILED); + // The "current" may no longer be valid. MMS depends on this to send properly. + phone.updateCurrentCarrierInProvider(); + // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. createAllApnList(); @@ -932,6 +943,16 @@ final class DataConnectionTracker extends Handler Log.i(LOG_TAG, "PDP connection has dropped. Reconnecting"); + // Add an event log when the network drops PDP + int cid = -1; + GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); + if (loc != null) cid = loc.getCid(); + + EventLog.List val = new EventLog.List(cid, + TelephonyManager.getDefault().getNetworkType()); + + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_NETWORK_DROP, val); + cleanUpConnection(true, null); return; @@ -964,6 +985,16 @@ final class DataConnectionTracker extends Handler Log.i(LOG_TAG, "PDP connection has dropped (active=false case). " + " Reconnecting"); + // Log the network drop on the event log. + int cid = -1; + GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); + if (loc != null) cid = loc.getCid(); + + EventLog.List val = new EventLog.List(cid, + TelephonyManager.getDefault().getNetworkType()); + + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_NETWORK_DROP, val); + cleanUpConnection(true, null); } } @@ -1040,14 +1071,14 @@ final class DataConnectionTracker extends Handler if (state == State.CONNECTED) { int maxPdpReset = Settings.Gservices.getInt(mResolver, Settings.Gservices.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT, - DEFAULT_MAX_PDP_RESET_FAIL); + DEFAULT_MAX_PDP_RESET_FAIL); if (mPdpResetCount < maxPdpReset) { mPdpResetCount++; - EventLog.writeEvent(EVENT_LOG_PDP_RESET, sentSinceLastRecv); + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_RESET, sentSinceLastRecv); cleanUpConnection(true, Phone.REASON_PDP_RESET); } else { mPdpResetCount = 0; - EventLog.writeEvent(EVENT_LOG_REREGISTER_NETWORK, sentSinceLastRecv); + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_REREGISTER_NETWORK, sentSinceLastRecv); phone.mSST.reRegisterNetwork(null); } // TODO: Add increasingly drastic recovery steps, eg, @@ -1096,8 +1127,8 @@ final class DataConnectionTracker extends Handler { public void run() { - int sent, received; - int preTxPkts = -1, preRxPkts = -1; + long sent, received; + long preTxPkts = -1, preRxPkts = -1; Activity newActivity; @@ -1105,8 +1136,8 @@ final class DataConnectionTracker extends Handler preRxPkts = rxPkts; try { - txPkts = netstat.getTxPackets(); - rxPkts = netstat.getRxPackets(); + txPkts = netstat.getMobileTxPackets(); + rxPkts = netstat.getMobileRxPackets(); } catch (RemoteException e) { txPkts = 0; rxPkts = 0; @@ -1152,7 +1183,7 @@ final class DataConnectionTracker extends Handler if (sentSinceLastRecv >= watchdogTrigger) { // we already have NUMBER_SENT_PACKETS sent without ack if (mNoRecvPollCount == 0) { - EventLog.writeEvent(EVENT_LOG_RADIO_RESET_COUNTDOWN_TRIGGERED, + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_RADIO_RESET_COUNTDOWN_TRIGGERED, sentSinceLastRecv); } @@ -1220,11 +1251,11 @@ final class DataConnectionTracker extends Handler } catch (Exception e) { Log.w(LOG_TAG, "exception trying to ping"); } - + if (status == 0) { // ping succeeded. False alarm. Reset netStatPoll. // ("-1" for this event indicates a false alarm) - EventLog.writeEvent(EVENT_LOG_PDP_RESET, -1); + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_RESET, -1); mPdpResetCount = 0; sendMessage(obtainMessage(EVENT_START_NETSTAT_POLL)); } else { @@ -1249,6 +1280,24 @@ final class DataConnectionTracker extends Handler return (shouldPost && cause != PdpConnection.PdpFailCause.UNKNOWN); } + /** + * Return true if data connection need to be setup after disconnected due to + * reason. + * + * @param reason the reason why data is disconnected + * @return true if try setup data connection is need for this reason + */ + private boolean retryAfterDisconnected(String reason) { + boolean retry = true; + + if ( Phone.REASON_RADIO_TURNED_OFF.equals(reason) || + Phone.REASON_DATA_DISABLED.equals(reason) || + Phone.REASON_PS_RESTRICT_ENABLED.equals(reason)) { + retry = false; + } + return retry; + } + private void reconnectAfterFail(PdpFailCause lastFailCauseCode, String reason) { if (state == State.FAILED) { Log.d(LOG_TAG, "PDP activate failed. Scheduling next attempt for " @@ -1301,7 +1350,7 @@ final class DataConnectionTracker extends Handler if (state == State.FAILED) { cleanUpConnection(false, null); } - sendMessage(obtainMessage(EVENT_TRY_SETUP_DATA)); + sendMessage(obtainMessage(EVENT_TRY_SETUP_DATA, Phone.REASON_SIM_LOADED)); break; case EVENT_ENABLE_NEW_APN: @@ -1312,6 +1361,10 @@ final class DataConnectionTracker extends Handler break; case EVENT_TRY_SETUP_DATA: + if (msg.obj instanceof String) { + reason = (String)msg.obj; + } + trySetupData(reason); break; @@ -1335,7 +1388,7 @@ final class DataConnectionTracker extends Handler case EVENT_GPRS_ATTACHED: onGprsAttached(); break; - + case EVENT_ROAMING_ON: if (getDataOnRoamingEnabled()) { trySetupData(Phone.REASON_ROAMING_ON); @@ -1410,7 +1463,7 @@ final class DataConnectionTracker extends Handler SystemProperties.set("gsm.defaultpdpcontext.active", "false"); } notifyDefaultData(reason); - + // TODO: For simultaneous PDP support, we need to build another // trigger another TRY_SETUP_DATA for the next APN type. (Note // that the existing connection may service that type, in which @@ -1421,7 +1474,7 @@ final class DataConnectionTracker extends Handler if(DBG) log("PDP setup failed " + cause); // Log this failure to the Event Logs. - if (cause == PdpConnection.PdpFailCause.BAD_APN || + if (cause == PdpConnection.PdpFailCause.BAD_APN || cause == PdpConnection.PdpFailCause.BAD_PAP_SECRET || cause == PdpConnection.PdpFailCause.BARRED || cause == PdpConnection.PdpFailCause.RADIO_ERROR_RETRY || @@ -1431,12 +1484,12 @@ final class DataConnectionTracker extends Handler int cid = -1; GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); if (loc != null) cid = loc.getCid(); - + EventLog.List val = new EventLog.List( - cause.ordinal(), cid, - TelephonyManager.getDefault().getNetworkType()); - EventLog.writeEvent(EVENT_LOG_RADIO_PDP_SETUP_FAIL, val); - } + cause.ordinal(), cid, + TelephonyManager.getDefault().getNetworkType()); + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_RADIO_PDP_SETUP_FAIL, val); + } // No try for permanent failure if (cause.isPermanentFail()) { notifyNoData(cause); @@ -1450,7 +1503,10 @@ final class DataConnectionTracker extends Handler } else { // we still have more apns to try setState(State.SCANNING); - trySetupData(reason); + // Wait a bit before trying the next APN, so that + // we're not tying up the RIL command channel + sendMessageDelayed(obtainMessage(EVENT_TRY_SETUP_DATA, reason), + RECONNECT_DELAY_INITIAL_MILLIS); } } else { startDelayedRetry(cause, reason); @@ -1467,7 +1523,9 @@ final class DataConnectionTracker extends Handler setState(State.IDLE); phone.notifyDataConnection(reason); mActiveApn = null; - trySetupData(reason); + if ( retryAfterDisconnected(reason) ) { + trySetupData(reason); + } break; case EVENT_PDP_STATE_CHANGED: @@ -1533,6 +1591,37 @@ final class DataConnectionTracker extends Handler case EVENT_APN_CHANGED: onApnChanged(); break; + + case EVENT_PS_RESTRICT_ENABLED: + /** + * We don't need to explicitly to tear down the PDP context + * when PS restricted is enabled. The base band will deactive + * PDP context and notify us with PDP_CONTEXT_CHANGED. + * But we should stop the network polling and prevent reset PDP. + */ + Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_ENABLED " + mIsPsRestricted); + stopNetStatPoll(); + mIsPsRestricted = true; + break; + + case EVENT_PS_RESTRICT_DISABLED: + /** + * When PS restrict is removed, we need setup PDP connection if + * PDP connection is down. + */ + Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_DISABLED " + mIsPsRestricted); + mIsPsRestricted = false; + if (state == State.CONNECTED) { + startNetStatPoll(); + } else { + if (state == State.FAILED) { + cleanUpConnection(false, Phone.REASON_PS_RESTRICT_ENABLED); + nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; + } + trySetupData(Phone.REASON_PS_RESTRICT_ENABLED); + } + break; + } } @@ -1575,7 +1664,7 @@ final class DataConnectionTracker extends Handler if (cursor != null) { if (cursor.getCount() > 0) { allApns = createApnList(cursor); - // TODO: Figure out where this fits in. This basically just + // TODO: Figure out where this fits in. This basically just // writes the pap-secrets file. No longer tied to PdpConnection // object. Not used on current platform (no ppp). //PdpConnection pdp = pdpList.get(pdp_name); @@ -1622,7 +1711,7 @@ final class DataConnectionTracker extends Handler } /** - * Get next apn in waitingApns + * Get next apn in waitingApns * @return the first apn found in waitingApns, null if none */ private ApnSetting getNextApn() { diff --git a/telephony/java/com/android/internal/telephony/gsm/GSMConnection.java b/telephony/java/com/android/internal/telephony/gsm/GSMConnection.java index 43930c10d53471dfc4526b1efa3c51f2bf771286..70e9f62f1f06a1da4741f49ed2259a967e9681f2 100644 --- a/telephony/java/com/android/internal/telephony/gsm/GSMConnection.java +++ b/telephony/java/com/android/internal/telephony/gsm/GSMConnection.java @@ -77,15 +77,15 @@ public class GSMConnection extends Connection { private PowerManager.WakeLock mPartialWakeLock; //***** Event Constants - static final int EVENT_DTMF_DONE = 1; static final int EVENT_PAUSE_DONE = 2; static final int EVENT_NEXT_POST_DIAL = 3; - + static final int EVENT_WAKE_LOCK_TIMEOUT = 4; + //***** Constants - static final int PAUSE_DELAY_FIRST_MILLIS = 100; static final int PAUSE_DELAY_MILLIS = 3 * 1000; + static final int WAKE_LOCK_TIMEOUT_MILLIS = 60*1000; //***** Inner Classes @@ -100,8 +100,10 @@ public class GSMConnection extends Connection { case EVENT_DTMF_DONE: case EVENT_PAUSE_DONE: processNextPostDialChar(); - break; - + break; + case EVENT_WAKE_LOCK_TIMEOUT: + releaseWakeLock(); + break; } } } @@ -279,7 +281,7 @@ public class GSMConnection extends Connection { return; } - postDialState = PostDialState.STARTED; + setPostDialState(PostDialState.STARTED); processNextPostDialChar(); } @@ -291,7 +293,7 @@ public class GSMConnection extends Connection { return; } - postDialState = PostDialState.STARTED; + setPostDialState(PostDialState.STARTED); if (false) { boolean playedTone = false; @@ -333,7 +335,7 @@ public class GSMConnection extends Connection { public void cancelPostDial() { - postDialState = PostDialState.CANCELLED; + setPostDialState(PostDialState.CANCELLED); } /** @@ -388,6 +390,16 @@ public class GSMConnection extends Connection { return DisconnectCause.OUT_OF_SERVICE; } else if (phone.getSimCard().getState() != GsmSimCard.State.READY) { return DisconnectCause.SIM_ERROR; + } else if (causeCode == CallFailCause.ERROR_UNSPECIFIED) { + if (phone.mSST.rs.isCsRestricted()) { + return DisconnectCause.CS_RESTRICTED; + } else if (phone.mSST.rs.isCsEmergencyRestricted()) { + return DisconnectCause.CS_RESTRICTED_EMERGENCY; + } else if (phone.mSST.rs.isCsNormalRestricted()) { + return DisconnectCause.CS_RESTRICTED_NORMAL; + } else { + return DisconnectCause.NORMAL; + } } else { return DisconnectCause.NORMAL; } @@ -562,9 +574,9 @@ public class GSMConnection extends Connection { PAUSE_DELAY_MILLIS); } } else if (c == PhoneNumberUtils.WAIT) { - postDialState = PostDialState.WAIT; + setPostDialState(PostDialState.WAIT); } else if (c == PhoneNumberUtils.WILD) { - postDialState = PostDialState.WILD; + setPostDialState(PostDialState.WILD); } else { return false; } @@ -614,14 +626,14 @@ public class GSMConnection extends Connection { if (postDialString == null || postDialString.length() <= nextPostDialChar) { - postDialState = PostDialState.COMPLETE; + setPostDialState(PostDialState.COMPLETE); // notifyMessage.arg1 is 0 on complete c = 0; } else { boolean isValid; - postDialState = PostDialState.STARTED; + setPostDialState(PostDialState.STARTED); c = postDialString.charAt(nextPostDialChar++); @@ -699,6 +711,26 @@ public class GSMConnection extends Connection { } } + /** + * Set post dial state and acquire wake lock while switching to "started" + * state, the wake lock will be released if state switches out of "started" + * state or after WAKE_LOCK_TIMEOUT_MILLIS. + * @param s new PostDialState + */ + private void setPostDialState(PostDialState s) { + if (postDialState != PostDialState.STARTED + && s == PostDialState.STARTED) { + acquireWakeLock(); + Message msg = h.obtainMessage(EVENT_WAKE_LOCK_TIMEOUT); + h.sendMessageDelayed(msg, WAKE_LOCK_TIMEOUT_MILLIS); + } else if (postDialState == PostDialState.STARTED + && s != PostDialState.STARTED) { + h.removeMessages(EVENT_WAKE_LOCK_TIMEOUT); + releaseWakeLock(); + } + postDialState = s; + } + private void createWakeLock(Context context) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); diff --git a/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java b/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java index f314944db02e86907603f94dfe6785382fc50511..f93c72469d0ed5d7a8a067023532276594f7a740 100644 --- a/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java +++ b/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java @@ -91,6 +91,8 @@ public class GSMPhone extends PhoneBase { public static final String VM_NUMBER = "vm_number_key"; // Key used to read/write the SIM IMSI used for storing the voice mail public static final String VM_SIM_IMSI = "vm_sim_imsi_key"; + // Key used to read/write "disable DNS server check" pref (used for testing) + public static final String DNS_SERVER_CHECK_DISABLED_KEY = "dns_server_check_disabled_key"; //***** Instance Variables @@ -108,6 +110,8 @@ public class GSMPhone extends PhoneBase { SimPhoneBookInterfaceManager mSimPhoneBookIntManager; SimSmsInterfaceManager mSimSmsIntManager; PhoneSubInfo mSubInfo; + boolean mDnsCheckDisabled = false; + Registrant mPostDialHandler; @@ -195,6 +199,9 @@ public class GSMPhone extends PhoneBase { mCM.setOnCallRing(h, EVENT_CALL_RING, null); mSST.registerForNetworkAttach(h, EVENT_REGISTERED_TO_NETWORK, null); + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); + mDnsCheckDisabled = sp.getBoolean(DNS_SERVER_CHECK_DISABLED_KEY, false); + if (false) { try { //debugSocket = new LocalServerSocket("com.android.internal.telephony.debug"); @@ -1151,6 +1158,26 @@ public class GSMPhone extends PhoneBase { return mDataConnection.getAllPdps(); } + /** + * Disables the DNS check (i.e., allows "0.0.0.0"). + * Useful for lab testing environment. + * @param b true disables the check, false enables. + */ + public void disableDnsCheck(boolean b) { + mDnsCheckDisabled = b; + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext()); + SharedPreferences.Editor editor = sp.edit(); + editor.putBoolean(DNS_SERVER_CHECK_DISABLED_KEY, b); + editor.commit(); + } + + /** + * Returns true if the DNS check is currently disabled. + */ + public boolean isDnsCheckDisabled() { + return mDnsCheckDisabled; + } + public void updateServiceLocation(Message response) { mSST.getLacAndCid(response); } @@ -1356,18 +1383,8 @@ public class GSMPhone extends PhoneBase { break; case EVENT_SIM_RECORDS_LOADED: - mSIMRecords.getSIMOperatorNumeric(); - - try { - //set the current field the telephony provider according to - //the SIM's operator - Uri uri = Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"); - ContentValues map = new ContentValues(); - map.put(Telephony.Carriers.NUMERIC, mSIMRecords.getSIMOperatorNumeric()); - mContext.getContentResolver().insert(uri, map); - } catch (SQLException e) { - Log.e(LOG_TAG, "Can't store current operator", e); - } + updateCurrentCarrierInProvider(); + // Check if this is a different SIM than the previous one. If so unset the // voice mail number. String imsi = getVmSimImsi(); @@ -1508,7 +1525,27 @@ public class GSMPhone extends PhoneBase { } } } - + + /** + * Sets the "current" field in the telephony provider according to the SIM's operator + * + * @return true for success; false otherwise. + */ + boolean updateCurrentCarrierInProvider() { + if (mSIMRecords != null) { + try { + Uri uri = Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"); + ContentValues map = new ContentValues(); + map.put(Telephony.Carriers.NUMERIC, mSIMRecords.getSIMOperatorNumeric()); + mContext.getContentResolver().insert(uri, map); + return true; + } catch (SQLException e) { + Log.e(LOG_TAG, "Can't store current operator", e); + } + } + return false; + } + /** * Used to track the settings upon completion of the network change. */ diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmAlphabet.java b/telephony/java/com/android/internal/telephony/gsm/GsmAlphabet.java index 59a94223b93dd001acae55318c0c02810c7c6ed7..df34897a5400937c86e0dd3e6dc822f08962ae13 100644 --- a/telephony/java/com/android/internal/telephony/gsm/GsmAlphabet.java +++ b/telephony/java/com/android/internal/telephony/gsm/GsmAlphabet.java @@ -532,7 +532,7 @@ public class GsmAlphabet * needed to represent this string. Counts unencodable char as 1 septet. */ public static int - countGsmSeptets(String s) + countGsmSeptets(CharSequence s) { try { return countGsmSeptets(s, false); @@ -549,7 +549,7 @@ public class GsmAlphabet * char. Otherwise, counts invalid char as 1 septet */ public static int - countGsmSeptets(String s, boolean throwsException) throws EncodeException + countGsmSeptets(CharSequence s, boolean throwsException) throws EncodeException { int charIndex = 0; int sz = s.length(); diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmSimCard.java b/telephony/java/com/android/internal/telephony/gsm/GsmSimCard.java index 085980635028bc1c240618ef0da385878b098455..a4cded9ddc4daac9f15d0ede9affd8bc7664a988 100644 --- a/telephony/java/com/android/internal/telephony/gsm/GsmSimCard.java +++ b/telephony/java/com/android/internal/telephony/gsm/GsmSimCard.java @@ -258,7 +258,7 @@ public final class GsmSimCard extends Handler implements SimCard { } public String getServiceProviderName () { - return phone.mSIMRecords.getServiceProvideName(); + return phone.mSIMRecords.getServiceProviderName(); } //***** Handler implementation diff --git a/telephony/java/com/android/internal/telephony/gsm/MccTable.java b/telephony/java/com/android/internal/telephony/gsm/MccTable.java index 8f6b22edc3486438c433f3fe7291e432eea63084..bb17cc42e831c289aa21741b2dc60a9e727653b8 100644 --- a/telephony/java/com/android/internal/telephony/gsm/MccTable.java +++ b/telephony/java/com/android/internal/telephony/gsm/MccTable.java @@ -171,16 +171,16 @@ public final class MccTable table.add(new MccEntry(202,"gr",2)); //Greece table.add(new MccEntry(204,"nl",2,"Europe/Amsterdam")); //Netherlands (Kingdom of the) table.add(new MccEntry(206,"be",2)); //Belgium - table.add(new MccEntry(208,"fr",2)); //France + table.add(new MccEntry(208,"fr",2,"Europe/Paris","fr")); //France table.add(new MccEntry(212,"mc",2)); //Monaco (Principality of) table.add(new MccEntry(213,"ad",2)); //Andorra (Principality of) - table.add(new MccEntry(214,"es",2)); //Spain + table.add(new MccEntry(214,"es",2,"Europe/Madrid","es")); //Spain table.add(new MccEntry(216,"hu",2)); //Hungary (Republic of) table.add(new MccEntry(218,"ba",2)); //Bosnia and Herzegovina table.add(new MccEntry(219,"hr",2)); //Croatia (Republic of) table.add(new MccEntry(220,"rs",2)); //Serbia and Montenegro - table.add(new MccEntry(222,"it",2)); //Italy - table.add(new MccEntry(225,"va",2)); //Vatican City State + table.add(new MccEntry(222,"it",2,"Europe/Rome","it")); //Italy + table.add(new MccEntry(225,"va",2,"Europe/Rome","it")); //Vatican City State table.add(new MccEntry(226,"ro",2)); //Romania table.add(new MccEntry(228,"ch",2)); //Switzerland (Confederation of) table.add(new MccEntry(230,"cz",2,"Europe/Prague")); //Czech Republic @@ -217,7 +217,7 @@ public final class MccTable table.add(new MccEntry(290,"gl",2)); //Greenland (Denmark) table.add(new MccEntry(292,"sm",2)); //San Marino (Republic of) table.add(new MccEntry(293,"sl",2)); //Slovenia (Republic of) - table.add(new MccEntry(294,"mk",2)); //The Former Yugoslav Republic of Macedonia + table.add(new MccEntry(294,"mk",2)); //The Former Yugoslav Republic of Macedonia table.add(new MccEntry(295,"li",2)); //Liechtenstein (Principality of) table.add(new MccEntry(302,"ca",2)); //Canada table.add(new MccEntry(308,"pm",2)); //Saint Pierre and Miquelon (Collectivit territoriale de la Rpublique franaise) @@ -283,8 +283,8 @@ public final class MccTable table.add(new MccEntry(436,"tj",2)); //Tajikistan (Republic of) table.add(new MccEntry(437,"kg",2)); //Kyrgyz Republic table.add(new MccEntry(438,"tm",2)); //Turkmenistan - table.add(new MccEntry(440,"jp",2)); //Japan - table.add(new MccEntry(441,"jp",2)); //Japan + table.add(new MccEntry(440,"jp",2,"Asia/Tokyo","ja")); //Japan + table.add(new MccEntry(441,"jp",2,"Asia/Tokyo","ja")); //Japan table.add(new MccEntry(450,"kr",2)); //Korea (Republic of) table.add(new MccEntry(452,"vn",2)); //Viet Nam (Socialist Republic of) table.add(new MccEntry(454,"hk",2)); //"Hong Kong, China" diff --git a/telephony/java/com/android/internal/telephony/gsm/PdpConnection.java b/telephony/java/com/android/internal/telephony/gsm/PdpConnection.java index 6428f7047c6fa03c1187f73a5c96da9ece297b31..66f8b72ae128a03ffadbfbcc7b3a405d79ee977a 100644 --- a/telephony/java/com/android/internal/telephony/gsm/PdpConnection.java +++ b/telephony/java/com/android/internal/telephony/gsm/PdpConnection.java @@ -114,9 +114,6 @@ public class PdpConnection extends Handler { private static final int EVENT_DEACTIVATE_DONE = 4; private static final int EVENT_FORCE_RETRY = 5; - //***** Tag IDs for EventLog - private static final int EVENT_LOG_BAD_DNS_ADDRESS = 50100; - //***** Instance Variables private GSMPhone phone; private String pdp_name; @@ -301,7 +298,7 @@ public class PdpConnection extends Handler { private void notifyDisconnect(Message msg) { if (DBG) log("Notify PDP disconnect"); - + if (msg != null) { AsyncResult.forMessage(msg); msg.sendToTarget(); @@ -378,7 +375,7 @@ public class PdpConnection extends Handler { if (ar.exception != null) { Log.e(LOG_TAG, "PDP Context Init failed " + ar.exception); - + if (receivedDisconnectReq) { // Don't bother reporting the error if there's already a // pending disconnect request, since DataConnectionTracker @@ -406,7 +403,7 @@ public class PdpConnection extends Handler { } else { String[] response = ((String[]) ar.result); cid = Integer.parseInt(response[0]); - + if (response.length > 2) { interfaceName = response[1]; ipAddress = response[2]; @@ -420,7 +417,8 @@ public class PdpConnection extends Handler { + " DNS2=" + dnsServers[1]); } - if (NULL_IP.equals(dnsServers[0]) && NULL_IP.equals(dnsServers[1])) { + if (NULL_IP.equals(dnsServers[0]) && NULL_IP.equals(dnsServers[1]) + && !phone.isDnsCheckDisabled()) { // Work around a race condition where QMI does not fill in DNS: // Deactivate PDP and let DataConnectionTracker retry. // Do not apply the race condition workaround for MMS APN @@ -428,20 +426,21 @@ public class PdpConnection extends Handler { // Otherwise, the default APN will not be restored anymore. if (!apn.types[0].equals(Phone.APN_TYPE_MMS) || !isIpAddress(apn.mmsProxy)) { - EventLog.writeEvent(EVENT_LOG_BAD_DNS_ADDRESS, dnsServers[0]); + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_BAD_DNS_ADDRESS, + dnsServers[0]); phone.mCM.deactivateDefaultPDP(cid, obtainMessage(EVENT_FORCE_RETRY)); break; } } } - + if (dataLink != null) { dataLink.connect(); } else { onLinkStateChanged(DataLink.LinkState.LINK_UP); } - + if (DBG) log("PDP setup on cid = " + cid); } } @@ -463,7 +462,7 @@ public class PdpConnection extends Handler { } else { ar = (AsyncResult) msg.obj; PdpFailCause cause = PdpFailCause.UNKNOWN; - + if (ar.exception == null) { int rilFailCause = ((int[]) (ar.result))[0]; cause = getFailCauseFromRequest(rilFailCause); diff --git a/telephony/java/com/android/internal/telephony/gsm/RIL.java b/telephony/java/com/android/internal/telephony/gsm/RIL.java index 8ec286a153f562928d5bacc96c3e423c48004c80..8b10ed242e5e29f3127eac873de1438088f9fe34 100644 --- a/telephony/java/com/android/internal/telephony/gsm/RIL.java +++ b/telephony/java/com/android/internal/telephony/gsm/RIL.java @@ -1980,6 +1980,7 @@ public final class RIL extends BaseCommands implements CommandsInterface case RIL_UNSOL_SIM_SMS_STORAGE_FULL: ret = responseVoid(p); break; case RIL_UNSOL_SIM_REFRESH: ret = responseInts(p); break; case RIL_UNSOL_CALL_RING: ret = responseVoid(p); break; + case RIL_UNSOL_RESTRICTED_STATE_CHANGED: ret = responseInts(p); break; default: throw new RuntimeException("Unrecognized unsol response: " + response); //break; (implied) @@ -2170,6 +2171,13 @@ public final class RIL extends BaseCommands implements CommandsInterface mRingRegistrant.notifyRegistrant(); } break; + + case RIL_UNSOL_RESTRICTED_STATE_CHANGED: + if (RILJ_LOGD) unsljLogvRet(response, ret); + if (mRestrictedStateRegistrant != null) { + mRestrictedStateRegistrant.notifyRegistrant( + new AsyncResult (null, ret, null)); + } } } @@ -2553,6 +2561,7 @@ public final class RIL extends BaseCommands implements CommandsInterface case RIL_UNSOL_SIM_SMS_STORAGE_FULL: return "UNSOL_SIM_SMS_STORAGE_FULL"; case RIL_UNSOL_SIM_REFRESH: return "UNSOL_SIM_REFRESH"; case RIL_UNSOL_CALL_RING: return "UNSOL_CALL_RING"; + case RIL_UNSOL_RESTRICTED_STATE_CHANGED: return "RIL_UNSOL_RESTRICTED_STATE_CHANGED"; default: return ""; } } diff --git a/telephony/java/com/android/internal/telephony/gsm/RILConstants.java b/telephony/java/com/android/internal/telephony/gsm/RILConstants.java index 0a8e19200e4a345057c3f55b0210ba306e3c7759..4463b2085d6b7806fe6e3f3852b984ced9a0a28c 100644 --- a/telephony/java/com/android/internal/telephony/gsm/RILConstants.java +++ b/telephony/java/com/android/internal/telephony/gsm/RILConstants.java @@ -51,6 +51,32 @@ cat include/telephony/ril.h | \ int RIL_SIM_PIN = 3; int RIL_SIM_PUK = 4; int RIL_SIM_NETWORK_PERSONALIZATION = 5; + + /** + * No restriction at all including voice/SMS/USSD/SS/AV64 + * and packet data. + */ + int RIL_RESTRICTED_STATE_NONE = 0x00; + /** + * Block emergency call due to restriction. + * But allow all normal voice/SMS/USSD/SS/AV64. + */ + int RIL_RESTRICTED_STATE_CS_EMERGENCY = 0x01; + /** + * Block all normal voice/SMS/USSD/SS/AV64 due to restriction. + * Only Emergency call allowed. + */ + int RIL_RESTRICTED_STATE_CS_NORMAL = 0x02; + /** + * Block all voice/SMS/USSD/SS/AV64 + * including emergency call due to restriction. + */ + int RIL_RESTRICTED_STATE_CS_ALL = 0x04; + /** + * Block packet data access due to restriction. + */ + int RIL_RESTRICTED_STATE_PS_ALL = 0x10; + int RIL_REQUEST_GET_SIM_STATUS = 1; int RIL_REQUEST_ENTER_SIM_PIN = 2; int RIL_REQUEST_ENTER_SIM_PUK = 3; @@ -147,4 +173,5 @@ cat include/telephony/ril.h | \ int RIL_UNSOL_SIM_SMS_STORAGE_FULL = 1016; int RIL_UNSOL_SIM_REFRESH = 1017; int RIL_UNSOL_CALL_RING = 1018; + int RIL_UNSOL_RESTRICTED_STATE_CHANGED = 1023; } diff --git a/telephony/java/com/android/internal/telephony/gsm/RestrictedState.java b/telephony/java/com/android/internal/telephony/gsm/RestrictedState.java new file mode 100644 index 0000000000000000000000000000000000000000..d17f134ead7e087d6b829762c5ac5e9d0a1f2429 --- /dev/null +++ b/telephony/java/com/android/internal/telephony/gsm/RestrictedState.java @@ -0,0 +1,122 @@ +/* + * 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. + */ + +package com.android.internal.telephony.gsm; + +import android.telephony.ServiceState; + +public class RestrictedState { + + /** + * Set true to block packet data access due to restriction + */ + private boolean mPsRestricted; + /** + * Set true to block all normal voice/SMS/USSD/SS/AV64 due to restriction + */ + private boolean mCsNormalRestricted; + /** + * Set true to block emergency call due to restriction + */ + private boolean mCsEmergencyRestricted; + + public RestrictedState() { + setPsRestricted(false); + setCsNormalRestricted(false); + setCsEmergencyRestricted(false); + } + + /** + * @param csEmergencyRestricted the csEmergencyRestricted to set + */ + public void setCsEmergencyRestricted(boolean csEmergencyRestricted) { + mCsEmergencyRestricted = csEmergencyRestricted; + } + + /** + * @return the csEmergencyRestricted + */ + public boolean isCsEmergencyRestricted() { + return mCsEmergencyRestricted; + } + + /** + * @param csNormalRestricted the csNormalRestricted to set + */ + public void setCsNormalRestricted(boolean csNormalRestricted) { + mCsNormalRestricted = csNormalRestricted; + } + + /** + * @return the csNormalRestricted + */ + public boolean isCsNormalRestricted() { + return mCsNormalRestricted; + } + + /** + * @param psRestricted the psRestricted to set + */ + public void setPsRestricted(boolean psRestricted) { + mPsRestricted = psRestricted; + } + + /** + * @return the psRestricted + */ + public boolean isPsRestricted() { + return mPsRestricted; + } + + public boolean isCsRestricted() { + return mCsNormalRestricted && mCsEmergencyRestricted; + } + + @Override + public boolean equals (Object o) { + RestrictedState s; + + try { + s = (RestrictedState) o; + } catch (ClassCastException ex) { + return false; + } + + if (o == null) { + return false; + } + + return mPsRestricted == s.mPsRestricted + && mCsNormalRestricted == s.mCsNormalRestricted + && mCsEmergencyRestricted == s.mCsEmergencyRestricted; + } + + @Override + public String toString() { + String csString = "none"; + + if (mCsEmergencyRestricted && mCsNormalRestricted) { + csString = "all"; + } else if (mCsEmergencyRestricted && !mCsNormalRestricted) { + csString = "emergency"; + } else if (!mCsEmergencyRestricted && mCsNormalRestricted) { + csString = "normal call"; + } + + return "Restricted State CS: " + csString + " PS:" + mPsRestricted; + } + +} diff --git a/telephony/java/com/android/internal/telephony/gsm/SIMRecords.java b/telephony/java/com/android/internal/telephony/gsm/SIMRecords.java index 75f56a35b87e9c0f44015af8104ca09784f0a65e..a62f6cfd4d09d5375d9fbafa2b659dc2b75ba342 100644 --- a/telephony/java/com/android/internal/telephony/gsm/SIMRecords.java +++ b/telephony/java/com/android/internal/telephony/gsm/SIMRecords.java @@ -56,6 +56,7 @@ public final class SIMRecords extends Handler implements SimConstants AdnRecordCache adnCache; VoiceMailConstants mVmConfig; + SpnOverride mSpnOverride; //***** Cached SIM State; cleared on channel close @@ -167,6 +168,7 @@ public final class SIMRecords extends Handler implements SimConstants adnCache = new AdnRecordCache(phone); mVmConfig = new VoiceMailConstants(); + mSpnOverride = new SpnOverride(); recordsRequested = false; // No load request is made till SIM ready @@ -202,7 +204,6 @@ public final class SIMRecords extends Handler implements SimConstants spnDisplayCondition = -1; efMWIS = null; efCPHS_MWI = null; - spn = null; spdiNetworks = null; pnnHomeName = null; @@ -284,7 +285,7 @@ public final class SIMRecords extends Handler implements SimConstants * Return Service Provider Name stored in SIM * @return null if SIM is not yet ready */ - public String getServiceProvideName() + String getServiceProviderName() { return spn; } @@ -1191,11 +1192,6 @@ public final class SIMRecords extends Handler implements SimConstants SmsMessage message = SmsMessage.newFromCMT( new String[] { "", pdu }); - Log.i("ENF", "message from " + - message.getOriginatingAddress()); - Log.i("ENF", "message text " + - message.getMessageBody()); - phone.mSMS.dispatchMessage(message); } } @@ -1226,11 +1222,6 @@ public final class SIMRecords extends Handler implements SimConstants SmsMessage message = SmsMessage.newFromCMT( new String[] { "", pdu }); - Log.i("ENF", "message from " + - message.getOriginatingAddress()); - Log.i("ENF", "message text " + - message.getMessageBody()); - phone.mSMS.dispatchMessage(message); // 3GPP TS 51.011 v5.0.0 (20011-12) 10.5.3 @@ -1267,10 +1258,11 @@ public final class SIMRecords extends Handler implements SimConstants { Log.d(LOG_TAG, "SIMRecords: record load complete"); + String operator = getSIMOperatorNumeric(); + // Some fields require more than one SIM record to set - phone.setSystemProperty(PROPERTY_SIM_OPERATOR_NUMERIC, - getSIMOperatorNumeric()); + phone.setSystemProperty(PROPERTY_SIM_OPERATOR_NUMERIC, operator); if (imsi != null) { phone.setSystemProperty(PROPERTY_SIM_OPERATOR_ISO_COUNTRY, @@ -1281,7 +1273,8 @@ public final class SIMRecords extends Handler implements SimConstants Log.e("SIM", "[SIMRecords] onAllRecordsLoaded: imsi is NULL!"); } - setVoiceMailByCountry(getSIMOperatorNumeric()); + setVoiceMailByCountry(operator); + setSpnFromConfig(operator); recordsLoadedRegistrants.notifyRegistrants( new AsyncResult(null, null, null)); @@ -1289,6 +1282,12 @@ public final class SIMRecords extends Handler implements SimConstants SimCard.INTENT_VALUE_SIM_LOADED, null); } + private void setSpnFromConfig(String carrier) { + if (mSpnOverride.containsCarrier(carrier)) { + spn = mSpnOverride.getSpn(carrier); + } + } + private void setVoiceMailByCountry (String spn) { if (mVmConfig.containsCarrier(spn)) { isVoiceMailFixed = true; diff --git a/telephony/java/com/android/internal/telephony/gsm/SMSDispatcher.java b/telephony/java/com/android/internal/telephony/gsm/SMSDispatcher.java index daf4b9cac920107c622eddeda2be7230769315d3..558552409b253997c09477df42cf62b452fe5e0c 100644 --- a/telephony/java/com/android/internal/telephony/gsm/SMSDispatcher.java +++ b/telephony/java/com/android/internal/telephony/gsm/SMSDispatcher.java @@ -32,11 +32,13 @@ import android.net.Uri; import android.os.AsyncResult; import android.os.Handler; import android.os.Message; +import android.os.PowerManager; import android.provider.Telephony; import android.provider.Settings; import android.provider.Telephony.Sms.Intents; import android.telephony.gsm.SmsMessage; import android.telephony.gsm.SmsManager; +import com.android.internal.telephony.WapPushOverSms; import android.telephony.ServiceState; import android.util.Config; import com.android.internal.util.HexDump; @@ -62,37 +64,6 @@ final class SMSDispatcher extends Handler { /** Default timeout for SMS sent query */ private static final int DEFAULT_SMS_TIMOUEOUT = 6000; - private static final int WAP_PDU_TYPE_PUSH = 0x06; - - private static final int WAP_PDU_TYPE_CONFIRMED_PUSH = 0x07; - - private static final byte DRM_RIGHTS_XML = (byte)0xca; - - private static final String DRM_RIGHTS_XML_MIME_TYPE = "application/vnd.oma.drm.rights+xml"; - - private static final byte DRM_RIGHTS_WBXML = (byte)0xcb; - - private static final String DRM_RIGHTS_WBXML_MIME_TYPE = - "application/vnd.oma.drm.rights+wbxml"; - - private static final byte WAP_SI_MIME_PORT = (byte)0xae; - - private static final String WAP_SI_MIME_TYPE = "application/vnd.wap.sic"; - - private static final byte WAP_SL_MIME_PORT = (byte)0xb0; - - private static final String WAP_SL_MIME_TYPE = "application/vnd.wap.slc"; - - private static final byte WAP_CO_MIME_PORT = (byte)0xb2; - - private static final String WAP_CO_MIME_TYPE = "application/vnd.wap.coc"; - - private static final int WAP_PDU_SHORT_LENGTH_MAX = 30; - - private static final int WAP_PDU_LENGTH_QUOTE = 31; - - private static final String MMS_MIME_TYPE = "application/vnd.wap.mms-message"; - private static final String[] RAW_PROJECTION = new String[] { "pdu", "sequence", @@ -124,6 +95,8 @@ final class SMSDispatcher extends Handler { private final GSMPhone mPhone; + private final WapPushOverSms mWapPush; + private final Context mContext; private final ContentResolver mResolver; @@ -135,7 +108,9 @@ final class SMSDispatcher extends Handler { /** Maximum number of times to retry sending a failed SMS. */ private static final int MAX_SEND_RETRIES = 3; /** Delay before next send attempt on a failed SMS, in milliseconds. */ - private static final int SEND_RETRY_DELAY = 2000; // ms + private static final int SEND_RETRY_DELAY = 2000; + /** single part SMS */ + private static final int SINGLE_PART_SMS = 1; /** * Message reference for a CONCATENATED_8_BIT_REFERENCE or @@ -148,6 +123,15 @@ final class SMSDispatcher extends Handler { private SmsTracker mSTracker; + /** Wake lock to ensure device stays awake while dispatching the SMS intent. */ + private PowerManager.WakeLock mWakeLock; + + /** + * Hold the wake lock for 5 seconds, which should be enough time for + * any receiver(s) to grab its own wake lock. + */ + private final int WAKE_LOCK_TIMEOUT = 5000; + /** * Implement the per-application based SMS control, which only allows * a limit on the number of SMS/MMS messages an app can send in checking @@ -169,15 +153,23 @@ final class SMSDispatcher extends Handler { mSmsStamp = new HashMap> (); } - boolean check(String appName) { + /** + * Check to see if an application allow to send new SMS messages + * + * @param appName is the application sending sms + * @param smsWaiting is the number of new sms wants to be sent + * @return true if application is allowed to send the requested number + * of new sms messages + */ + boolean check(String appName, int smsWaiting) { if (!mSmsStamp.containsKey(appName)) { mSmsStamp.put(appName, new ArrayList()); } - return isUnderLimit(mSmsStamp.get(appName)); + return isUnderLimit(mSmsStamp.get(appName), smsWaiting); } - private boolean isUnderLimit(ArrayList sent) { + private boolean isUnderLimit(ArrayList sent, int smsWaiting) { Long ct = System.currentTimeMillis(); Log.d(TAG, "SMS send size=" + sent.size() + "time=" + ct); @@ -185,9 +177,11 @@ final class SMSDispatcher extends Handler { while (sent.size() > 0 && (ct - sent.get(0)) > mCheckPeriod ) { sent.remove(0); } - - if (sent.size() < mMaxAllowed) { - sent.add(ct); + + if ( (sent.size() + smsWaiting) <= mMaxAllowed) { + for (int i = 0; i < smsWaiting; i++ ) { + sent.add(ct); + } return true; } return false; @@ -196,11 +190,14 @@ final class SMSDispatcher extends Handler { SMSDispatcher(GSMPhone phone) { mPhone = phone; + mWapPush = new WapPushOverSms(phone); mContext = phone.getContext(); mResolver = mContext.getContentResolver(); mCm = phone.mCM; mSTracker = null; + createWakelock(); + int check_period = Settings.Gservices.getInt(mResolver, Settings.Gservices.SMS_OUTGOING_CEHCK_INTERVAL_MS, DEFAULT_SMS_CHECK_PERIOD); @@ -290,14 +287,30 @@ final class SMSDispatcher extends Handler { case EVENT_SEND_CONFIRMED_SMS: if (mSTracker!=null) { - Log.d(TAG, "Ready to send SMS again."); - sendSms(mSTracker); + if (isMultipartTracker(mSTracker)) { + sendMultipartSms(mSTracker); + } else { + sendSms(mSTracker); + } mSTracker = null; } break; } } + private void createWakelock() { + PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); + mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SMSDispatcher"); + mWakeLock.setReferenceCounted(true); + } + + private void sendBroadcast(Intent intent, String permission) { + // Hold a wake lock for WAKE_LOCK_TIMEOUT seconds, enough to give any + // receivers time to take their own wake locks. + mWakeLock.acquire(WAKE_LOCK_TIMEOUT); + mContext.sendBroadcast(intent, permission); + } + /** * Called when SIM_FULL message is received from the RIL. Notifies interested * parties that SIM storage for SMS messages is full. @@ -305,7 +318,7 @@ final class SMSDispatcher extends Handler { private void handleSimFull() { // broadcast SIM_FULL intent Intent intent = new Intent(Intents.SIM_FULL_ACTION); - mPhone.getContext().sendBroadcast(intent, "android.permission.RECEIVE_SMS"); + sendBroadcast(intent, "android.permission.RECEIVE_SMS"); } /** @@ -434,6 +447,13 @@ final class SMSDispatcher extends Handler { * @param sms the incoming message from the phone */ /* package */ void dispatchMessage(SmsMessage sms) { + + // If sms is null, means there was a parsing error. + // TODO: Should NAK this. + if (sms == null) { + return; + } + boolean handled = false; // Special case the message waiting indicator messages @@ -476,35 +496,50 @@ final class SMSDispatcher extends Handler { SmsHeader header = sms.getUserDataHeader(); if (header != null) { for (SmsHeader.Element element : header.getElements()) { - switch (element.getID()) { - case SmsHeader.CONCATENATED_8_BIT_REFERENCE: { - byte[] data = element.getData(); - - referenceNumber = data[0] & 0xff; - count = data[1] & 0xff; - sequence = data[2] & 0xff; - - break; - } - - case SmsHeader.CONCATENATED_16_BIT_REFERENCE: { - byte[] data = element.getData(); - - referenceNumber = (data[0] & 0xff) * 256 + (data[1] & 0xff); - count = data[2] & 0xff; - sequence = data[3] & 0xff; - - break; - } - - case SmsHeader.APPLICATION_PORT_ADDRESSING_16_BIT: { - byte[] data = element.getData(); - - destPort = (data[0] & 0xff) << 8; - destPort |= (data[1] & 0xff); - - break; - } + try { + switch (element.getID()) { + case SmsHeader.CONCATENATED_8_BIT_REFERENCE: { + byte[] data = element.getData(); + + referenceNumber = data[0] & 0xff; + count = data[1] & 0xff; + sequence = data[2] & 0xff; + + // Per TS 23.040, 9.2.3.24.1: If the count is zero, sequence + // is zero, or sequence > count, ignore the entire element + if (count == 0 || sequence == 0 || sequence > count) { + referenceNumber = -1; + } + break; + } + + case SmsHeader.CONCATENATED_16_BIT_REFERENCE: { + byte[] data = element.getData(); + + referenceNumber = (data[0] & 0xff) * 256 + (data[1] & 0xff); + count = data[2] & 0xff; + sequence = data[3] & 0xff; + + // Per TS 23.040, 9.2.3.24.8: If the count is zero, sequence + // is zero, or sequence > count, ignore the entire element + if (count == 0 || sequence == 0 || sequence > count) { + referenceNumber = -1; + } + break; + } + + case SmsHeader.APPLICATION_PORT_ADDRESSING_16_BIT: { + byte[] data = element.getData(); + + destPort = (data[0] & 0xff) << 8; + destPort |= (data[1] & 0xff); + + break; + } + } + } catch (ArrayIndexOutOfBoundsException e) { + Log.e(TAG, "Bad element in header", e); + return; // TODO: NACK the message or something, don't just discard. } } } @@ -516,7 +551,7 @@ final class SMSDispatcher extends Handler { if (destPort != -1) { if (destPort == SmsHeader.PORT_WAP_PUSH) { - dispatchWapPdu(sms.getUserData()); + mWapPush.dispatchWapPdu(sms.getUserData()); } // The message was sent to a port, so concoct a URI for it dispatchPortAddressedPdus(pdus, destPort); @@ -599,7 +634,7 @@ final class SMSDispatcher extends Handler { } // Handle the PUSH - dispatchWapPdu(output.toByteArray()); + mWapPush.dispatchWapPdu(output.toByteArray()); break; } @@ -623,8 +658,7 @@ final class SMSDispatcher extends Handler { private void dispatchPdus(byte[][] pdus) { Intent intent = new Intent(Intents.SMS_RECEIVED_ACTION); intent.putExtra("pdus", pdus); - mPhone.getContext().sendBroadcast( - intent, "android.permission.RECEIVE_SMS"); + sendBroadcast(intent, "android.permission.RECEIVE_SMS"); } /** @@ -637,130 +671,73 @@ final class SMSDispatcher extends Handler { Uri uri = Uri.parse("sms://localhost:" + port); Intent intent = new Intent(Intents.DATA_SMS_RECEIVED_ACTION, uri); intent.putExtra("pdus", pdus); - mPhone.getContext().sendBroadcast( - intent, "android.permission.RECEIVE_SMS"); + sendBroadcast(intent, "android.permission.RECEIVE_SMS"); } + /** - * Dispatches inbound messages that are in the WAP PDU format. See - * wap-230-wsp-20010705-a section 8 for details on the WAP PDU format. + * Send a multi-part text based SMS. * - * @param pdu The WAP PDU, made up of one or more SMS PDUs + * @param destinationAddress the address to send the message to + * @param scAddress is the service center address or null to use + * the current default SMSC + * @param parts an ArrayList of strings that, in order, + * comprise the original message + * @param sentIntents if not null, an ArrayList of + * PendingIntents (one for each message part) that is + * broadcast when the corresponding message part has been sent. + * The result code will be Activity.RESULT_OK for success, + * or one of these errors: + * RESULT_ERROR_GENERIC_FAILURE + * RESULT_ERROR_RADIO_OFF + * RESULT_ERROR_NULL_PDU. + * The per-application based SMS control checks sentIntent. If sentIntent + * is NULL the caller will be checked against all unknown applicaitons, + * which cause smaller number of SMS to be sent in checking period. + * @param deliveryIntents if not null, an ArrayList of + * PendingIntents (one for each message part) that is + * broadcast when the corresponding message part has been delivered + * to the recipient. The raw pdu of the status report is in the + * extended data ("pdu"). */ - private void dispatchWapPdu(byte[] pdu) { - int index = 0; - int transactionId = pdu[index++] & 0xFF; - int pduType = pdu[index++] & 0xFF; - int headerLength = 0; - - if ((pduType != WAP_PDU_TYPE_PUSH) && - (pduType != WAP_PDU_TYPE_CONFIRMED_PUSH)) { - Log.w(TAG, "Received non-PUSH WAP PDU. Type = " + pduType); - return; - } - - /** - * Parse HeaderLen(unsigned integer). - * From wap-230-wsp-20010705-a section 8.1.2 - * The maximum size of a uintvar is 32 bits. - * So it will be encoded in no more than 5 octets. - */ - int temp = 0; - do { - temp = pdu[index++]; - headerLength = headerLength << 7; - headerLength |= temp & 0x7F; - } while ((temp & 0x80) != 0); - - int headerStartIndex = index; - - /** - * Parse Content-Type. - * From wap-230-wsp-20010705-a section 8.4.2.24 - * - * Content-type-value = Constrained-media | Content-general-form - * Content-general-form = Value-length Media-type - * Media-type = (Well-known-media | Extension-Media) *(Parameter) - * Value-length = Short-length | (Length-quote Length) - * Short-length = (octet <= WAP_PDU_SHORT_LENGTH_MAX) - * Length-quote = (WAP_PDU_LENGTH_QUOTE) - * Length = Uintvar-integer - */ - // Parse Value-length. - if ((pdu[index] & 0xff) <= WAP_PDU_SHORT_LENGTH_MAX) { - // Short-length. - index++; - } else if (pdu[index] == WAP_PDU_LENGTH_QUOTE) { - // Skip Length-quote. - index++; - // Skip Length. - // Now we assume 8bit is enough to store the content-type length. - index++; - } - String mimeType; - switch (pdu[headerStartIndex]) - { - case DRM_RIGHTS_XML: - mimeType = DRM_RIGHTS_XML_MIME_TYPE; - break; - case DRM_RIGHTS_WBXML: - mimeType = DRM_RIGHTS_WBXML_MIME_TYPE; - break; - case WAP_SI_MIME_PORT: - // application/vnd.wap.sic - mimeType = WAP_SI_MIME_TYPE; - break; - case WAP_SL_MIME_PORT: - mimeType = WAP_SL_MIME_TYPE; - break; - case WAP_CO_MIME_PORT: - mimeType = WAP_CO_MIME_TYPE; - break; - default: - int start = index; + void sendMultipartText(String destinationAddress, String scAddress, ArrayList parts, + ArrayList sentIntents, ArrayList deliveryIntents) { - // Skip text-string. - // Now we assume the mimetype is Extension-Media. - while (pdu[index++] != '\0') { - ; + PendingIntent sentIntent = null; + + + int ss = mPhone.getServiceState().getState(); + + if (ss == ServiceState.STATE_IN_SERVICE) { + // Only check SMS sending limit while in service + if (sentIntents != null && sentIntents.size() > 0) { + sentIntent = sentIntents.get(0); + } + String appName = getAppNameByIntent(sentIntent); + if ( !mCounter.check(appName, parts.size())) { + HashMap map = new HashMap(); + map.put("destination", destinationAddress); + map.put("scaddress", scAddress); + map.put("parts", parts); + map.put("sentIntents", sentIntents); + map.put("deliveryIntents", deliveryIntents); + + SmsTracker multipartParameter = new SmsTracker(map, null, null); + + sendMessage(obtainMessage(EVENT_POST_ALERT, multipartParameter)); + return; } - mimeType = new String(pdu, start, index-start-1); - break; - } - - // XXX Skip the remainder of the header for now - int dataIndex = headerStartIndex + headerLength; - byte[] data; - if (pdu[headerStartIndex] == WAP_CO_MIME_PORT) - { - // because SMSDispatcher can't parse push headers "Content-Location" and - // X-Wap-Content-URI, so pass the whole push to CO application. - data = pdu; - } else - { - data = new byte[pdu.length - dataIndex]; - System.arraycopy(pdu, dataIndex, data, 0, data.length); - } - - // Notify listeners about the WAP PUSH - Intent intent = new Intent(Intents.WAP_PUSH_RECEIVED_ACTION); - intent.setType(mimeType); - intent.putExtra("transactionId", transactionId); - intent.putExtra("pduType", pduType); - intent.putExtra("data", data); - - if (mimeType.equals(MMS_MIME_TYPE)) { - mPhone.getContext().sendBroadcast( - intent, "android.permission.RECEIVE_MMS"); - } else { - mPhone.getContext().sendBroadcast( - intent, "android.permission.RECEIVE_WAP_PUSH"); } + + sendMultipartTextWithPermit(destinationAddress, + scAddress, parts, sentIntents, deliveryIntents); } /** - * Send a multi-part text based SMS. + * Send a multi-part text based SMS which already passed SMS control check. * + * It is the working function for sendMultipartText(). + * * @param destinationAddress the address to send the message to * @param scAddress is the service center address or null to use * the current default SMSC @@ -774,17 +751,32 @@ final class SMSDispatcher extends Handler { * RESULT_ERROR_GENERIC_FAILURE * RESULT_ERROR_RADIO_OFF * RESULT_ERROR_NULL_PDU. - * The per-application based SMS control checks sentIntent. If sentIntent - * is NULL the caller will be checked against all unknown applicaitons, - * which cause smaller number of SMS to be sent in checking period. * @param deliveryIntents if not null, an ArrayList of * PendingIntents (one for each message part) that is * broadcast when the corresponding message part has been delivered * to the recipient. The raw pdu of the status report is in the * extended data ("pdu"). */ - void sendMultipartText(String destinationAddress, String scAddress, ArrayList parts, - ArrayList sentIntents, ArrayList deliveryIntents) { + private void sendMultipartTextWithPermit(String destinationAddress, + String scAddress, ArrayList parts, + ArrayList sentIntents, + ArrayList deliveryIntents) { + + PendingIntent sentIntent = null; + PendingIntent deliveryIntent = null; + + // check if in service + int ss = mPhone.getServiceState().getState(); + if (ss != ServiceState.STATE_IN_SERVICE) { + for (int i = 0, count = parts.size(); i < count; i++) { + if (sentIntents != null && sentIntents.size() > i) { + sentIntent = sentIntents.get(i); + } + SmsTracker tracker = new SmsTracker(null, sentIntent, null); + handleNotInService(ss, tracker); + } + return; + } int ref = ++sConcatenatedRef & 0xff; @@ -796,9 +788,7 @@ final class SMSDispatcher extends Handler { data[2] = (byte) (i + 1); // 1-based sequence SmsHeader header = new SmsHeader(); header.add(new SmsHeader.Element(SmsHeader.CONCATENATED_8_BIT_REFERENCE, data)); - PendingIntent sentIntent = null; - PendingIntent deliveryIntent = null; - + if (sentIntents != null && sentIntents.size() > i) { sentIntent = sentIntents.get(i); } @@ -809,8 +799,14 @@ final class SMSDispatcher extends Handler { SmsMessage.SubmitPdu pdus = SmsMessage.getSubmitPdu(scAddress, destinationAddress, parts.get(i), deliveryIntent != null, header.toByteArray()); - sendRawPdu(pdus.encodedScAddress, pdus.encodedMessage, sentIntent, deliveryIntent); - } + HashMap map = new HashMap(); + map.put("smsc", pdus.encodedScAddress); + map.put("pdu", pdus.encodedMessage); + + SmsTracker tracker = new SmsTracker(map, sentIntent, + deliveryIntent); + sendSms(tracker); + } } /** @@ -856,7 +852,7 @@ final class SMSDispatcher extends Handler { handleNotInService(ss, tracker); } else { String appName = getAppNameByIntent(sentIntent); - if (mCounter.check(appName)) { + if (mCounter.check(appName, SINGLE_PART_SMS)) { sendSms(tracker); } else { sendMessage(obtainMessage(EVENT_POST_ALERT, tracker)); @@ -912,6 +908,41 @@ final class SMSDispatcher extends Handler { SimUtils.bytesToHexString(pdu), reply); } + /** + * Send the multi-part SMS based on multipart Sms tracker + * + * @param tracker holds the multipart Sms tracker ready to be sent + */ + private void sendMultipartSms (SmsTracker tracker) { + ArrayList parts; + ArrayList sentIntents; + ArrayList deliveryIntents; + + HashMap map = tracker.mData; + + String destinationAddress = (String) map.get("destination"); + String scAddress = (String) map.get("scaddress"); + + parts = (ArrayList) map.get("parts"); + sentIntents = (ArrayList) map.get("sentIntents"); + deliveryIntents = (ArrayList) map.get("deliveryIntents"); + + sendMultipartTextWithPermit(destinationAddress, + scAddress, parts, sentIntents, deliveryIntents); + + } + + /** + * Check if a SmsTracker holds multi-part Sms + * + * @param tracker a SmsTracker could hold a multi-part Sms + * @return true for tracker holds Multi-parts Sms + */ + private boolean isMultipartTracker (SmsTracker tracker) { + HashMap map = tracker.mData; + return ( map.get("parts") != null); + } + /** * Keeps track of an SMS that has been sent to the RIL, until it it has * successfully been sent, or we're done trying. @@ -939,7 +970,7 @@ final class SMSDispatcher extends Handler { new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { - if (which == DialogInterface.BUTTON1) { + if (which == DialogInterface.BUTTON_POSITIVE) { Log.d(TAG, "click YES to send out sms"); sendMessage(obtainMessage(EVENT_SEND_CONFIRMED_SMS)); } diff --git a/telephony/java/com/android/internal/telephony/gsm/ServiceStateTracker.java b/telephony/java/com/android/internal/telephony/gsm/ServiceStateTracker.java index d3a19c58370846a604edb451930b3046a1566794..89ce506f78951bcffc7e55af0d226d7313b9b4ac 100644 --- a/telephony/java/com/android/internal/telephony/gsm/ServiceStateTracker.java +++ b/telephony/java/com/android/internal/telephony/gsm/ServiceStateTracker.java @@ -23,9 +23,15 @@ import static com.android.internal.telephony.TelephonyProperties.PROPERTY_OPERAT import static com.android.internal.telephony.TelephonyProperties.PROPERTY_OPERATOR_NUMERIC; import static com.android.internal.telephony.TelephonyProperties.PROPERTY_SIM_OPERATOR_ALPHA; import static com.android.internal.telephony.TelephonyProperties.PROPERTY_SIM_OPERATOR_NUMERIC; + import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.Phone; +import com.android.internal.telephony.gsm.DataConnectionTracker.State; + import android.app.AlarmManager; +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; @@ -33,6 +39,7 @@ import android.database.ContentObserver; import android.os.AsyncResult; import android.os.Handler; import android.os.Message; +import android.os.PowerManager; import android.os.Registrant; import android.os.RegistrantList; import android.os.SystemClock; @@ -70,6 +77,9 @@ final class ServiceStateTracker extends Handler static final int DATA_ACCESS_GPRS = 1; static final int DATA_ACCESS_EDGE = 2; static final int DATA_ACCESS_UMTS = 3; + + static final int MAX_NUM_DATA_STATE_READS = 15; + static final int DATA_STATE_POLL_SLEEP_MS = 100; //***** Instance Variables @@ -81,6 +91,7 @@ final class ServiceStateTracker extends Handler GsmCellLocation cellLoc; GsmCellLocation newCellLoc; int mPreferredNetworkType; + RestrictedState rs; int rssi = 99; // signal strength 0-31, 99=unknown // That's "received signal strength indication" fyi @@ -113,6 +124,9 @@ final class ServiceStateTracker extends Handler private RegistrantList gprsDetachedRegistrants = new RegistrantList(); private RegistrantList roamingOnRegistrants = new RegistrantList(); private RegistrantList roamingOffRegistrants = new RegistrantList(); + private RegistrantList psRestrictEnabledRegistrants = new RegistrantList(); + private RegistrantList psRestrictDisabledRegistrants = new RegistrantList(); + // Sometimes we get the NITZ time before we know what country we are in. // Keep the time zone information from the NITZ string so we can fix @@ -122,7 +136,7 @@ final class ServiceStateTracker extends Handler private boolean mZoneDst; private long mZoneTime; private boolean mGotCountryCode = false; - + String mSavedTimeZone; long mSavedTime; long mSavedAtTime; @@ -135,7 +149,15 @@ final class ServiceStateTracker extends Handler private boolean mStartedGprsRegCheck = false; // Already sent the event-log for no gprs register private boolean mReportedGprsNoReg = false; + + /** + * The Notification object given to the NotificationManager. + */ + private Notification mNotification; + // Wake lock used while setting time of day. + private PowerManager.WakeLock mWakeLock; + private static final String WAKELOCK_TAG = "ServiceStateTracker"; // Keep track of SPN display rules, so we only broadcast intent if something changes. private String curSpn = null; @@ -153,8 +175,18 @@ final class ServiceStateTracker extends Handler // waiting period before recheck gprs and voice registration static final int DEFAULT_GPRS_CHECK_PERIOD_MILLIS = 60 * 1000; - //***** Events + // notification type + static final int PS_ENABLED = 1001; // Access Control blocks data service + static final int PS_DISABLED = 1002; // Access Control enables data service + static final int CS_ENABLED = 1003; // Access Control blocks all voice/sms service + static final int CS_DISABLED = 1004; // Access Control enables all voice/sms service + static final int CS_NORMAL_ENABLED = 1005; // Access Control blocks normal voice/sms service + static final int CS_NORMAL_DISABLED = 1006; // Access Control enables normal voice/sms service + static final int CS_EMERGENCY_ENABLED = 1007; // Access Control blocks emergency call service + static final int CS_EMERGENCY_DISABLED = 1008; // Access Control enables emergency call service + + //***** Events static final int EVENT_RADIO_STATE_CHANGED = 1; static final int EVENT_NETWORK_STATE_CHANGED = 2; static final int EVENT_GET_SIGNAL_STRENGTH = 3; @@ -174,10 +206,7 @@ final class ServiceStateTracker extends Handler static final int EVENT_SET_PREFERRED_NETWORK_TYPE = 20; static final int EVENT_RESET_PREFERRED_NETWORK_TYPE = 21; static final int EVENT_CHECK_REPORT_GPRS = 22; - - // Event Log Tags - private static final int EVENT_LOG_CGREG_FAIL = 50107; - private static final int EVENT_DATA_STATE_RADIO_OFF = 50108; + static final int EVENT_RESTRICTED_STATE_CHANGED = 23; //***** Time Zones @@ -209,7 +238,7 @@ final class ServiceStateTracker extends Handler "tg", // Togo "uk", // U.K }; - + private ContentObserver mAutoTimeObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { @@ -217,8 +246,7 @@ final class ServiceStateTracker extends Handler revertToNitz(); } }; - - + //***** Constructors ServiceStateTracker(GSMPhone phone) @@ -229,6 +257,11 @@ final class ServiceStateTracker extends Handler newSS = new ServiceState(); cellLoc = new GsmCellLocation(); newCellLoc = new GsmCellLocation(); + rs = new RestrictedState(); + + PowerManager powerManager = + (PowerManager)phone.getContext().getSystemService(Context.POWER_SERVICE); + mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG); cm.registerForAvailable(this, EVENT_RADIO_AVAILABLE, null); cm.registerForRadioStateChanged(this, EVENT_RADIO_STATE_CHANGED, null); @@ -236,18 +269,18 @@ final class ServiceStateTracker extends Handler cm.registerForNetworkStateChanged(this, EVENT_NETWORK_STATE_CHANGED, null); cm.setOnNITZTime(this, EVENT_NITZ_TIME, null); cm.setOnSignalStrengthUpdate(this, EVENT_SIGNAL_STRENGTH_UPDATE, null); - + cm.setOnRestrictedStateChanged(this, EVENT_RESTRICTED_STATE_CHANGED, null); cm.registerForSIMReady(this, EVENT_SIM_READY, null); - + // system setting property AIRPLANE_MODE_ON is set in Settings. int airplaneMode = Settings.System.getInt( phone.getContext().getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0); - mDesiredPowerState = ! (airplaneMode > 0); + mDesiredPowerState = ! (airplaneMode > 0); ContentResolver cr = phone.getContext().getContentResolver(); cr.registerContentObserver( - Settings.System.getUriFor(Settings.System.AUTO_TIME), true, + Settings.System.getUriFor(Settings.System.AUTO_TIME), true, mAutoTimeObserver); setRssiDefaultValues(); mNeedToRegForSimLoaded = true; @@ -259,8 +292,7 @@ final class ServiceStateTracker extends Handler * @param what what code of message when delivered * @param obj placed in Message.obj */ - /*protected*/ void - registerForGprsAttached(Handler h, int what, Object obj) { + /*protected*/ void registerForGprsAttached(Handler h, int what, Object obj) { Registrant r = new Registrant(h, what, obj); gprsAttachedRegistrants.add(r); @@ -272,7 +304,7 @@ final class ServiceStateTracker extends Handler void registerForNetworkAttach(Handler h, int what, Object obj) { Registrant r = new Registrant(h, what, obj); networkAttachedRegistrants.add(r); - + if (ss.getState() == ServiceState.STATE_IN_SERVICE) { r.notifyRegistrant(); } @@ -283,8 +315,7 @@ final class ServiceStateTracker extends Handler * @param what what code of message when delivered * @param obj placed in Message.obj */ - /*protected*/ void - registerForGprsDetached(Handler h, int what, Object obj) { + /*protected*/ void registerForGprsDetached(Handler h, int what, Object obj) { Registrant r = new Registrant(h, what, obj); gprsDetachedRegistrants.add(r); @@ -341,6 +372,38 @@ final class ServiceStateTracker extends Handler obtainMessage(EVENT_GET_PREFERRED_NETWORK_TYPE, onComplete)); } + /** + * Registration point for transition into packet service restricted zone. + * @param h handler to notify + * @param what what code of message when delivered + * @param obj placed in Message.obj + */ + void registerForPsRestrictedEnabled(Handler h, int what, Object obj) { + Log.d(LOG_TAG, "[DSAC DEB] " + "registerForPsRestrictedEnabled "); + Registrant r = new Registrant(h, what, obj); + psRestrictEnabledRegistrants.add(r); + + if (rs.isPsRestricted()) { + r.notifyRegistrant(); + } + } + + /** + * Registration point for transition out of packet service restricted zone. + * @param h handler to notify + * @param what what code of message when delivered + * @param obj placed in Message.obj + */ + void registerForPsRestrictedDisabled(Handler h, int what, Object obj) { + Log.d(LOG_TAG, "[DSAC DEB] " + "registerForPsRestrictedDisabled "); + Registrant r = new Registrant(h, what, obj); + psRestrictDisabledRegistrants.add(r); + + if (rs.isPsRestricted()) { + r.notifyRegistrant(); + } + } + //***** Called from GSMPhone public void @@ -360,7 +423,7 @@ final class ServiceStateTracker extends Handler /*package*/ void enableLocationUpdates() { cm.setLocationUpdates(true, obtainMessage(EVENT_LOCATION_UPDATES_ENABLED)); } - + /*package*/ void disableLocationUpdates() { cm.setLocationUpdates(false, null); } @@ -407,7 +470,7 @@ final class ServiceStateTracker extends Handler pollState(); break; - case EVENT_GET_SIGNAL_STRENGTH: + case EVENT_GET_SIGNAL_STRENGTH: // This callback is called when signal strength is polled // all by itself @@ -418,7 +481,7 @@ final class ServiceStateTracker extends Handler ar = (AsyncResult) msg.obj; onSignalStrengthResult(ar); queueNextSignalStrengthPoll(); - + break; case EVENT_GET_LOC_DONE: @@ -503,7 +566,7 @@ final class ServiceStateTracker extends Handler getLacAndCid(null); } break; - + case EVENT_SET_PREFERRED_NETWORK_TYPE: ar = (AsyncResult) msg.obj; // Don't care the result, only use for dereg network (COPS=2) @@ -548,11 +611,22 @@ final class ServiceStateTracker extends Handler if (loc != null) cid = loc.getCid(); EventLog.List val = new EventLog.List(ss.getOperatorNumeric(), cid); - EventLog.writeEvent(EVENT_LOG_CGREG_FAIL, val); + EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_CGREG_FAIL, val); mReportedGprsNoReg = true; } mStartedGprsRegCheck = false; break; + + case EVENT_RESTRICTED_STATE_CHANGED: + // This is a notification from + // CommandsInterface.setOnRestrictedStateChanged + + Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_RESTRICTED_STATE_CHANGED"); + + ar = (AsyncResult) msg.obj; + + onRestrictedStateChanged(ar); + break; } } @@ -561,7 +635,7 @@ final class ServiceStateTracker extends Handler private void updateSpnDisplay() { int rule = phone.mSIMRecords.getDisplayRule(ss.getOperatorNumeric()); - String spn = phone.mSIMRecords.getServiceProvideName(); + String spn = phone.mSIMRecords.getServiceProviderName(); String plmn = ss.getOperatorAlphaLong(); if (rule != curSpnRule @@ -598,7 +672,19 @@ final class ServiceStateTracker extends Handler EventLog.List val = new EventLog.List( dcTracker.getStateInString(), (dcTracker.getAnyDataEnabled() ? 1 : 0) ); - EventLog.writeEvent(EVENT_DATA_STATE_RADIO_OFF, val); + EventLog.writeEvent(TelephonyEventLog.EVENT_DATA_STATE_RADIO_OFF, val); + } + dcTracker.cleanConnectionBeforeRadioOff(); + + // poll data state up to 15 times, with a 100ms delay + // totaling 1.5 sec. Normal data disable action will finish in 100ms. + for (int i = 0; i < MAX_NUM_DATA_STATE_READS; i++) { + if (dcTracker.state != State.CONNECTED + && dcTracker.state != State.DISCONNECTING) { + Log.d(LOG_TAG, "Data shutdown complete."); + break; + } + SystemClock.sleep(DATA_STATE_POLL_SLEEP_MS); } // If it's on and available and we want it off.. cm.setRadioPower(false, null); @@ -689,7 +775,7 @@ final class ServiceStateTracker extends Handler if (states.length > 0) { try { regState = Integer.parseInt(states[0]); - + // states[3] (if present) is the current radio technology if (states.length >= 4 && states[3] != null) { type = Integer.parseInt(states[3]); @@ -1038,7 +1124,7 @@ final class ServiceStateTracker extends Handler break; } } - + return guess; } @@ -1091,6 +1177,63 @@ final class ServiceStateTracker extends Handler phone.notifySignalStrength(); } } + + /** + * Set restricted state based on the OnRestrictedStateChanged notification + * If any voice or packet restricted state changes, trigger a UI + * notification and notify registrants. + * @param ar an int value of RIL_RESTRICTED_STATE_* + */ + private void onRestrictedStateChanged(AsyncResult ar) + { + Log.d(LOG_TAG, "[DSAC DEB] " + "onRestrictedStateChanged"); + RestrictedState newRs = new RestrictedState(); + + Log.d(LOG_TAG, "[DSAC DEB] " + "current rs at enter "+ rs); + + if (ar.exception == null) { + int[] ints = (int[])ar.result; + int state = ints[0]; + + newRs.setCsEmergencyRestricted( + ((state & RILConstants.RIL_RESTRICTED_STATE_CS_EMERGENCY) != 0) || + ((state & RILConstants.RIL_RESTRICTED_STATE_CS_ALL) != 0) ); + newRs.setCsNormalRestricted( + ((state & RILConstants.RIL_RESTRICTED_STATE_CS_NORMAL) != 0) || + ((state & RILConstants.RIL_RESTRICTED_STATE_CS_ALL) != 0) ); + newRs.setPsRestricted( + (state & RILConstants.RIL_RESTRICTED_STATE_PS_ALL)!= 0); + + Log.d(LOG_TAG, "[DSAC DEB] " + "new rs "+ newRs); + + if (!rs.isPsRestricted() && newRs.isPsRestricted()) { + psRestrictEnabledRegistrants.notifyRegistrants(); + setNotification(PS_ENABLED, false); + } else if (rs.isPsRestricted() && !newRs.isPsRestricted()) { + psRestrictDisabledRegistrants.notifyRegistrants(); + setNotification(PS_DISABLED, false); + } + + if (!rs.isCsRestricted() && newRs.isCsRestricted()) { + setNotification(CS_ENABLED, false); + } else if (rs.isCsRestricted() && !newRs.isCsRestricted()) { + setNotification(CS_DISABLED, false); + } else { + if (!rs.isCsEmergencyRestricted() && newRs.isCsEmergencyRestricted()) { + setNotification(CS_EMERGENCY_ENABLED, false); + } else if (rs.isCsEmergencyRestricted() && !newRs.isCsEmergencyRestricted()) { + setNotification(CS_EMERGENCY_DISABLED, false); + } + if (!rs.isCsNormalRestricted() && newRs.isCsNormalRestricted()) { + setNotification(CS_NORMAL_ENABLED, false); + } else if (rs.isCsEmergencyRestricted() && !newRs.isCsEmergencyRestricted()) { + setNotification(CS_NORMAL_DISABLED, false); + } + } + rs = newRs; + } + Log.d(LOG_TAG, "[DSAC DEB] " + "current rs at return "+ rs); + } /** code is registration state 0-5 from TS 27.007 7.2 */ private int @@ -1147,7 +1290,7 @@ final class ServiceStateTracker extends Handler String simNumeric = SystemProperties.get(PROPERTY_SIM_OPERATOR_NUMERIC, ""); String operatorNumeric = s.getOperatorNumeric(); - + boolean equalsMcc = true; try { equalsMcc = simNumeric.substring(0, 3). @@ -1329,49 +1472,56 @@ final class ServiceStateTracker extends Handler } saveNitzTimeZone(zone.getID()); } - + String ignore = SystemProperties.get("gsm.ignore-nitz"); if (ignore != null && ignore.equals("yes")) { Log.i(LOG_TAG, "NITZ: Not setting clock because gsm.ignore-nitz is set"); return; } - if (getAutoTime()) { - long millisSinceNitzReceived - = SystemClock.elapsedRealtime() - nitzReceiveTime; - - if (millisSinceNitzReceived < 0) { - // Sanity check: something is wrong - Log.i(LOG_TAG, "NITZ: not setting time, clock has rolled " - + "backwards since NITZ time was received, " - + nitz); - return; + try { + mWakeLock.acquire(); + + if (getAutoTime()) { + long millisSinceNitzReceived + = SystemClock.elapsedRealtime() - nitzReceiveTime; + + if (millisSinceNitzReceived < 0) { + // Sanity check: something is wrong + Log.i(LOG_TAG, "NITZ: not setting time, clock has rolled " + + "backwards since NITZ time was received, " + + nitz); + return; + } + + if (millisSinceNitzReceived > Integer.MAX_VALUE) { + // If the time is this far off, something is wrong > 24 days! + Log.i(LOG_TAG, "NITZ: not setting time, processing has taken " + + (millisSinceNitzReceived / (1000 * 60 * 60 * 24)) + + " days"); + return; + } + + // Note: with range checks above, cast to int is safe + c.add(Calendar.MILLISECOND, (int)millisSinceNitzReceived); + + Log.i(LOG_TAG, "NITZ: Setting time of day to " + c.getTime() + + " NITZ receive delay(ms): " + millisSinceNitzReceived + + " gained(ms): " + + (c.getTimeInMillis() - System.currentTimeMillis()) + + " from " + nitz); + + setAndBroadcastNetworkSetTime(c.getTimeInMillis()); + Log.i(LOG_TAG, "NITZ: after Setting time of day"); } - - if (millisSinceNitzReceived > Integer.MAX_VALUE) { - // If the time is this far off, something is wrong > 24 days! - Log.i(LOG_TAG, "NITZ: not setting time, processing has taken " - + (millisSinceNitzReceived / (1000 * 60 * 60 * 24)) - + " days"); - return; + SystemProperties.set("gsm.nitz.time", String.valueOf(c.getTimeInMillis())); + saveNitzTime(c.getTimeInMillis()); + if (Config.LOGV) { + long end = SystemClock.elapsedRealtime(); + Log.v(LOG_TAG, "NITZ: end=" + end + " dur=" + (end - start)); } - - // Note: with range checks above, cast to int is safe - c.add(Calendar.MILLISECOND, (int)millisSinceNitzReceived); - - Log.i(LOG_TAG, "NITZ: Setting time of day to " + c.getTime() - + " NITZ receive delay(ms): " + millisSinceNitzReceived - + " gained(ms): " - + (c.getTimeInMillis() - System.currentTimeMillis()) - + " from " + nitz); - - setAndBroadcastNetworkSetTime(c.getTimeInMillis()); - } - SystemProperties.set("gsm.nitz.time", String.valueOf(c.getTimeInMillis())); - saveNitzTime(c.getTimeInMillis()); - if (Config.LOGV) { - long end = SystemClock.elapsedRealtime(); - Log.v(LOG_TAG, "NITZ: end=" + end + " dur=" + (end - start)); + } finally { + mWakeLock.release(); } } catch (RuntimeException ex) { Log.e(LOG_TAG, "NITZ: Parsing NITZ time " + nitz, ex); @@ -1399,11 +1549,11 @@ final class ServiceStateTracker extends Handler /** * Set the timezone and send out a sticky broadcast so the system can * determine if the timezone was set by the carrier. - * + * * @param zoneId timezone set by carrier */ private void setAndBroadcastNetworkSetTimeZone(String zoneId) { - AlarmManager alarm = + AlarmManager alarm = (AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE); alarm.setTimeZone(zoneId); Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE); @@ -1414,9 +1564,9 @@ final class ServiceStateTracker extends Handler /** * Set the time and Send out a sticky broadcast so the system can determine * if the time was set by the carrier. - * + * * @param time time set by network - */ + */ private void setAndBroadcastNetworkSetTime(long time) { SystemClock.setCurrentTimeMillis(time); Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIME); @@ -1438,4 +1588,72 @@ final class ServiceStateTracker extends Handler + (SystemClock.elapsedRealtime() - mSavedAtTime)); } } + + /** + * Post a notification to NotificationManager for restricted state + * + * @param notifyType is one state of PS/CS_*_ENABLE/DISABLE + * @param isCancel true to cancel the previous posted notification + * (current is not implemented yet) + */ + private void setNotification(int notifyType, boolean isCancel) { + + Log.d(LOG_TAG, "[DSAC DEB] " + "create notification " + notifyType); + mNotification = new Notification(); + mNotification.when = System.currentTimeMillis(); + mNotification.flags = Notification.FLAG_AUTO_CANCEL; + mNotification.icon = com.android.internal.R.drawable.icon_highlight_square; + Intent intent = new Intent(); + mNotification.contentIntent = PendingIntent + .getActivity(phone.getContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); + + // TODO + // should use getResources().getText(com.android.internal.R.) + CharSequence title = "Restricted State Changed"; + CharSequence details = ""; + switch (notifyType) { + case PS_ENABLED: + details = "Access Control blocks data service."; + break; + case PS_DISABLED: + details = "Access Control enables data service."; + break; + case CS_ENABLED: + details = "Access Control blocks all voice/sms service."; + break; + case CS_DISABLED: + details = "Access Control enables all voice/sms service."; + break; + case CS_NORMAL_ENABLED: + details = "Access Control blocks normal voice/sms service."; + break; + case CS_NORMAL_DISABLED: + details = "Access Control enables normal voice/sms service."; + break; + case CS_EMERGENCY_ENABLED: + details = "Access Control blocks emergency call service."; + break; + case CS_EMERGENCY_DISABLED: + details = "Access Control enables emergency call service."; + break; + } + + Log.d(LOG_TAG, "[DSAC DEB] " + "put notification " + title + " / " +details); + mNotification.tickerText = title; + mNotification.setLatestEventInfo(phone.getContext(), title, details, + mNotification.contentIntent); + + NotificationManager notificationManager = (NotificationManager) + phone.getContext().getSystemService(Context.NOTIFICATION_SERVICE); + + if (isCancel) { + // TODO + //if we go the notification route, probably want to only put up a single + //notification if both CS+PS is restricted, instead of one for each.nnnnn + //Anyway, need UX team input on UI. + //notificationManager.cancel(notifyType); + } + notificationManager.notify(notifyType, mNotification); + } + } diff --git a/telephony/java/com/android/internal/telephony/gsm/SpnOverride.java b/telephony/java/com/android/internal/telephony/gsm/SpnOverride.java new file mode 100644 index 0000000000000000000000000000000000000000..9ea3010197a5ed31bb14e4fd328875c37a4faaad --- /dev/null +++ b/telephony/java/com/android/internal/telephony/gsm/SpnOverride.java @@ -0,0 +1,78 @@ +package com.android.internal.telephony.gsm; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; + +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; + +import android.os.Environment; +import android.util.Log; +import android.util.Xml; + +import com.android.internal.util.XmlUtils; + +public class SpnOverride { + private HashMap CarrierSpnMap; + + + static final String LOG_TAG = "GSM"; + static final String PARTNER_SPN_OVERRIDE_PATH ="etc/spn-conf.xml"; + + SpnOverride () { + CarrierSpnMap = new HashMap(); + loadSpnOverrides(); + } + + boolean containsCarrier(String carrier) { + return CarrierSpnMap.containsKey(carrier); + } + + String getSpn(String carrier) { + return CarrierSpnMap.get(carrier); + } + + private void loadSpnOverrides() { + FileReader spnReader; + + final File spnFile = new File(Environment.getRootDirectory(), + PARTNER_SPN_OVERRIDE_PATH); + + try { + spnReader = new FileReader(spnFile); + } catch (FileNotFoundException e) { + Log.w(LOG_TAG, "Can't open " + + Environment.getRootDirectory() + "/" + PARTNER_SPN_OVERRIDE_PATH); + return; + } + + try { + XmlPullParser parser = Xml.newPullParser(); + parser.setInput(spnReader); + + XmlUtils.beginDocument(parser, "spnOverrides"); + + while (true) { + XmlUtils.nextElement(parser); + + String name = parser.getName(); + if (!"spnOverride".equals(name)) { + break; + } + + String numeric = parser.getAttributeValue(null, "numeric"); + String data = parser.getAttributeValue(null, "spn"); + + CarrierSpnMap.put(numeric, data); + } + } catch (XmlPullParserException e) { + Log.w(LOG_TAG, "Exception in spn-conf parser " + e); + } catch (IOException e) { + Log.w(LOG_TAG, "Exception in spn-conf parser " + e); + } + } + +} diff --git a/telephony/java/com/android/internal/telephony/gsm/TelephonyEventLog.java b/telephony/java/com/android/internal/telephony/gsm/TelephonyEventLog.java new file mode 100644 index 0000000000000000000000000000000000000000..1e583f0b9f9e8a1bcf9e68d324e64f76c9b70864 --- /dev/null +++ b/telephony/java/com/android/internal/telephony/gsm/TelephonyEventLog.java @@ -0,0 +1,33 @@ +/* + * 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. + */ + +package com.android.internal.telephony.gsm; + +/* This class contains the details related to Telephony Event Logging */ +public final class TelephonyEventLog { + + /* Event log tags */ + public static final int EVENT_LOG_BAD_DNS_ADDRESS = 50100; + public static final int EVENT_LOG_RADIO_RESET_COUNTDOWN_TRIGGERED = 50101; + public static final int EVENT_LOG_RADIO_RESET = 50102; + public static final int EVENT_LOG_PDP_RESET = 50103; + public static final int EVENT_LOG_REREGISTER_NETWORK = 50104; + public static final int EVENT_LOG_RADIO_PDP_SETUP_FAIL = 50105; + public static final int EVENT_LOG_CALL_DROP = 50106; + public static final int EVENT_LOG_CGREG_FAIL = 50107; + public static final int EVENT_DATA_STATE_RADIO_OFF = 50108; + public static final int EVENT_LOG_PDP_NETWORK_DROP = 50109; +} diff --git a/test-runner/android/test/InstrumentationTestRunner.java b/test-runner/android/test/InstrumentationTestRunner.java index 8b8d47217ecb7d8724187f1cb2ecbd042730aa17..f038612cbd0ed9e0d22691050b339ddc31c1050e 100644 --- a/test-runner/android/test/InstrumentationTestRunner.java +++ b/test-runner/android/test/InstrumentationTestRunner.java @@ -148,6 +148,8 @@ public class InstrumentationTestRunner extends Instrumentation implements TestSu public static final String ARGUMENT_TEST_SIZE_PREDICATE = "size"; /** @hide */ public static final String ARGUMENT_INCLUDE_PERF = "perf"; + /** @hide */ + public static final String ARGUMENT_DELAY_MSEC = "delay_msec"; private static final String SMALL_SUITE = "small"; private static final String MEDIUM_SUITE = "medium"; @@ -249,6 +251,7 @@ public class InstrumentationTestRunner extends Instrumentation implements TestSu private String mPackageOfTests; private boolean mCoverage; private String mCoverageFilePath; + private int mDelayMsec; @Override public void onCreate(Bundle arguments) { @@ -277,11 +280,18 @@ public class InstrumentationTestRunner extends Instrumentation implements TestSu logOnly = getBooleanArgument(arguments, ARGUMENT_LOG_ONLY); mCoverage = getBooleanArgument(arguments, "coverage"); mCoverageFilePath = arguments.getString("coverageFile"); + + try { + Object delay = arguments.get(ARGUMENT_DELAY_MSEC); // Accept either string or int + if (delay != null) mDelayMsec = Integer.parseInt(delay.toString()); + } catch (NumberFormatException e) { + Log.e(LOG_TAG, "Invalid delay_msec parameter", e); + } } - + TestSuiteBuilder testSuiteBuilder = new TestSuiteBuilder(getClass().getName(), getTargetContext().getClassLoader()); - + if (testSizePredicate != null) { testSuiteBuilder.addRequirements(testSizePredicate); } @@ -600,6 +610,18 @@ public class InstrumentationTestRunner extends Instrumentation implements TestSu } else { mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, ""); } + + // The delay_msec parameter is normally used to provide buffers of idle time + // for power measurement purposes. To make sure there is a delay before and after + // every test in a suite, we delay *after* every test (see endTest below) and also + // delay *before* the first test. So, delay test1 delay test2 delay. + + try { + if (mTestNum == 1) Thread.sleep(mDelayMsec); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + sendStatus(REPORT_VALUE_RESULT_START, mTestResult); mTestResultCode = 0; } @@ -636,10 +658,15 @@ public class InstrumentationTestRunner extends Instrumentation implements TestSu mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, "."); } sendStatus(mTestResultCode, mTestResult); + + try { // Sleep after every test, if specified + Thread.sleep(mDelayMsec); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } } // TODO report the end of the cycle // TODO report runtime for each test } } - diff --git a/test-runner/android/test/ServiceTestCase.java b/test-runner/android/test/ServiceTestCase.java index c53bf7d2a7a70a1694905b86440672ad22d5a05a..fcb9d55e8360f69a5e3c9481161e4e2a8a79bd8d 100644 --- a/test-runner/android/test/ServiceTestCase.java +++ b/test-runner/android/test/ServiceTestCase.java @@ -48,7 +48,7 @@ import java.util.Random; * the test case will call onCreate(), and then call the corresponding entry point in your service. * It will record any parameters or other support values necessary to support the lifecycle.

            • *
            • After your test completes, the test case {@link #tearDown} function is - * automatically called, and it will stop & destroy your service with the appropriate + * automatically called, and it will stop and destroy your service with the appropriate * calls (depending on how your test invoked the service.)
            • *
            * @@ -172,7 +172,7 @@ public abstract class ServiceTestCase extends AndroidTestCase * Return the communication channel to the service. May return null if * clients can not bind to the service. The returned * {@link android.os.IBinder} is usually for a complex interface - * that has been described using + * that has been described using * aidl. * * Note: In order to test with this interface, your service must implement a getService() diff --git a/test-runner/android/test/TestCaseUtil.java b/test-runner/android/test/TestCaseUtil.java index 4109d9cc0394e441f838378ec66ebcb4afc271ab..3ba97118e56b0c3b75ac7d323b21230f1cd040ff 100644 --- a/test-runner/android/test/TestCaseUtil.java +++ b/test-runner/android/test/TestCaseUtil.java @@ -17,6 +17,7 @@ package android.test; import com.google.android.collect.Lists; + import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; @@ -26,7 +27,9 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Enumeration; +import java.util.HashSet; import java.util.List; +import java.util.Set; /** * @hide - This is part of a framework that is under development and should not be used for @@ -48,10 +51,25 @@ public class TestCaseUtil { } public static List getTests(Test test, boolean flatten) { + return getTests(test, flatten, new HashSet>()); + } + + private static List getTests(Test test, boolean flatten, + Set> seen) { List testCases = Lists.newArrayList(); if (test != null) { - Test workingTest = invokeSuiteMethodIfPossible(test.getClass()); + Test workingTest = null; + /* + * If we want to run a single TestCase method only, we must not + * invoke the suite() method, because we will run all test methods + * of the class then. + */ + if (test instanceof TestCase && + ((TestCase)test).getName() == null) { + workingTest = invokeSuiteMethodIfPossible(test.getClass(), + seen); + } if (workingTest == null) { workingTest = test; } @@ -62,7 +80,7 @@ public class TestCaseUtil { while (enumeration.hasMoreElements()) { Test childTest = (Test) enumeration.nextElement(); if (flatten) { - testCases.addAll(getTests(childTest, flatten)); + testCases.addAll(getTests(childTest, flatten, seen)); } else { testCases.add(childTest); } @@ -74,11 +92,20 @@ public class TestCaseUtil { return testCases; } - private static Test invokeSuiteMethodIfPossible(Class testClass) { + private static Test invokeSuiteMethodIfPossible(Class testClass, + Set> seen) { try { Method suiteMethod = testClass.getMethod( BaseTestRunner.SUITE_METHODNAME, new Class[0]); - if (Modifier.isStatic(suiteMethod.getModifiers())) { + /* + * Additional check necessary: If a TestCase contains a suite() + * method that returns a TestSuite including the TestCase itself, + * we need to stop the recursion. We use a set of classes to + * remember which classes' suite() methods were already invoked. + */ + if (Modifier.isStatic(suiteMethod.getModifiers()) + && !seen.contains(testClass)) { + seen.add(testClass); try { return (Test) suiteMethod.invoke(null, (Object[]) null); } catch (InvocationTargetException e) { @@ -128,7 +155,8 @@ public class TestCaseUtil { public static TestSuite createTestSuite(Class testClass) throws InstantiationException, IllegalAccessException { - Test test = invokeSuiteMethodIfPossible(testClass); + Test test = invokeSuiteMethodIfPossible(testClass, + new HashSet>()); if (test == null) { return new TestSuite(testClass); diff --git a/test-runner/android/test/TouchUtils.java b/test-runner/android/test/TouchUtils.java index c4bca41bd2def60ded76e9db97fc5f458c91f616..52d2ee85687b7c254e686582964e89a8932e47f6 100644 --- a/test-runner/android/test/TouchUtils.java +++ b/test-runner/android/test/TouchUtils.java @@ -73,7 +73,7 @@ public class TouchUtils { */ @Deprecated public static void dragQuarterScreenUp(ActivityInstrumentationTestCase test) { - dragQuarterScreenDown(test, test.getActivity()); + dragQuarterScreenUp(test, test.getActivity()); } /** @@ -269,9 +269,9 @@ public class TouchUtils { inst.waitForIdleSync(); eventTime = SystemClock.uptimeMillis(); - event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, - x + (ViewConfiguration.getTouchSlop() / 2.0f), - y + (ViewConfiguration.getTouchSlop() / 2.0f), 0); + final int touchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop(); + event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, + x + (touchSlop / 2.0f), y + (touchSlop / 2.0f), 0); inst.sendPointerSync(event); inst.waitForIdleSync(); @@ -309,9 +309,9 @@ public class TouchUtils { inst.waitForIdleSync(); eventTime = SystemClock.uptimeMillis(); + final int touchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop(); event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_CANCEL, - x + (ViewConfiguration.getTouchSlop() / 2.0f), - y + (ViewConfiguration.getTouchSlop() / 2.0f), 0); + x + (touchSlop / 2.0f), y + (touchSlop / 2.0f), 0); inst.sendPointerSync(event); inst.waitForIdleSync(); @@ -345,9 +345,9 @@ public class TouchUtils { eventTime = SystemClock.uptimeMillis(); - event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, - x + (ViewConfiguration.getTouchSlop() / 2.0f), - y + (ViewConfiguration.getTouchSlop() / 2.0f), 0); + final int touchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop(); + event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, + x + (touchSlop / 2.0f), y + (touchSlop / 2.0f), 0); inst.sendPointerSync(event); inst.waitForIdleSync(); @@ -405,9 +405,9 @@ public class TouchUtils { inst.waitForIdleSync(); eventTime = SystemClock.uptimeMillis(); - event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, - x + ViewConfiguration.getTouchSlop() / 2, - y + ViewConfiguration.getTouchSlop() / 2, 0); + final int touchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop(); + event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, + x + touchSlop / 2, y + touchSlop / 2, 0); inst.sendPointerSync(event); inst.waitForIdleSync(); diff --git a/test-runner/android/test/mock/MockContentProvider.java b/test-runner/android/test/mock/MockContentProvider.java index 9c00ecf9116aaba5b91a1e80e93da120f2cd3cfb..d04fc44303ae93fcd8adedfec50b229e0d0caf16 100644 --- a/test-runner/android/test/mock/MockContentProvider.java +++ b/test-runner/android/test/mock/MockContentProvider.java @@ -19,6 +19,7 @@ package android.test.mock; import android.content.ContentValues; import android.content.IContentProvider; import android.content.ISyncAdapter; +import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.database.CursorWindow; import android.database.IBulkCursor; @@ -81,6 +82,12 @@ public class MockContentProvider implements IContentProvider { throw new UnsupportedOperationException("unimplemented mock method"); } + @SuppressWarnings("unused") + public AssetFileDescriptor openAssetFile(Uri uri, String mode) + throws FileNotFoundException { + throw new UnsupportedOperationException("unimplemented mock method"); + } + @SuppressWarnings("unused") public Cursor query(Uri url, String[] projection, String selection, String[] selectionArgs, String sortOrder) throws RemoteException { diff --git a/test-runner/android/test/mock/MockPackageManager.java b/test-runner/android/test/mock/MockPackageManager.java index f131bf26545b77d616cadad232f835e40e4b0da6..ea190e237144810aaaf0318fbf0d8a9d65a55fdf 100644 --- a/test-runner/android/test/mock/MockPackageManager.java +++ b/test-runner/android/test/mock/MockPackageManager.java @@ -34,6 +34,7 @@ import android.content.pm.PermissionInfo; import android.content.pm.ProviderInfo; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; +import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.graphics.drawable.Drawable; @@ -55,6 +56,12 @@ public class MockPackageManager extends PackageManager { throw new UnsupportedOperationException(); } + @Override + public Intent getLaunchIntentForPackage(String packageName) + throws NameNotFoundException { + throw new UnsupportedOperationException(); + } + @Override public int[] getPackageGids(String packageName) throws NameNotFoundException { throw new UnsupportedOperationException(); @@ -393,4 +400,14 @@ public class MockPackageManager extends PackageManager { List outActivities, String packageName) { throw new UnsupportedOperationException(); } + + @Override + public String[] getSystemSharedLibraryNames() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isSafeMode() { + throw new UnsupportedOperationException(); + } } diff --git a/tests/AndroidTests/Android.mk b/tests/AndroidTests/Android.mk index cf8ac94ca5f369341c297ef7f9728996e9ea8f62..f5e49d702d5857f90f707d8f4663d192bc04a344 100644 --- a/tests/AndroidTests/Android.mk +++ b/tests/AndroidTests/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := eng tests +LOCAL_MODULE_TAGS := tests LOCAL_JAVA_LIBRARIES := framework-tests android.test.runner diff --git a/tests/AndroidTests/AndroidManifest.xml b/tests/AndroidTests/AndroidManifest.xml index f126b8cbe60ffab1659400056a2a52e1ed3b973a..843d844379ae417912a100204cd7df4e8dbe98ee 100644 --- a/tests/AndroidTests/AndroidManifest.xml +++ b/tests/AndroidTests/AndroidManifest.xml @@ -44,10 +44,10 @@ - + diff --git a/tests/AndroidTests/DisabledTestApp/Android.mk b/tests/AndroidTests/DisabledTestApp/Android.mk index 814607d58c53e7a84ef27733191a91ceb5214c65..a5daedf06b8d69ac20453679d2603c56edeeaa42 100644 --- a/tests/AndroidTests/DisabledTestApp/Android.mk +++ b/tests/AndroidTests/DisabledTestApp/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := eng tests +LOCAL_MODULE_TAGS := tests LOCAL_SRC_FILES := $(call all-subdir-java-files) diff --git a/tests/AndroidTests/EnabledTestApp/Android.mk b/tests/AndroidTests/EnabledTestApp/Android.mk index 2de5c3b5e2442184da15005c119bd45900a44d2a..4b986d39b2097bc08581041d7e8ba068cc2bf9ed 100644 --- a/tests/AndroidTests/EnabledTestApp/Android.mk +++ b/tests/AndroidTests/EnabledTestApp/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := eng tests +LOCAL_MODULE_TAGS := tests LOCAL_SRC_FILES := $(call all-subdir-java-files) diff --git a/tests/AndroidTests/src/com/android/unit_tests/AppCacheTest.java b/tests/AndroidTests/src/com/android/unit_tests/AppCacheTest.java index 6a9ac86a854a071c63a0a5011ae6f14cf2a760d5..3daa8abbde9bc6f977b1564b0d32979881e49614 100755 --- a/tests/AndroidTests/src/com/android/unit_tests/AppCacheTest.java +++ b/tests/AndroidTests/src/com/android/unit_tests/AppCacheTest.java @@ -44,7 +44,7 @@ import android.os.ServiceManager; import android.os.StatFs; public class AppCacheTest extends AndroidTestCase { - private static final boolean localLOGV = true; + private static final boolean localLOGV = false; public static final String TAG="AppCacheTest"; public final long MAX_WAIT_TIME=60*1000; public final long WAIT_TIME_INCR=10*1000; @@ -121,6 +121,7 @@ public class AppCacheTest extends AndroidTestCase { } @LargeTest public void testFreeApplicationCacheAllFiles() throws Exception { + boolean TRACKING = true; StatFs st = new StatFs("/data"); long blks1 = getFreeStorageBlks(st); long availableMem = getFreeStorageSize(st); @@ -128,11 +129,11 @@ public class AppCacheTest extends AndroidTestCase { assertNotNull(cacheDir); createTestFiles1(cacheDir, "testtmpdir", 5); long blks2 = getFreeStorageBlks(st); - if(localLOGV) Log.i(TAG, "blk1="+blks1+", blks2="+blks2); + if(localLOGV || TRACKING) Log.i(TAG, "blk1="+blks1+", blks2="+blks2); //this should free up the test files that were created earlier invokePMFreeApplicationCache(availableMem); long blks3 = getFreeStorageBlks(st); - if(localLOGV) Log.i(TAG, "blks3="+blks3); + if(localLOGV || TRACKING) Log.i(TAG, "blks3="+blks3); verifyTestFiles1(cacheDir, "testtmpdir", 5); } @@ -593,6 +594,20 @@ public class AppCacheTest extends AndroidTestCase { ", cache="+stats.cacheSize); } + @SmallTest + public void testGetSystemSharedLibraryNames() throws Exception { + try { + String[] sharedLibs = getPm().getSystemSharedLibraryNames(); + if (localLOGV) { + for (String str : sharedLibs) { + Log.i(TAG, str); + } + } + } catch (RemoteException e) { + fail("Failed invoking getSystemSharedLibraryNames with exception:" + e); + } + } + class FreeStorageReceiver extends BroadcastReceiver { public static final String ACTION_FREE = "com.android.unit_tests.testcallback"; private boolean doneFlag = false; @@ -615,15 +630,16 @@ public class AppCacheTest extends AndroidTestCase { @SmallTest public void testFreeStorage() throws Exception { + boolean TRACKING = true; StatFs st = new StatFs("/data"); long blks1 = getFreeStorageBlks(st); - if(localLOGV) Log.i(TAG, "Available free blocks="+blks1); + if(localLOGV || TRACKING) Log.i(TAG, "Available free blocks="+blks1); long availableMem = getFreeStorageSize(st); File cacheDir = mContext.getCacheDir(); assertNotNull(cacheDir); createTestFiles1(cacheDir, "testtmpdir", 5); long blks2 = getFreeStorageBlks(st); - if(localLOGV) Log.i(TAG, "Available blocks after writing test files in application cache="+blks2); + if(localLOGV || TRACKING) Log.i(TAG, "Available blocks after writing test files in application cache="+blks2); // Create receiver and register it FreeStorageReceiver receiver = new FreeStorageReceiver(); mContext.registerReceiver(receiver, new IntentFilter(FreeStorageReceiver.ACTION_FREE)); @@ -632,7 +648,7 @@ public class AppCacheTest extends AndroidTestCase { // Invoke PackageManager api invokePMFreeStorage(availableMem, receiver, pi); long blks3 = getFreeStorageBlks(st); - if(localLOGV) Log.i(TAG, "Available blocks after freeing cache"+blks3); + if(localLOGV || TRACKING) Log.i(TAG, "Available blocks after freeing cache"+blks3); assertEquals(receiver.getResultCode(), 1); mContext.unregisterReceiver(receiver); // Verify result diff --git a/tests/AndroidTests/src/com/android/unit_tests/BluetoothTest.java b/tests/AndroidTests/src/com/android/unit_tests/BluetoothTest.java deleted file mode 100644 index 21fb94b822008addb8b31cb1665bef14507e8e0a..0000000000000000000000000000000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/BluetoothTest.java +++ /dev/null @@ -1,497 +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. - */ - -package com.android.unit_tests; - -import android.bluetooth.BluetoothA2dp; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothIntent; -import android.bluetooth.BluetoothClass; -import android.bluetooth.IBluetoothDeviceCallback; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.SystemProperties; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.LargeTest; -import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.Log; - -import junit.framework.Assert; - -import java.util.List; -import java.util.HashSet; - -public class BluetoothTest extends AndroidTestCase { - private static final String TAG = "BluetoothTest"; - - @MediumTest - public void testBluetoothSmokeTest() throws Exception { - - BluetoothDevice btDevice = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - - // TODO: Use a more reliable check to see if this product should - // support Bluetooth - see bug 988521 - boolean shouldSupportBluetooth = SystemProperties.get("ro.kernel.qemu").equals("0"); - - assertFalse(shouldSupportBluetooth && btDevice == null); - if (!shouldSupportBluetooth) { - Log.i(TAG, "Skipping test - this device does not have bluetooth."); - return; - } - - boolean bluetoothWasEnabled = btDevice.isEnabled(); - - if (bluetoothWasEnabled) { - Log.i(TAG, "Bluetooth already enabled"); - } else { - Log.i(TAG, "Enabling Bluetooth..."); - btDevice.enable(); - Log.i(TAG, "Bluetooth enabled"); - } - Assert.assertTrue(btDevice.isEnabled()); - - String myAddress = btDevice.getAddress(); - Assert.assertTrue(myAddress != null); - Log.i(TAG, "My Bluetooth Address is " + myAddress); - Assert.assertFalse(myAddress.equals("00:00:00:00:00:00")); - - if (!bluetoothWasEnabled) { - Log.i(TAG, "Disabling Bluetooth..."); - btDevice.disable(); - Log.i(TAG, "Bluetooth disabled"); - } - } - - private boolean listenA2dp = false; - private void listenA2dp() { - if (!listenA2dp) { - listenA2dp = true; - getContext().registerReceiver(new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - int state = intent.getIntExtra(BluetoothA2dp.SINK_STATE, -1); - int oldState = intent.getIntExtra(BluetoothA2dp.SINK_PREVIOUS_STATE, -1); - Log.e(TAG, "A2DP INTENT: state = " + state + " oldState = " + oldState); - } - }, new IntentFilter(BluetoothIntent.REMOTE_DEVICE_FOUND_ACTION)); - } - } - - @MediumTest - public void testA2dpSmokeTest() throws Exception { - listenA2dp(); - - BluetoothA2dp a2dp = new BluetoothA2dp(getContext()); - - List sinks = a2dp.listConnectedSinks(); - Log.e(TAG, "listConnectedSinks()..."); - for (String sink : sinks) { - Log.e(TAG, sink + " state = " + a2dp.getSinkState(sink)); - } - } - - @MediumTest - public void testA2dpConnect() throws Exception { - listenA2dp(); - String address = SystemProperties.get("debug.a2dp.address", ""); - BluetoothA2dp a2dp = new BluetoothA2dp(getContext()); - int result = a2dp.connectSink(address); - Log.e(TAG, "connectSink(" + address + ") = " + result); - } - - @MediumTest - public void testA2dpDisconnect() throws Exception { - listenA2dp(); - String address = SystemProperties.get("debug.a2dp.address", ""); - BluetoothA2dp a2dp = new BluetoothA2dp(getContext()); - int result = a2dp.disconnectSink(address); - Log.e(TAG, "disconnectSink(" + address + ") = " + result); - } - - @MediumTest - public void testBluetoothEnabled() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - - if (device.isEnabled()) { - Log.i(TAG, "isEnabled() = yes"); - } else { - Log.i(TAG, "isEnabled() = no"); - } - } - - @MediumTest - public void testEnableBluetooth() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - device.enable(); - } - - @MediumTest - public void testEnableBluetoothWithCallback() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - if (!device.enable(mCallback)) { - Log.e(TAG, "enable() failed"); - } - } - - @MediumTest - public void testDisableBluetooth() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - device.disable(); - } - - @LargeTest - public void testDiscovery() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - if (device.isEnabled()) { - getContext().registerReceiver((BroadcastReceiver)new TestDiscoveryReceiver(), - new IntentFilter(BluetoothIntent.REMOTE_DEVICE_FOUND_ACTION)); - Log.i(TAG, "Starting discovery..."); - String result = device.startDiscovery() ? "true" : "false"; - Log.i(TAG, "startDiscovery() = " + result); - } - } - - @LargeTest - public void testMultipleDiscovery() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - if (device.isEnabled()) { - getContext().registerReceiver((BroadcastReceiver)new TestDiscoveryReceiver(), - new IntentFilter(BluetoothIntent.REMOTE_DEVICE_FOUND_ACTION)); - String result; - Log.i(TAG, "Starting multiple discovery..."); - for (int i = 0; i < 5; i++) { - result = device.startDiscovery() ? "true" : "false"; - Log.i(TAG, "startDiscovery() = " + result); - } - } - } - private class TestDiscoveryReceiver extends BroadcastReceiver { - @Override public void onReceive(Context context, Intent intent) { - String address = intent.getStringExtra(BluetoothIntent.ADDRESS); - int deviceClass = intent.getIntExtra(BluetoothIntent.CLASS, -1); - short rssi = intent.getShortExtra(BluetoothIntent.RSSI, (short)-1); - Log.i(TAG, "Discovered Device: " + address + " " + deviceClass + " " + rssi); - } - } - - private IBluetoothDeviceCallback mCallback = new IBluetoothDeviceCallback.Stub() { - public void onEnableResult(int res) { - String result = "unknown"; - switch (res) { - case BluetoothDevice.RESULT_SUCCESS: - result = "success"; - break; - case BluetoothDevice.RESULT_FAILURE: - result = "FAILURE"; - break; - } - Log.i(TAG, "onEnableResult(" + result + ")"); - } - public void onGetRemoteServiceChannelResult(String device, int channel) {} - }; - - @SmallTest - public void testCreateBond() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - if (!device.createBond("01:23:45:67:89:AB")) { - Log.e(TAG, "createBonding() failed"); - } - } - - @SmallTest - public void testIsPeriodicDiscovery() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - boolean ret = device.isPeriodicDiscovery(); - if (ret) { - Log.i(TAG, "isPeriodicDiscovery() = TRUE"); - } else { - Log.i(TAG, "isPeriodicDiscovery() = FALSE"); - } - } - - @LargeTest - public void testListBondings() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - String[] addresses = device.listBonds(); - if (addresses == null) { - Log.i(TAG, "Bluetooth disabled"); - return; - } - for (String address : addresses) { - String name = device.getRemoteName(address); - Log.i(TAG, "BONDING: " + address + " (" + name + ")"); - } - } - - @LargeTest - public void testListAclConnections() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - String[] addresses = device.listAclConnections(); - if (addresses == null) { - Log.i(TAG, "Bluetooth disabled"); - return; - } - for (String address : addresses) { - String name = device.getRemoteName(address); - Log.i(TAG, "CONNECTION: " + address + " (" + name + ")"); - } - } - - @LargeTest - public void testListRemoteDevices() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - String[] addresses = device.listRemoteDevices(); - if (addresses == null) { - Log.i(TAG, "Bluetooth disabled"); - return; - } - for (String address : addresses) { - String name = device.getRemoteName(address); - Log.i(TAG, "KNOWN DEVICE: " + address + " (" + name + ")"); - } - } - - @MediumTest - public void testSetupBTIntentRecv() throws Exception { - BluetoothDevice device = - (BluetoothDevice)getContext().getSystemService(Context.BLUETOOTH_SERVICE); - if (device == null) { - Log.i(TAG, "Device not Bluetooth capable, skipping test"); - return; - } - if (device.isEnabled()) { - IntentFilter filter = new IntentFilter(BluetoothIntent.ENABLED_ACTION); - filter.addAction(BluetoothIntent.ENABLED_ACTION); - filter.addAction(BluetoothIntent.DISABLED_ACTION); - filter.addAction(BluetoothIntent.NAME_CHANGED_ACTION); - filter.addAction(BluetoothIntent.MODE_CHANGED_ACTION); - filter.addAction(BluetoothIntent.DISCOVERY_STARTED_ACTION); - filter.addAction(BluetoothIntent.DISCOVERY_COMPLETED_ACTION); - filter.addAction(BluetoothIntent.PAIRING_REQUEST_ACTION); - filter.addAction(BluetoothIntent.PAIRING_CANCEL_ACTION); - filter.addAction(BluetoothIntent.REMOTE_DEVICE_FOUND_ACTION); - filter.addAction(BluetoothIntent.REMOTE_DEVICE_DISAPPEARED_ACTION); - filter.addAction(BluetoothIntent.REMOTE_DEVICE_CLASS_UPDATED_ACTION); - filter.addAction(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION); - filter.addAction(BluetoothIntent.REMOTE_DEVICE_DISCONNECT_REQUESTED_ACTION); - filter.addAction(BluetoothIntent.REMOTE_DEVICE_DISCONNECTED_ACTION); - filter.addAction(BluetoothIntent.REMOTE_NAME_UPDATED_ACTION); - filter.addAction(BluetoothIntent.REMOTE_NAME_FAILED_ACTION); - filter.addAction(BluetoothIntent.REMOTE_ALIAS_CHANGED_ACTION); - filter.addAction(BluetoothIntent.REMOTE_ALIAS_CLEARED_ACTION); - filter.addAction(BluetoothIntent.BOND_STATE_CHANGED_ACTION); - filter.addAction(BluetoothIntent.HEADSET_STATE_CHANGED_ACTION); - getContext().registerReceiver( - (BroadcastReceiver)new BluetoothIntentReceiver(), filter); - Log.i(TAG, "Listening for BLUETOOTH INTENTS...."); - } else { - Log.e(TAG, "BT not enabled"); - } - } - - - private class BluetoothIntentReceiver extends BroadcastReceiver { - @Override public void onReceive(Context context, Intent intent) { - String msg = ""; - - String address = intent.getStringExtra(BluetoothIntent.ADDRESS); - if (address != null) { - msg += " address=" + address; - } - - int deviceClass = intent.getIntExtra(BluetoothIntent.CLASS, BluetoothClass.ERROR); - if (deviceClass != BluetoothClass.ERROR) { - msg += " class=" + deviceClass; - } - - int rssi = intent.getIntExtra(BluetoothIntent.RSSI, -1); - if (rssi != -1) { - msg += " rssi=" + rssi; - } - - String name = intent.getStringExtra(BluetoothIntent.NAME); - if (name != null) { - msg += " name=" + name; - } - - String alias = intent.getStringExtra(BluetoothIntent.ALIAS); - if (alias != null) { - msg += " alias=" + alias; - } - - int mode = intent.getIntExtra(BluetoothIntent.MODE, -10); - if (mode != -10) { - msg += " mode=" + mode; - } - - int state = intent.getIntExtra(BluetoothIntent.HEADSET_STATE, -10); - if (state != -10) { - msg += " headset state=" + state; - } - Log.i(TAG, "BLUETOOTH INTENT: " + intent.getAction() + msg); - } - } - - - private static final int[] ALL_SERVICE_CLASSES = new int[] { - BluetoothClass.Service.LIMITED_DISCOVERABILITY, - BluetoothClass.Service.POSITIONING, - BluetoothClass.Service.NETWORKING, - BluetoothClass.Service.RENDER, - BluetoothClass.Service.CAPTURE, - BluetoothClass.Service.OBJECT_TRANSFER, - BluetoothClass.Service.AUDIO, - BluetoothClass.Service.TELEPHONY, - BluetoothClass.Service.INFORMATION - }; - private void assertOnlyTheseServiceClassesAreSupported(int deviceClass, HashSet serviceClasses) { - for (int serviceClassType : ALL_SERVICE_CLASSES) { - Assert.assertEquals(serviceClasses.contains(new Integer(serviceClassType)), - BluetoothClass.Service.hasService(deviceClass, serviceClassType)); - } - } - - @SmallTest - public void testDeviceClass() throws Exception { - // This test does not require bluetooth hardware - int deviceClass; - HashSet serviceClasses; - - deviceClass = BluetoothClass.ERROR; // bogus class - serviceClasses = new HashSet(); - assertOnlyTheseServiceClassesAreSupported(deviceClass, serviceClasses); - Assert.assertEquals(BluetoothClass.ERROR, BluetoothClass.Device.Major.getDeviceMajor(deviceClass)); - Assert.assertEquals(BluetoothClass.ERROR, BluetoothClass.Device.getDevice(deviceClass)); - - deviceClass = 0x10210C; // mac book pro - serviceClasses = new HashSet(); - serviceClasses.add(BluetoothClass.Service.OBJECT_TRANSFER); - serviceClasses.add(BluetoothClass.Service.LIMITED_DISCOVERABILITY); - assertOnlyTheseServiceClassesAreSupported(deviceClass, serviceClasses); - Assert.assertEquals(BluetoothClass.Device.Major.COMPUTER, - BluetoothClass.Device.Major.getDeviceMajor(deviceClass)); - Assert.assertEquals(0x10C, BluetoothClass.Device.getDevice(deviceClass)); - - // mac book pro with some unused bits set. Expecting the same results - deviceClass = 0xFF10210F; - serviceClasses = new HashSet(); - serviceClasses.add(BluetoothClass.Service.OBJECT_TRANSFER); - serviceClasses.add(BluetoothClass.Service.LIMITED_DISCOVERABILITY); - assertOnlyTheseServiceClassesAreSupported(deviceClass, serviceClasses); - Assert.assertEquals(BluetoothClass.Device.Major.COMPUTER, - BluetoothClass.Device.Major.getDeviceMajor(deviceClass)); - Assert.assertEquals(0x10C, BluetoothClass.Device.getDevice(deviceClass)); - - deviceClass = 0x3E0100; // droid.corp.google.com - serviceClasses = new HashSet(); - serviceClasses.add(BluetoothClass.Service.AUDIO); - serviceClasses.add(BluetoothClass.Service.OBJECT_TRANSFER); - serviceClasses.add(BluetoothClass.Service.CAPTURE); - serviceClasses.add(BluetoothClass.Service.RENDER); - serviceClasses.add(BluetoothClass.Service.NETWORKING); - assertOnlyTheseServiceClassesAreSupported(deviceClass, serviceClasses); - Assert.assertEquals(BluetoothClass.Device.Major.COMPUTER, - BluetoothClass.Device.Major.getDeviceMajor(deviceClass)); - Assert.assertEquals(0x100, BluetoothClass.Device.getDevice(deviceClass)); - - deviceClass = 0x40020C; // Android - serviceClasses = new HashSet(); - serviceClasses.add(BluetoothClass.Service.TELEPHONY); - assertOnlyTheseServiceClassesAreSupported(deviceClass, serviceClasses); - Assert.assertEquals(BluetoothClass.Device.Major.PHONE, BluetoothClass.Device.Major.getDeviceMajor(deviceClass)); - Assert.assertEquals(0x20C, BluetoothClass.Device.getDevice(deviceClass)); - - // Motorola T305 & Jabra BT125 & Jabra BT250V - // This seems to be a very common headset & handsfree device code - deviceClass = 0x200404; - serviceClasses = new HashSet(); - serviceClasses.add(BluetoothClass.Service.AUDIO); - assertOnlyTheseServiceClassesAreSupported(deviceClass, serviceClasses); - Assert.assertEquals(BluetoothClass.Device.Major.AUDIO_VIDEO, - BluetoothClass.Device.Major.getDeviceMajor(deviceClass)); - Assert.assertEquals(BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET, - BluetoothClass.Device.getDevice(deviceClass)); - - // Audi UHV 0128 - deviceClass = 0x200408; - serviceClasses = new HashSet(); - serviceClasses.add(BluetoothClass.Service.AUDIO); - assertOnlyTheseServiceClassesAreSupported(deviceClass, serviceClasses); - Assert.assertEquals(BluetoothClass.Device.Major.AUDIO_VIDEO, - BluetoothClass.Device.Major.getDeviceMajor(deviceClass)); - Assert.assertEquals(BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE, - BluetoothClass.Device.getDevice(deviceClass)); - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/BuildTest.java b/tests/AndroidTests/src/com/android/unit_tests/BuildTest.java index a8c51f4bef0a8003ea749bcae09c89155fcf19b4..dbfd0e7ffcff1f45c0e9efea99c1c84b7fb29007 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/BuildTest.java +++ b/tests/AndroidTests/src/com/android/unit_tests/BuildTest.java @@ -55,6 +55,7 @@ public class BuildTest extends TestCase { @SmallTest public void testBuildFields() throws Exception { assertNotEmpty("ID", Build.ID); + assertNotEmpty("DISPLAY", Build.DISPLAY); assertNotEmpty("PRODUCT", Build.PRODUCT); assertNotEmpty("DEVICE", Build.DEVICE); assertNotEmpty("BOARD", Build.BOARD); diff --git a/tests/AndroidTests/src/com/android/unit_tests/CheckinProviderTest.java b/tests/AndroidTests/src/com/android/unit_tests/CheckinProviderTest.java deleted file mode 100644 index f9a2ec0f08a6d0c6ff9f27820c0059313987e368..0000000000000000000000000000000000000000 --- a/tests/AndroidTests/src/com/android/unit_tests/CheckinProviderTest.java +++ /dev/null @@ -1,187 +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. - */ - -package com.android.unit_tests; - -import org.apache.commons.codec.binary.Base64; - -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.ContentUris; -import android.database.Cursor; -import android.net.Uri; -import android.provider.Checkin; -import android.server.checkin.CheckinProvider; -import android.server.data.BuildData; -import android.server.data.CrashData; -import android.server.data.ThrowableData; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.SmallTest; - -import java.io.DataInputStream; -import java.io.ByteArrayInputStream; - -/** Unit test for {@link CheckinProvider}. */ -public class CheckinProviderTest extends AndroidTestCase { - @MediumTest - public void testEventReport() { - long start = System.currentTimeMillis(); - ContentResolver r = getContext().getContentResolver(); - Checkin.logEvent(r, Checkin.Events.Tag.TEST, "Test Value"); - - Cursor c = r.query(Checkin.Events.CONTENT_URI, - null, - Checkin.Events.TAG + "=?", - new String[] { Checkin.Events.Tag.TEST.toString() }, - null); - - long id = -1; - while (c.moveToNext()) { - String tag = c.getString(c.getColumnIndex(Checkin.Events.TAG)); - String value = c.getString(c.getColumnIndex(Checkin.Events.VALUE)); - long date = c.getLong(c.getColumnIndex(Checkin.Events.DATE)); - assertEquals(Checkin.Events.Tag.TEST.toString(), tag); - if ("Test Value".equals(value) && date >= start) { - assertTrue(id < 0); - id = c.getInt(c.getColumnIndex(Checkin.Events._ID)); - } - } - assertTrue(id > 0); - - int rows = r.delete(ContentUris.withAppendedId(Checkin.Events.CONTENT_URI, id), null, null); - assertEquals(1, rows); - c.requery(); - while (c.moveToNext()) { - long date = c.getLong(c.getColumnIndex(Checkin.Events.DATE)); - assertTrue(date < start); // Have deleted the only newer TEST. - } - - c.close(); - } - - @MediumTest - public void testStatsUpdate() { - ContentResolver r = getContext().getContentResolver(); - - // First, delete any existing data associated with the TEST tag. - Uri uri = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 0, 0); - assertNotNull(uri); - assertEquals(1, r.delete(uri, null, null)); - assertFalse(r.query(uri, null, null, null, null).moveToNext()); - - // Now, add a known quantity to the TEST tag. - Uri u2 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 1, 0.5); - assertFalse(uri.equals(u2)); - - Cursor c = r.query(u2, null, null, null, null); - assertTrue(c.moveToNext()); - assertEquals(1, c.getInt(c.getColumnIndex(Checkin.Stats.COUNT))); - assertEquals(0.5, c.getDouble(c.getColumnIndex(Checkin.Stats.SUM))); - assertFalse(c.moveToNext()); // Only one. - - // Add another known quantity to TEST (should sum with the first). - Uri u3 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 2, 1.0); - assertEquals(u2, u3); - c.requery(); - assertTrue(c.moveToNext()); - assertEquals(3, c.getInt(c.getColumnIndex(Checkin.Stats.COUNT))); - assertEquals(1.5, c.getDouble(c.getColumnIndex(Checkin.Stats.SUM))); - assertFalse(c.moveToNext()); // Only one. - - // Now subtract the values; the whole row should disappear. - Uri u4 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, -3, -1.5); - assertNull(u4); - c.requery(); - assertFalse(c.moveToNext()); // Row has been deleted. - c.close(); - } - - @MediumTest - public void testCrashReport() throws Exception { - long start = System.currentTimeMillis(); - ContentResolver r = getContext().getContentResolver(); - - // Log a test (fake) crash report. - Checkin.reportCrash(r, new CrashData( - "Test", - "Test Activity", - new BuildData("Test Build", "123", start), - new ThrowableData(new RuntimeException("Test Exception")))); - - - // Crashes aren't indexed; go through them all to find the one we added. - Cursor c = r.query(Checkin.Crashes.CONTENT_URI, null, null, null, null); - - Uri uri = null; - while (c.moveToNext()) { - String coded = c.getString(c.getColumnIndex(Checkin.Crashes.DATA)); - byte[] bytes = Base64.decodeBase64(coded.getBytes()); - CrashData crash = new CrashData( - new DataInputStream(new ByteArrayInputStream(bytes))); - - // Should be exactly one recently added "Test" crash. - if (crash.getId().equals("Test") && crash.getTime() > start) { - assertEquals("Test Activity", crash.getActivity()); - assertEquals("Test Build", crash.getBuildData().getFingerprint()); - assertEquals("Test Exception", - crash.getThrowableData().getMessage()); - - assertNull(uri); - uri = ContentUris.withAppendedId(Checkin.Crashes.CONTENT_URI, c.getInt(c.getColumnIndex(Checkin.Crashes._ID))); - } - } - assertNotNull(uri); - c.close(); - - // Update the "logs" column. - ContentValues values = new ContentValues(); - values.put(Checkin.Crashes.LOGS, "Test Logs"); - assertEquals(1, r.update(uri, values, null, null)); - - c = r.query(uri, null, null, null, null); - assertTrue(c.moveToNext()); - String logs = c.getString(c.getColumnIndex(Checkin.Crashes.LOGS)); - assertEquals("Test Logs", logs); - c.deleteRow(); - c.close(); - - c.requery(); - assertFalse(c.moveToNext()); - c.close(); - } - - @MediumTest - public void testPropertiesRestricted() throws Exception { - ContentResolver r = getContext().getContentResolver(); - - // The test app doesn't have the permission to access properties, - // so any attempt to do so should fail. - try { - r.insert(Checkin.Properties.CONTENT_URI, new ContentValues()); - fail("SecurityException expected"); - } catch (SecurityException e) { - // expected - } - - try { - r.query(Checkin.Properties.CONTENT_URI, null, null, null, null); - fail("SecurityException expected"); - } catch (SecurityException e) { - // expected - } - } -} diff --git a/tests/AndroidTests/src/com/android/unit_tests/DatabaseGeneralTest.java b/tests/AndroidTests/src/com/android/unit_tests/DatabaseGeneralTest.java index b004c938f72e4bd2d3feb4036abdb2dff27b8361..d775dc201526ce78fd7b9baaab87b5756f3285df 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/DatabaseGeneralTest.java +++ b/tests/AndroidTests/src/com/android/unit_tests/DatabaseGeneralTest.java @@ -166,15 +166,6 @@ public class DatabaseGeneralTest extends TestCase implements PerformanceTestCase assertEquals("+" + PHONE_NUMBER, number); c.close(); - c = mDatabase.query("phones", null, - "PHONE_NUMBERS_EQUAL(num, '+1 (617).555-1212p1234')", null, null, null, null); - assertNotNull(c); - assertEquals(1, c.getCount()); - c.moveToFirst(); - number = c.getString(c.getColumnIndexOrThrow("num")); - assertEquals("+" + PHONE_NUMBER, number); - c.close(); - c = mDatabase.query("phones", null, "PHONE_NUMBERS_EQUAL(num, '" + PHONE_NUMBER + "')", null, null, null, null); assertNotNull(c); diff --git a/tests/AndroidTests/src/com/android/unit_tests/DatabaseLocaleTest.java b/tests/AndroidTests/src/com/android/unit_tests/DatabaseLocaleTest.java index 0560c21ec5543f013d4f4b36fec664c64e2ba532..f07ca7c74ef6301e61ddafb0a551d62885e32a5e 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/DatabaseLocaleTest.java +++ b/tests/AndroidTests/src/com/android/unit_tests/DatabaseLocaleTest.java @@ -46,9 +46,13 @@ public class DatabaseLocaleTest extends TestCase { protected void setUp() throws Exception { super.setUp(); mDatabase = SQLiteDatabase.create(null); - mDatabase.execSQL("CREATE TABLE test (data TEXT COLLATE LOCALIZED);"); + mDatabase.execSQL( + "CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT COLLATE LOCALIZED);"); + } + + private void insertStrings() { for (String s : STRINGS) { - mDatabase.execSQL("INSERT INTO test VALUES('" + s + "');"); + mDatabase.execSQL("INSERT INTO test (data) VALUES('" + s + "');"); } } @@ -75,12 +79,14 @@ public class DatabaseLocaleTest extends TestCase { @MediumTest public void testLocaleInsertOrder() throws Exception { + insertStrings(); String[] results = query("SELECT data FROM test"); MoreAsserts.assertEquals(STRINGS, results); } @MediumTest public void testLocaleenUS() throws Exception { + insertStrings(); Log.i("LocaleTest", "about to call setLocale en_US"); mDatabase.setLocale(new Locale("en", "US")); String[] results; @@ -99,4 +105,25 @@ public class DatabaseLocaleTest extends TestCase { STRINGS[5], // "dog" }); } -} + + @SmallTest + public void testHoge() throws Exception { + Cursor cursor = null; + try { + String expectedString = new String(new int[] {0xFE000}, 0, 1); + mDatabase.execSQL("INSERT INTO test(id, data) VALUES(1, '" + expectedString + "')"); + cursor = mDatabase.rawQuery("SELECT data FROM test WHERE id = 1", null); + + assertNotNull(cursor); + assertTrue(cursor.moveToFirst()); + String actualString = cursor.getString(0); + assertEquals(expectedString.length(), actualString.length()); + for (int i = 0; i < expectedString.length(); i++) { + assertEquals((int)expectedString.charAt(i), (int)actualString.charAt(i)); + } + assertEquals(expectedString, actualString); + } finally { + if (cursor != null) cursor.close(); + } + } +} \ No newline at end of file diff --git a/tests/AndroidTests/src/com/android/unit_tests/DatabaseLockTest.java b/tests/AndroidTests/src/com/android/unit_tests/DatabaseLockTest.java new file mode 100644 index 0000000000000000000000000000000000000000..bb821e309c3cbc89878b89e735ce08e7504f855d --- /dev/null +++ b/tests/AndroidTests/src/com/android/unit_tests/DatabaseLockTest.java @@ -0,0 +1,170 @@ +/* + * 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. + */ + +package com.android.unit_tests; + +import android.app.Activity; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.test.suitebuilder.annotation.LargeTest; +import android.util.Log; +import java.io.File; +import java.util.concurrent.atomic.AtomicInteger; +import android.test.AndroidTestCase; + +import junit.framework.TestCase; + +/* + * This is a series of unit tests for database locks. + */ +public class DatabaseLockTest extends AndroidTestCase { + + private static final int NUM_ITERATIONS = 100; + private static final int SLEEP_TIME = 30; + private static final int MAX_ALLOWED_LATENCY_TIME = 30; + private SQLiteDatabase mDatabase; + private File mDatabaseFile; + private AtomicInteger mCounter = new AtomicInteger(); + + @Override + protected void setUp() throws Exception { + super.setUp(); + File parentDir = getContext().getFilesDir(); + mDatabaseFile = new File(parentDir, "database_test.db"); + + if (mDatabaseFile.exists()) { + mDatabaseFile.delete(); + } + mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null); + assertNotNull(mDatabase); + } + + @Override + protected void tearDown() throws Exception { + mDatabase.close(); + mDatabaseFile.delete(); + super.tearDown(); + } + + /* + * testLockFairness() tests the fairness of prioritizing multiple threads + * attempting to access a database concurrently. + * This test is intended to verify that, when two threads are accessing the + * same database at the same time with the same prioritization, neither thread + * is locked out and prevented from accessing the database. + */ + @LargeTest + public void testLockFairness() { + startDatabaseFairnessThread(); + int previous = 0; + for (int i = 0; i < NUM_ITERATIONS; i++) { + mDatabase.beginTransaction(); + int val = mCounter.get(); + if (i == 0) { + previous = val - i; + } + assertTrue(previous == (val - i)); + try { + Thread.currentThread().sleep(SLEEP_TIME); + } catch (InterruptedException e) { + // ignore + } + mDatabase.endTransaction(); + } + } + + /* + * This function is to create the second thread for testLockFairness() test. + */ + private void startDatabaseFairnessThread() { + Thread thread = new DatabaseFairnessThread(); + thread.start(); + } + + private class DatabaseFairnessThread extends Thread { + @Override + public void run() { + for (int i = 0; i < NUM_ITERATIONS; i++) { + mDatabase.beginTransaction(); + int val = mCounter.incrementAndGet(); + try { + Thread.currentThread().sleep(SLEEP_TIME); + } catch (InterruptedException e) { + // ignore + } + mDatabase.endTransaction(); + } + } + } + + /* + * testLockLatency() tests the latency of database locks. + * This test is intended to verify that, even when two threads are accessing + * the same database, the locking/unlocking of the database is done within an + * appropriate amount of time (MAX_ALLOWED_LATENCY_TIME). + */ + @LargeTest + public void testLockLatency() { + startDatabaseLatencyThread(); + int previous = 0; + long sumTime = 0; + long maxTime = 0; + for (int i = 0; i < NUM_ITERATIONS; i++) { + long startTime = System.currentTimeMillis(); + mDatabase.beginTransaction(); + long endTime = System.currentTimeMillis(); + long elapsedTime = endTime - startTime; + if (maxTime < elapsedTime) { + maxTime = elapsedTime; + } + sumTime += elapsedTime; + try { + Thread.currentThread().sleep(SLEEP_TIME); + } catch (InterruptedException e) { + // ignore + } + mDatabase.endTransaction(); + } + long averageTime = sumTime/NUM_ITERATIONS; + Log.i("DatabaseLockLatency", "AverageTime: " + averageTime); + Log.i("DatabaseLockLatency", "MaxTime: " + maxTime); + assertTrue( (averageTime - SLEEP_TIME) <= MAX_ALLOWED_LATENCY_TIME); + } + + /* + * This function is to create the second thread for testLockLatency() test. + */ + private void startDatabaseLatencyThread() { + Thread thread = new DatabaseLatencyThread(); + thread.start(); + } + + private class DatabaseLatencyThread extends Thread { + @Override + public void run() { + for (int i = 0; i < NUM_ITERATIONS; i++) + { + mDatabase.beginTransaction(); + try { + Thread.currentThread().sleep(SLEEP_TIME); + } catch (InterruptedException e) { + // ignore + } + mDatabase.endTransaction(); + } + } + } +} diff --git a/tests/AndroidTests/src/com/android/unit_tests/DatabaseTests.java b/tests/AndroidTests/src/com/android/unit_tests/DatabaseTests.java index 68b0b83aaa35dc0f66712e122ad7123fc9bcb410..a7a1400341dcf22918abca20be7a983111a8a0a5 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/DatabaseTests.java +++ b/tests/AndroidTests/src/com/android/unit_tests/DatabaseTests.java @@ -27,6 +27,7 @@ public class DatabaseTests { suite.addTestSuite(DatabaseStatementTest.class); suite.addTestSuite(DatabaseLocaleTest.class); suite.addTestSuite(CursorWindowTest.class); + suite.addTestSuite(DatabaseLockTest.class); return suite; } diff --git a/tests/AndroidTests/src/com/android/unit_tests/DbSSLSessionCacheTest.java b/tests/AndroidTests/src/com/android/unit_tests/DbSSLSessionCacheTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8d7d797c74accf26635b8d2340a4a5f370c96d56 --- /dev/null +++ b/tests/AndroidTests/src/com/android/unit_tests/DbSSLSessionCacheTest.java @@ -0,0 +1,259 @@ +/* + * 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. + */ + +package com.android.unit_tests; + +import android.content.ContentResolver; +import android.database.Cursor; +import android.database.sqlite.SQLiteOpenHelper; +import android.provider.Settings; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.LargeTest; +import android.test.suitebuilder.annotation.Suppress; + +import com.google.android.net.GoogleHttpClient; + +import com.android.internal.net.DbSSLSessionCache; +import com.android.internal.net.DbSSLSessionCache.DatabaseHelper; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; + +import java.io.IOException; +import java.security.Principal; +import java.security.cert.Certificate; + +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSessionContext; +import javax.security.cert.X509Certificate; + +/** Unit test for SSL session caching with {@link GoogleHttpClient}. + * Uses network resources. + */ +@Suppress +public class DbSSLSessionCacheTest extends AndroidTestCase { + + protected void setUp() throws Exception { + } + + protected void tearDown() throws Exception { + } + + /** + * We want to test the actual database write - the actual hooking into + * low-level SSL is tested. + */ + @LargeTest + public void testSslCacheAdd() throws Exception { + // Let's verify the database has the rows. + // Use internal details of the implementation - could make the field + // visible for testing, but it's same. + + // Use default database + DbSSLSessionCache cache = DbSSLSessionCache.getInstanceForPackage(getContext()); + cache.clear(); + + + makeRequestInNewContext("https://www.google.com"); + + // Verify the key was inserted + SQLiteOpenHelper helper = new DatabaseHelper(getContext()); + Cursor query = null; + try { + query = helper.getReadableDatabase().query(DbSSLSessionCache.SSL_CACHE_TABLE, + new String[] {"hostport"}, null, + null, null, null, null); + + assertTrue(query.moveToFirst()); // one row inserted + String hostPort = query.getString(0); + assertEquals(hostPort, "www.google.com:443"); + } finally { + query.close(); + } + } + + @LargeTest + public void testExpire() throws Exception { + DatabaseHelper helper = new DatabaseHelper(getContext()); + // clean up + DbSSLSessionCache cache = new DbSSLSessionCache(helper); + cache.clear(); + + long t0 = System.currentTimeMillis(); + for (int i = 0; i < DbSSLSessionCache.MAX_CACHE_SIZE + 2; i++) { + final int port = i; + cache.putSessionData(new MockSession() { + + public String getPeerHost() { + return "test.host.com"; + } + + public int getPeerPort() { + return port; + } + }, new byte[256]); + } + long t1 = System.currentTimeMillis(); + + System.err.println("Time to insert " + + (DbSSLSessionCache.MAX_CACHE_SIZE + 2) + " " + (t1 - t0)); + + // first entry should have port 1. + Cursor query = helper.getReadableDatabase().query(DbSSLSessionCache.SSL_CACHE_TABLE, + new String[] {"hostport", "session"}, null, + null, null, null, null); + + int cnt = query.getCount(); + + assertTrue(query.moveToFirst()); // one row inserted + String hostPort = query.getString(0); + assertEquals("test.host.com:2", hostPort); + while (query.moveToNext()) { + hostPort = query.getString(0); + String session = query.getString(1); + } + long t2 = System.currentTimeMillis(); + System.err.println("Time to load " + cnt + " " + (t2 - t1)); + + query.close(); + } + + private void makeRequestInNewContext(String url) throws IOException { + GoogleHttpClient client = new GoogleHttpClient(getContext(), "Test", + false /* no gzip */); + + try { + // Note: we must test against a real server, because the connection + // gets established before the interceptor can crash the request. + HttpGet method = new HttpGet(url); + HttpResponse response = client.execute(method); + } finally { + client.close(); + } + } + + private static class MockSession implements SSLSession { + + public String getPeerHost() { + throw new UnsupportedOperationException(); + } + + + public int getPeerPort() { + throw new UnsupportedOperationException(); + } + + + + public int getApplicationBufferSize() { + throw new UnsupportedOperationException(); + } + + + public String getCipherSuite() { + throw new UnsupportedOperationException(); + } + + + public long getCreationTime() { + throw new UnsupportedOperationException(); + } + + + public byte[] getId() { + throw new UnsupportedOperationException(); + } + + + public long getLastAccessedTime() { + throw new UnsupportedOperationException(); + } + + + public Certificate[] getLocalCertificates() { + throw new UnsupportedOperationException(); + } + + + public Principal getLocalPrincipal() { + throw new UnsupportedOperationException(); + } + + + public int getPacketBufferSize() { + throw new UnsupportedOperationException(); + } + + + public X509Certificate[] getPeerCertificateChain() + throws SSLPeerUnverifiedException { + throw new UnsupportedOperationException(); + } + + + public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException { + throw new UnsupportedOperationException(); + } + + + public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { + throw new UnsupportedOperationException(); + } + + + public String getProtocol() { + throw new UnsupportedOperationException(); + } + + + public SSLSessionContext getSessionContext() { + throw new UnsupportedOperationException(); + } + + + public Object getValue(String name) { + throw new UnsupportedOperationException(); + } + + + public String[] getValueNames() { + throw new UnsupportedOperationException(); + } + + + public void invalidate() { + throw new UnsupportedOperationException(); + } + + + public boolean isValid() { + throw new UnsupportedOperationException(); + } + + + public void putValue(String name, Object value) { + throw new UnsupportedOperationException(); + } + + + public void removeValue(String name) { + throw new UnsupportedOperationException(); + } + } + + +} diff --git a/tests/AndroidTests/src/com/android/unit_tests/HtmlTest.java b/tests/AndroidTests/src/com/android/unit_tests/HtmlTest.java index 26a3ae0f84e46770070cbf18d5a5964ec9ec46a3..27da4f1c72aef2da3822a2f4553416599a70cb67 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/HtmlTest.java +++ b/tests/AndroidTests/src/com/android/unit_tests/HtmlTest.java @@ -61,6 +61,10 @@ public class HtmlTest extends TestCase { s = new SpannableString("Hello world\n\n\nor something"); assertEquals(Html.toHtml(s), "

            Hello world

            \n

            or something

            \n"); + + assertEquals("foo\nbar", Html.fromHtml("foo
            bar").toString()); + assertEquals("foo\nbar", Html.fromHtml("foo
            \nbar").toString()); + assertEquals("foo\nbar", Html.fromHtml("foo
            \n \nbar").toString()); } @SmallTest diff --git a/tests/AndroidTests/src/com/android/unit_tests/MenuTest.java b/tests/AndroidTests/src/com/android/unit_tests/MenuTest.java index d184543dfb2598d796b7d63fbb7d44353c7b606b..c436726a0fc874060c676d5d2c3e524510be3d10 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/MenuTest.java +++ b/tests/AndroidTests/src/com/android/unit_tests/MenuTest.java @@ -131,20 +131,7 @@ public class MenuTest extends AndroidTestCase { makeKeyEvent(KeyEvent.KEYCODE_A, KeyEvent.META_SYM_ON))); } - - @LargeTest - public void testIsNotShortcutWithMultipleMetas() throws Exception { - mMenu.setQwertyMode(true); - mMenu.add(0, 0, 0, "test").setShortcut('2', 'a'); - Assert.assertFalse(mMenu.isShortcutKey( - 'a', - makeKeyEvent(KeyEvent.KEYCODE_A, KeyEvent.META_SYM_ON & KeyEvent.META_ALT_ON))); - Assert.assertFalse(mMenu.isShortcutKey( - 'a', makeKeyEvent(KeyEvent.KEYCODE_A, KeyEvent.META_SYM_ON))); - Assert.assertFalse(mMenu.isShortcutKey( - 'a', makeKeyEvent(KeyEvent.KEYCODE_A, KeyEvent.META_SHIFT_ON))); - } - + @SmallTest public void testIsShortcutWithUpperCaseAlpha() throws Exception { mMenu.setQwertyMode(true); diff --git a/tests/AndroidTests/src/com/android/unit_tests/NewDatabasePerformanceTestSuite.java b/tests/AndroidTests/src/com/android/unit_tests/NewDatabasePerformanceTestSuite.java new file mode 100644 index 0000000000000000000000000000000000000000..3462f97dec077934a9237b8fd4a5af76e494b3a3 --- /dev/null +++ b/tests/AndroidTests/src/com/android/unit_tests/NewDatabasePerformanceTestSuite.java @@ -0,0 +1,94 @@ +/* + * 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. + */ + +package com.android.unit_tests; +import android.test.FrameworkTests; +import android.test.suitebuilder.TestSuiteBuilder; + +import junit.framework.TestSuite; +import junit.framework.TestCase; + +public class NewDatabasePerformanceTestSuite extends TestSuite { + public static TestSuite suite() { + TestSuite suite = + new TestSuite(NewDatabasePerformanceTestSuite.class.getName()); + + suite.addTestSuite(NewDatabasePerformanceTests. + Insert1000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + InsertIndexed1000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + Select100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectStringComparison100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectIndex100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + InnerJoin100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + InnerJoinOneSide100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + InnerJoinNoIndex100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectSubQIndex100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectIndexStringComparison100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectInteger100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectString100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectIntegerIndex100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectIndexString100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectStringStartsWith100.class); + suite.addTestSuite(NewDatabasePerformanceTests. + DeleteIndexed1000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + Delete1000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + DeleteWhere1000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + DeleteIndexWhere1000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + UpdateIndexWhere1000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + UpdateWhere1000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + InsertInteger10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + InsertIntegerIndex10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + InsertString10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + InsertStringIndexed10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectStringStartsWith10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectStringIndexedStartsWith10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectInteger10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectIntegerIndexed10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectStringContains10000.class); + suite.addTestSuite(NewDatabasePerformanceTests. + SelectStringIndexedContains10000.class); + + return suite; + } +} diff --git a/tests/AndroidTests/src/com/android/unit_tests/NewDatabasePerformanceTests.java b/tests/AndroidTests/src/com/android/unit_tests/NewDatabasePerformanceTests.java new file mode 100644 index 0000000000000000000000000000000000000000..8644fbb657d34bd9443936cb919d3cbd9abc0078 --- /dev/null +++ b/tests/AndroidTests/src/com/android/unit_tests/NewDatabasePerformanceTests.java @@ -0,0 +1,1234 @@ +/* + * 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. + */ + +package com.android.unit_tests; + +import android.content.ContentValues; +import android.database.sqlite.SQLiteDatabase; +import android.test.PerformanceTestCase; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import java.io.File; +import java.util.Random; + +/** + * Database Performance Tests + * + */ + +public class NewDatabasePerformanceTests { + + // Edit this to change the test run times. The original is 100. + final static int kMultiplier = 1; + + public static class PerformanceBase extends TestCase + implements PerformanceTestCase { + protected static final int CURRENT_DATABASE_VERSION = 42; + protected SQLiteDatabase mDatabase; + protected File mDatabaseFile; + + public void setUp() { + mDatabaseFile = new File("/sdcard", "perf_database_test.db"); + if (mDatabaseFile.exists()) { + mDatabaseFile.delete(); + } + mDatabase = + SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), + null); + assertTrue(mDatabase != null); + mDatabase.setVersion(CURRENT_DATABASE_VERSION); + } + + public void tearDown() { + mDatabase.close(); + mDatabaseFile.delete(); + } + + public boolean isPerformanceOnly() { + return true; + } + + // These tests can only be run once. + public int startPerformance(Intermediates intermediates) { + return 0; + } + + public String numberName(int number) { + String result = ""; + + if (number >= 1000) { + result += numberName((number / 1000)) + " thousand"; + number = (number % 1000); + + if (number > 0) result += " "; + } + + if (number >= 100) { + result += ONES[(number / 100)] + " hundred"; + number = (number % 100); + + if (number > 0) result += " "; + } + + if (number >= 20) { + result += TENS[(number / 10)]; + number = (number % 10); + + if (number > 0) result += " "; + } + + if (number > 0) { + result += ONES[number]; + } + + return result; + } + } + + /** + * Test 1000 inserts. + */ + + public static class Insert1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + + private String[] statements = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + statements[i] = + "INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"; + } + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.execSQL(statements[i]); + } + } + } + + /** + * Test 1000 inserts into an indexed table. + */ + + public static class InsertIndexed1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + + private String[] statements = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + statements[i] = + "INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"; + } + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.execSQL(statements[i]); + } + } + } + + /** + * 100 SELECTs without an index + */ + + public static class Select100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 100 SELECTs on a string comparison + */ + + public static class SelectStringComparison100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + where[i] = "c LIKE '" + numberName(i) + "'"; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 100 SELECTs with an index + */ + + public static class SelectIndex100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * INNER JOIN without an index + */ + + public static class InnerJoin100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"t1.a"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + } + + public void testRun() { + mDatabase.query("t1 INNER JOIN t2 ON t1.b = t2.b", COLUMNS, null, + null, null, null, null); + } + } + + /** + * INNER JOIN without an index on one side + */ + + public static class InnerJoinOneSide100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"t1.a"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); + + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + } + + public void testRun() { + mDatabase.query("t1 INNER JOIN t2 ON t1.b = t2.b", COLUMNS, null, + null, null, null, null); + } + } + + /** + * INNER JOIN without an index on one side + */ + + public static class InnerJoinNoIndex100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"t1.a"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); + + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + } + + public void testRun() { + mDatabase.query("t1 INNER JOIN t2 ON t1.c = t2.c", COLUMNS, null, + null, null, null, null); + } + } + + /** + * 100 SELECTs with subqueries. Subquery is using an index + */ + + public static class SelectSubQIndex100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"t1.a"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); + + mDatabase.execSQL("CREATE INDEX i2b ON t2(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = + "t1.b IN (SELECT t2.b FROM t2 WHERE t2.b >= " + lower + + " AND t2.b < " + upper + ")"; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 100 SELECTs on string comparison with Index + */ + + public static class SelectIndexStringComparison100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i3c ON t1(c)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + where[i] = "c LIKE '" + numberName(i) + "'"; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 100 SELECTs on integer + */ + + public static class SelectInteger100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"b"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t1", COLUMNS, null, null, null, null, null); + } + } + } + + /** + * 100 SELECTs on String + */ + + public static class SelectString100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"c"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t1", COLUMNS, null, null, null, null, null); + } + } + } + + /** + * 100 SELECTs on integer with index + */ + + public static class SelectIntegerIndex100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"b"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1b on t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t1", COLUMNS, null, null, null, null, null); + } + } + } + + /** + * 100 SELECTs on String with index + */ + + public static class SelectIndexString100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"c"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t1", COLUMNS, null, null, null, null, null); + } + } + } + + /** + * 100 SELECTs on String with starts with + */ + + public static class SelectStringStartsWith100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"c"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + where[i] = "c LIKE '" + numberName(r).substring(0, 1) + "*'"; + + } + + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 1000 Deletes on an indexed table + */ + + public static class DeleteIndexed1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private static final String[] COLUMNS = {"c"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i3c ON t1(c)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.delete("t1", null, null); + } + } + } + + /** + * 1000 Deletes + */ + + public static class Delete1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private static final String[] COLUMNS = {"c"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.delete("t1", null, null); + } + } + } + + /** + * 1000 DELETE's without an index with where clause + */ + + public static class DeleteWhere1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.delete("t1", where[i], null); + } + } + } + + /** + * 1000 DELETE's with an index with where clause + */ + + public static class DeleteIndexWhere1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.delete("t1", where[i], null); + } + } + } + + /** + * 1000 update's with an index with where clause + */ + + public static class UpdateIndexWhere1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private String[] where = new String[SIZE]; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + ContentValues b = new ContentValues(1); + b.put("b", upper); + mValues[i] = b; + + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.update("t1", mValues[i], where[i], null); + } + } + } + + /** + * 1000 update's without an index with where clause + */ + + public static class UpdateWhere1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private String[] where = new String[SIZE]; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + ContentValues b = new ContentValues(1); + b.put("b", upper); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.update("t1", mValues[i], where[i], null); + } + } + } + + /** + * 10000 inserts for an integer + */ + + public static class InsertInteger10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + ContentValues b = new ContentValues(1); + b.put("a", r); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.insert("t1", null, mValues[i]); + } + } + } + + /** + * 10000 inserts for an integer -indexed table + */ + + public static class InsertIntegerIndex10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER)"); + mDatabase.execSQL("CREATE INDEX i1a ON t1(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + ContentValues b = new ContentValues(1); + b.put("a", r); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.insert("t1", null, mValues[i]); + } + } + } + + /** + * 10000 inserts for a String + */ + + public static class InsertString10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + ContentValues b = new ContentValues(1); + b.put("a", numberName(r)); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.insert("t1", null, mValues[i]); + } + } + } + + /** + * 10000 inserts for a String - indexed table + */ + + public static class InsertStringIndexed10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1a ON t1(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + ContentValues b = new ContentValues(1); + b.put("a", numberName(r)); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.insert("t1", null, mValues[i]); + } + } + } + + + /** + * 10000 selects for a String -starts with + */ + + public static class SelectStringStartsWith10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t3.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t3(a VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t3 VALUES('" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + where[i] = "a LIKE '" + numberName(r).substring(0, 1) + "*'"; + + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 10000 selects for a String - indexed table -starts with + */ + + public static class SelectStringIndexedStartsWith10000 extends + PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t3.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t3(a VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i3a ON t3(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t3 VALUES('" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + where[i] = "a LIKE '" + numberName(r).substring(0, 1) + "*'"; + + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 10000 selects for an integer - + */ + + public static class SelectInteger10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t4.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t4(a INTEGER)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t4 VALUES(" + r + ")"); + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "a >= " + lower + " AND a < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t4", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 10000 selects for an integer -indexed table + */ + + public static class SelectIntegerIndexed10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t4.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t4(a INTEGER)"); + mDatabase.execSQL("CREATE INDEX i4a ON t4(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t4 VALUES(" + r + ")"); + + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "a >= " + lower + " AND a < " + upper; + } + + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t4", COLUMNS, where[i], null, null, null, null); + } + } + } + + + /** + * 10000 selects for a String - contains 'e' + */ + + public static class SelectStringContains10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t3.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t3(a VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t3 VALUES('" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + where[i] = "a LIKE '*e*'"; + + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); + } + } + } + + /** + * 10000 selects for a String - contains 'e'-indexed table + */ + + public static class SelectStringIndexedContains10000 extends + PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t3.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t3(a VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i3a ON t3(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t3 VALUES('" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + where[i] = "a LIKE '*e*'"; + + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); + } + } + } + + public static final String[] ONES = + {"zero", "one", "two", "three", "four", "five", "six", "seven", + "eight", "nine", "ten", "eleven", "twelve", "thirteen", + "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", + "nineteen"}; + + public static final String[] TENS = + {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", + "seventy", "eighty", "ninety"}; +} diff --git a/tests/AndroidTests/src/com/android/unit_tests/SSLClientSessionCacheFactoryTest.java b/tests/AndroidTests/src/com/android/unit_tests/SSLClientSessionCacheFactoryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5d7349f79bd9cc1d5ba3e9ee68dafd2daee65954 --- /dev/null +++ b/tests/AndroidTests/src/com/android/unit_tests/SSLClientSessionCacheFactoryTest.java @@ -0,0 +1,54 @@ +package com.android.unit_tests; + +import com.google.android.net.SSLClientSessionCacheFactory; +import com.android.internal.net.DbSSLSessionCache; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.MediumTest; +import android.content.ContentResolver; +import android.content.Context; +import android.provider.Settings; +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; + +/** + * Unit test for {@link SSLClientSessionCacheFactory}. + */ +@MediumTest +public final class SSLClientSessionCacheFactoryTest extends AndroidTestCase { + + protected void tearDown() throws Exception { + setSslSessionCacheValue(getContext(), ""); + super.tearDown(); + } + + private static void setSslSessionCacheValue(Context context, String value) { + ContentResolver resolver = context.getContentResolver(); + Settings.Gservices.putString(resolver, Settings.Gservices.SSL_SESSION_CACHE, value); + } + + private static SSLClientSessionCache getCache(Context context, String type) { + setSslSessionCacheValue(context, type); + return SSLClientSessionCacheFactory.getCache(context); + } + + public void testGetDbCache() throws Exception { + Context context = getContext(); + SSLClientSessionCache cache = getCache(context, "db"); + assertNotNull(cache); + assertTrue(cache instanceof DbSSLSessionCache); + } + + public void testGetFileCache() throws Exception { + Context context = getContext(); + SSLClientSessionCache cache = getCache(context, "file"); + assertNotNull(cache); + // yuck =) + assertEquals("org.apache.harmony.xnet.provider.jsse.FileClientSessionCache$Impl", + cache.getClass().getName()); + } + + public void testGetNoCache() throws Exception { + Context context = getContext(); + SSLClientSessionCache cache = getCache(context, "none"); + assertNull(cache); + } +} diff --git a/tests/AndroidTests/src/com/android/unit_tests/TextUtilsTest.java b/tests/AndroidTests/src/com/android/unit_tests/TextUtilsTest.java index 8c1c91f4cd31d441f66cf4aab514afe215c585ef..51e841cb8d3a3b873cee9dbdf77669b7fa5a24db 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/TextUtilsTest.java +++ b/tests/AndroidTests/src/com/android/unit_tests/TextUtilsTest.java @@ -262,7 +262,7 @@ public class TextUtilsTest extends TestCase { Map fixes = Maps.newHashMap(); fixes.put("a", ""); fixes.put("a b", ""); - fixes.put("a@b", ""); + fixes.put("a@b", ""); for (Map.Entry e : fixes.entrySet()) { assertEquals(e.getValue(), validator.fixText(e.getKey()).toString()); diff --git a/tests/AndroidTests/src/com/android/unit_tests/activity/ActivityManagerTest.java b/tests/AndroidTests/src/com/android/unit_tests/activity/ActivityManagerTest.java index d7d8c893c78f3a9596369eea517549cf72177e53..ab917614031216c843165b220640ea14a03c05a3 100644 --- a/tests/AndroidTests/src/com/android/unit_tests/activity/ActivityManagerTest.java +++ b/tests/AndroidTests/src/com/android/unit_tests/activity/ActivityManagerTest.java @@ -18,6 +18,8 @@ package com.android.unit_tests.activity; import android.app.ActivityManager; import android.content.Context; +import android.content.pm.ConfigurationInfo; +import android.content.res.Configuration; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; import android.test.suitebuilder.annotation.Suppress; @@ -90,6 +92,24 @@ public class ActivityManagerTest extends AndroidTestCase { // test: confirm our ANR'ing application shows up in the list } + @SmallTest + public void testGetDeviceConfigurationInfo() throws Exception { + ConfigurationInfo config = mActivityManager.getDeviceConfigurationInfo(); + assertNotNull(config); + // Validate values against configuration retrieved from resources + Configuration vconfig = mContext.getResources().getConfiguration(); + assertNotNull(vconfig); + assertEquals(config.reqKeyboardType, vconfig.keyboard); + assertEquals(config.reqTouchScreen, vconfig.touchscreen); + assertEquals(config.reqNavigation, vconfig.navigation); + if (vconfig.navigation == Configuration.NAVIGATION_NONAV) { + assertNotNull(config.reqInputFeatures & ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV); + } + if (vconfig.keyboard != Configuration.KEYBOARD_UNDEFINED) { + assertNotNull(config.reqInputFeatures & ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD); + } + } + // If any entries in appear in the list, sanity check them against all running applications private void checkErrorListSanity(List errList) { if (errList == null) return; diff --git a/tests/CoreTests/android/Android.mk b/tests/CoreTests/android/Android.mk index 3b80228d75abb21bf8295b4d6f9085f596270e49..e6b5c4597db636c244290db001032c36e089a1f3 100644 --- a/tests/CoreTests/android/Android.mk +++ b/tests/CoreTests/android/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := eng tests +LOCAL_MODULE_TAGS := tests LOCAL_SRC_FILES := \ $(call all-subdir-java-files) diff --git a/tests/CoreTests/android/AndroidManifest.xml b/tests/CoreTests/android/AndroidManifest.xml index 8c642f4a9018ec43e83a6aff9e14cd9be3da5e85..4809f84499e51f7497861e3c2fc9d06cd3c5b2be 100644 --- a/tests/CoreTests/android/AndroidManifest.xml +++ b/tests/CoreTests/android/AndroidManifest.xml @@ -23,6 +23,7 @@ + diff --git a/tests/CoreTests/android/core/DatabaseSessionCache.java b/tests/CoreTests/android/core/DatabaseSessionCache.java new file mode 100644 index 0000000000000000000000000000000000000000..c344d9ce197984d5497180f56b2a37dac867d323 --- /dev/null +++ b/tests/CoreTests/android/core/DatabaseSessionCache.java @@ -0,0 +1,312 @@ +// Copyright 2009 The Android Open Source Project + +package android.core; + +import android.database.Cursor; +import android.database.SQLException; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; +import android.content.ContentValues; +import android.content.Context; + +import org.apache.commons.codec.binary.Base64; +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; + +import java.util.LinkedHashMap; +import java.util.Map; + +import javax.net.ssl.SSLSession; + +/** + * Hook into harmony SSL cache to persist the SSL sessions. + * + * Current implementation is suitable for saving a small number of hosts - + * like google services. It can be extended with expiration and more features + * to support more hosts. + * + * {@hide} + */ +public class DatabaseSessionCache implements SSLClientSessionCache { + private static final String TAG = "SslSessionCache"; + static DatabaseHelper sDefaultDatabaseHelper; + + private DatabaseHelper mDatabaseHelper; + + /** + * Table where sessions are stored. + */ + public static final String SSL_CACHE_TABLE = "ssl_sessions"; + + private static final String SSL_CACHE_ID = "_id"; + + /** + * Key is host:port - port is not optional. + */ + private static final String SSL_CACHE_HOSTPORT = "hostport"; + + /** + * Base64-encoded DER value of the session. + */ + private static final String SSL_CACHE_SESSION = "session"; + + /** + * Time when the record was added - should be close to the time + * of the initial session negotiation. + */ + private static final String SSL_CACHE_TIME_SEC = "time_sec"; + + public static final String DATABASE_NAME = "ssl_sessions.db"; + + public static final int DATABASE_VERSION = 1; + + /** public for testing + */ + public static final int SSL_CACHE_ID_COL = 0; + public static final int SSL_CACHE_HOSTPORT_COL = 1; + public static final int SSL_CACHE_SESSION_COL = 2; + public static final int SSL_CACHE_TIME_SEC_COL = 3; + + private static final String SAVE_ON_ADD = "save_on_add"; + + static boolean sHookInitializationDone = false; + + public static final int MAX_CACHE_SIZE = 256; + + private static final Map mExternalCache = + new LinkedHashMap(MAX_CACHE_SIZE, 0.75f, true) { + @Override + public boolean removeEldestEntry( + Map.Entry eldest) { + boolean shouldDelete = this.size() > MAX_CACHE_SIZE; + + // TODO: delete from DB + return shouldDelete; + } + }; + static boolean mNeedsCacheLoad = true; + + public static final String[] PROJECTION = new String[] { + SSL_CACHE_ID, + SSL_CACHE_HOSTPORT, + SSL_CACHE_SESSION, + SSL_CACHE_TIME_SEC + }; + + /** + * This class needs to be installed as a hook, if the security property + * is set. Getting the right classloader may be fun since we don't use + * Provider to get its classloader, but in android this is in same + * loader with AndroidHttpClient. + * + * This constructor will use the default database. You must + * call init() before to specify the context used for the database and + * check settings. + */ + public DatabaseSessionCache() { + Log.v(TAG, "Instance created."); + // May be null if caching is disabled - no sessions will be persisted. + this.mDatabaseHelper = sDefaultDatabaseHelper; + } + + /** + * Create a SslSessionCache instance, using the specified context to + * initialize the database. + * + * This constructor will use the default database - created the first + * time. + * + * @param activityContext + */ + public DatabaseSessionCache(Context activityContext) { + // Static init - only one initialization will happen. + // Each SslSessionCache is using the same DB. + init(activityContext); + // May be null if caching is disabled - no sessions will be persisted. + this.mDatabaseHelper = sDefaultDatabaseHelper; + } + + /** + * Create a SslSessionCache that uses a specific database. + * + * @param database + */ + public DatabaseSessionCache(DatabaseHelper database) { + this.mDatabaseHelper = database; + } + +// public static boolean enabled(Context androidContext) { +// String sslCache = Settings.Gservices.getString(androidContext.getContentResolver(), +// Settings.Gservices.SSL_SESSION_CACHE); +// +// if (Log.isLoggable(TAG, Log.DEBUG)) { +// Log.d(TAG, "enabled " + sslCache + " " + androidContext.getPackageName()); +// } +// +// return SAVE_ON_ADD.equals(sslCache); +// } + + /** + * You must call this method to enable SSL session caching for an app. + */ + public synchronized static void init(Context activityContext) { + // It is possible that multiple provider will try to install this hook. + // We want a single db per VM. + if (sHookInitializationDone) { + return; + } + + +// // More values can be added in future to provide different +// // behaviours, like 'batch save'. +// if (enabled(activityContext)) { + Context appContext = activityContext.getApplicationContext(); + sDefaultDatabaseHelper = new DatabaseHelper(appContext); + + // Set default SSLSocketFactory + // The property is defined in the javadocs for javax.net.SSLSocketFactory + // (no constant defined there) + // This should cover all code using SSLSocketFactory.getDefault(), + // including native http client and apache httpclient. + // MCS is using its own custom factory - will need special code. +// Security.setProperty("ssl.SocketFactory.provider", +// SslSocketFactoryWithCache.class.getName()); +// } + + // Won't try again. + sHookInitializationDone = true; + } + + public void putSessionData(SSLSession session, byte[] der) { + if (mDatabaseHelper == null) { + return; + } + if (mExternalCache.size() > MAX_CACHE_SIZE) { + // remove oldest. + Cursor byTime = mDatabaseHelper.getWritableDatabase().query(SSL_CACHE_TABLE, + PROJECTION, null, null, null, null, SSL_CACHE_TIME_SEC); + byTime.moveToFirst(); + // TODO: can I do byTime.deleteRow() ? + String hostPort = byTime.getString(SSL_CACHE_HOSTPORT_COL); + + mDatabaseHelper.getWritableDatabase().delete(SSL_CACHE_TABLE, + SSL_CACHE_HOSTPORT + "= ?" , new String[] { hostPort }); + } + // Serialize native session to standard DER encoding + long t0 = System.currentTimeMillis(); + + String b64 = new String(Base64.encodeBase64(der)); + String key = session.getPeerHost() + ":" + session.getPeerPort(); + + ContentValues values = new ContentValues(); + values.put(SSL_CACHE_HOSTPORT, key); + values.put(SSL_CACHE_SESSION, b64); + values.put(SSL_CACHE_TIME_SEC, System.currentTimeMillis() / 1000); + + synchronized (this.getClass()) { + mExternalCache.put(key, der); + + try { + mDatabaseHelper.getWritableDatabase().insert(SSL_CACHE_TABLE, null /*nullColumnHack */ , values); + } catch(SQLException ex) { + // Ignore - nothing we can do to recover, and caller shouldn't + // be affected. + Log.w(TAG, "Ignoring SQL exception when caching session", ex); + } + } + if (Log.isLoggable(TAG, Log.DEBUG)) { + long t1 = System.currentTimeMillis(); + Log.d(TAG, "New SSL session " + session.getPeerHost() + + " DER len: " + der.length + " " + (t1 - t0)); + } + + } + + public byte[] getSessionData(String host, int port) { + // Current (simple) implementation does a single lookup to DB, then saves + // all entries to the cache. + + // This works for google services - i.e. small number of certs. + // If we extend this to all processes - we should hold a separate cache + // or do lookups to DB each time. + if (mDatabaseHelper == null) { + return null; + } + synchronized(this.getClass()) { + if (mNeedsCacheLoad) { + // Don't try to load again, if something is wrong on the first + // request it'll likely be wrong each time. + mNeedsCacheLoad = false; + long t0 = System.currentTimeMillis(); + + Cursor cur = null; + try { + cur = mDatabaseHelper.getReadableDatabase().query(SSL_CACHE_TABLE, PROJECTION, null, + null, null, null, null); + if (cur.moveToFirst()) { + do { + String hostPort = cur.getString(SSL_CACHE_HOSTPORT_COL); + String value = cur.getString(SSL_CACHE_SESSION_COL); + + if (hostPort == null || value == null) { + continue; + } + // TODO: blob support ? + byte[] der = Base64.decodeBase64(value.getBytes()); + mExternalCache.put(hostPort, der); + } while (cur.moveToNext()); + + } + } catch (SQLException ex) { + Log.d(TAG, "Error loading SSL cached entries ", ex); + } finally { + if (cur != null) { + cur.close(); + } + if (Log.isLoggable(TAG, Log.DEBUG)) { + long t1 = System.currentTimeMillis(); + Log.d(TAG, "LOADED CACHED SSL " + (t1 - t0) + " ms"); + } + } + } + + String key = host + ":" + port; + + return mExternalCache.get(key); + } + } + + public byte[] getSessionData(byte[] id) { + // We support client side only - the cache will do nothing on client. + return null; + } + + /** Visible for testing. + */ + public static class DatabaseHelper extends SQLiteOpenHelper { + + public DatabaseHelper(Context context) { + super(context, DATABASE_NAME, null /* factory */, DATABASE_VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + db.execSQL("CREATE TABLE " + SSL_CACHE_TABLE + " (" + + SSL_CACHE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + SSL_CACHE_HOSTPORT + " TEXT UNIQUE ON CONFLICT REPLACE," + + SSL_CACHE_SESSION + " TEXT," + + SSL_CACHE_TIME_SEC + " INTEGER" + + ");"); + db.execSQL("CREATE INDEX ssl_sessions_idx1 ON ssl_sessions (" + + SSL_CACHE_HOSTPORT + ");"); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + db.execSQL("DROP TABLE IF EXISTS " + SSL_CACHE_TABLE ); + onCreate(db); + } + + } + +} \ No newline at end of file diff --git a/tests/CoreTests/android/core/SSLPerformanceTest.java b/tests/CoreTests/android/core/SSLPerformanceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e2bd9c566668d5b63686067af33f1f5f469029db --- /dev/null +++ b/tests/CoreTests/android/core/SSLPerformanceTest.java @@ -0,0 +1,432 @@ +/* + * 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. + */ + +package android.core; + +import android.test.AndroidTestCase; +import android.os.Debug; +import org.apache.harmony.xnet.provider.jsse.FileClientSessionCache; +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; +import org.apache.harmony.xnet.provider.jsse.SSLContextImpl; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.conn.SingleClientConnManager; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.HttpResponse; + +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSessionContext; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Method; +import java.lang.reflect.InvocationTargetException; +import java.security.cert.Certificate; +import java.security.Principal; +import java.security.KeyManagementException; +import java.util.Arrays; + +public class SSLPerformanceTest extends AndroidTestCase { + + static final byte[] SESSION_DATA = new byte[6000]; + static { + for (int i = 0; i < SESSION_DATA.length; i++) { + SESSION_DATA[i] = (byte) i; + } + } + + static final File dataDir = new File("/data/data/android.core/"); + static final File filesDir = new File(dataDir, "files"); + static final File dbDir = new File(dataDir, "databases"); + + static final String CACHE_DIR + = SSLPerformanceTest.class.getName() + "/cache"; + + static final int ITERATIONS = 10; + + public void testCreateNewEmptyDatabase() { + deleteDatabase(); + + Stopwatch stopwatch = new Stopwatch(); + + DatabaseSessionCache cache = new DatabaseSessionCache(getContext()); + cache.getSessionData("crazybob.org", 443); + + stopwatch.stop(); + } + + public void testCreateNewEmptyDirectory() throws IOException { + deleteDirectory(); + + Stopwatch stopwatch = new Stopwatch(); + + SSLClientSessionCache cache = FileClientSessionCache.usingDirectory( + getCacheDirectory()); + cache.getSessionData("crazybob.org", 443); + + stopwatch.stop(); + } + + public void testOpenDatabaseWith10Sessions() { + deleteDatabase(); + + DatabaseSessionCache cache = new DatabaseSessionCache(getContext()); + putSessionsIn(cache); + closeDatabase(); + + System.err.println("Size of ssl_sessions.db w/ 10 sessions: " + + new File(dbDir, "ssl_sessions.db").length()); + + Stopwatch stopwatch = new Stopwatch(); + + cache = new DatabaseSessionCache(getContext()); + cache.getSessionData("crazybob.org", 443); + + stopwatch.stop(); + } + + public void testOpenDirectoryWith10Sessions() throws IOException { + deleteDirectory(); + + SSLClientSessionCache cache = FileClientSessionCache.usingDirectory( + getCacheDirectory()); + putSessionsIn(cache); + closeDirectoryCache(); + + Stopwatch stopwatch = new Stopwatch(); + + cache = FileClientSessionCache.usingDirectory( + getCacheDirectory()); + cache.getSessionData("crazybob.org", 443); + + stopwatch.stop(); + } + + public void testGetSessionFromDatabase() { + deleteDatabase(); + + DatabaseSessionCache cache = new DatabaseSessionCache(getContext()); + cache.putSessionData(new FakeSession("foo"), SESSION_DATA); + closeDatabase(); + + cache = new DatabaseSessionCache(getContext()); + cache.getSessionData("crazybob.org", 443); + + Stopwatch stopwatch = new Stopwatch(); + + byte[] sessionData = cache.getSessionData("foo", 443); + + stopwatch.stop(); + + assertTrue(Arrays.equals(SESSION_DATA, sessionData)); + } + + public void testGetSessionFromDirectory() throws IOException { + deleteDirectory(); + + SSLClientSessionCache cache = FileClientSessionCache.usingDirectory( + getCacheDirectory()); + cache.putSessionData(new FakeSession("foo"), SESSION_DATA); + closeDirectoryCache(); + + cache = FileClientSessionCache.usingDirectory( + getCacheDirectory()); + cache.getSessionData("crazybob.org", 443); + + Stopwatch stopwatch = new Stopwatch(); + + byte[] sessionData = cache.getSessionData("foo", 443); + + stopwatch.stop(); + + assertTrue(Arrays.equals(SESSION_DATA, sessionData)); + } + + public void testPutSessionIntoDatabase() { + deleteDatabase(); + + DatabaseSessionCache cache = new DatabaseSessionCache(getContext()); + cache.getSessionData("crazybob.org", 443); + + Stopwatch stopwatch = new Stopwatch(); + + cache.putSessionData(new FakeSession("foo"), SESSION_DATA); + + stopwatch.stop(); + } + + public void testPutSessionIntoDirectory() throws IOException { + deleteDirectory(); + + SSLClientSessionCache cache = FileClientSessionCache.usingDirectory( + getCacheDirectory()); + cache.getSessionData("crazybob.org", 443); + + Stopwatch stopwatch = new Stopwatch(); + + cache.putSessionData(new FakeSession("foo"), SESSION_DATA); + + stopwatch.stop(); + } + + public void testEngineInit() throws IOException, KeyManagementException { + Stopwatch stopwatch = new Stopwatch(); + + new SSLContextImpl().engineInit(null, null, null); + + stopwatch.stop(); + } + + public void testWebRequestWithoutCache() throws IOException, + KeyManagementException { + SSLContextImpl sslContext = new SSLContextImpl(); + sslContext.engineInit(null, null, null); + + Stopwatch stopwatch = new Stopwatch(); + + getVerisignDotCom(sslContext); + + stopwatch.stop(); + } + + public void testWebRequestWithFileCache() throws IOException, + KeyManagementException { + deleteDirectory(); + + SSLContextImpl sslContext = new SSLContextImpl(); + sslContext.engineInit(null, null, null, + FileClientSessionCache.usingDirectory(getCacheDirectory()), + null); + + // Make sure www.google.com is in the cache. + getVerisignDotCom(sslContext); + + // Re-initialize so we hit the file cache. + sslContext.engineInit(null, null, null, + FileClientSessionCache.usingDirectory(getCacheDirectory()), + null); + + Stopwatch stopwatch = new Stopwatch(); + + getVerisignDotCom(sslContext); + + stopwatch.stop(); + } + + public void testWebRequestWithInMemoryCache() throws IOException, + KeyManagementException { + deleteDirectory(); + + SSLContextImpl sslContext = new SSLContextImpl(); + sslContext.engineInit(null, null, null); + + // Make sure www.google.com is in the cache. + getVerisignDotCom(sslContext); + + Stopwatch stopwatch = new Stopwatch(); + + getVerisignDotCom(sslContext); + + stopwatch.stop(); + } + + private void getVerisignDotCom(SSLContextImpl sslContext) + throws IOException { + SchemeRegistry schemeRegistry = new SchemeRegistry(); + schemeRegistry.register(new Scheme("https", + new SSLSocketFactory(sslContext.engineGetSocketFactory()), + 443)); + + ClientConnectionManager manager = + new SingleClientConnManager(null, schemeRegistry); + + new DefaultHttpClient(manager, null).execute( + new HttpGet("https://www.verisign.com"), + new ResponseHandler() { + public Object handleResponse(HttpResponse response) + throws ClientProtocolException, IOException { + return null; + } + }); + } + + private void putSessionsIn(SSLClientSessionCache cache) { + for (int i = 0; i < 10; i++) { + cache.putSessionData(new FakeSession("host" + i), SESSION_DATA); + } + } + + private void deleteDatabase() { + closeDatabase(); + if (!new File(dbDir, "ssl_sessions.db").delete()) { + System.err.println("Failed to delete database."); + } + } + + private void closeDatabase() { + if (DatabaseSessionCache.sDefaultDatabaseHelper != null) { + DatabaseSessionCache.sDefaultDatabaseHelper.close(); + } + DatabaseSessionCache.sDefaultDatabaseHelper = null; + DatabaseSessionCache.sHookInitializationDone = false; + DatabaseSessionCache.mNeedsCacheLoad = true; + } + + private void deleteDirectory() { + closeDirectoryCache(); + + File dir = getCacheDirectory(); + if (!dir.exists()) { + return; + } + for (File file : dir.listFiles()) { + file.delete(); + } + if (!dir.delete()) { + System.err.println("Failed to delete directory."); + } + } + + private void closeDirectoryCache() { + try { + Method reset = FileClientSessionCache.class + .getDeclaredMethod("reset"); + reset.setAccessible(true); + reset.invoke(null); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private File getCacheDirectory() { + return new File(getContext().getFilesDir(), CACHE_DIR); + } + + class Stopwatch { + { + Debug.startAllocCounting(); + } + long start = System.nanoTime(); + + void stop() { + long elapsed = (System.nanoTime() - start) / 1000; + Debug.stopAllocCounting(); + System.err.println(getName() + ": " + elapsed + "us, " + + Debug.getThreadAllocCount() + " allocations, " + + Debug.getThreadAllocSize() + " bytes"); + } + } +} + +class FakeSession implements SSLSession { + final String host; + + FakeSession(String host) { + this.host = host; + } + + public int getApplicationBufferSize() { + throw new UnsupportedOperationException(); + } + + public String getCipherSuite() { + throw new UnsupportedOperationException(); + } + + public long getCreationTime() { + throw new UnsupportedOperationException(); + } + + public byte[] getId() { + return host.getBytes(); + } + + public long getLastAccessedTime() { + throw new UnsupportedOperationException(); + } + + public Certificate[] getLocalCertificates() { + throw new UnsupportedOperationException(); + } + + public Principal getLocalPrincipal() { + throw new UnsupportedOperationException(); + } + + public int getPacketBufferSize() { + throw new UnsupportedOperationException(); + } + + public javax.security.cert.X509Certificate[] getPeerCertificateChain() { + throw new UnsupportedOperationException(); + } + + public Certificate[] getPeerCertificates() { + throw new UnsupportedOperationException(); + } + + public String getPeerHost() { + return host; + } + + public int getPeerPort() { + return 443; + } + + public Principal getPeerPrincipal() { + throw new UnsupportedOperationException(); + } + + public String getProtocol() { + throw new UnsupportedOperationException(); + } + + public SSLSessionContext getSessionContext() { + throw new UnsupportedOperationException(); + } + + public Object getValue(String name) { + throw new UnsupportedOperationException(); + } + + public String[] getValueNames() { + throw new UnsupportedOperationException(); + } + + public void invalidate() { + throw new UnsupportedOperationException(); + } + + public boolean isValid() { + throw new UnsupportedOperationException(); + } + + public void putValue(String name, Object value) { + throw new UnsupportedOperationException(); + } + + public void removeValue(String name) { + throw new UnsupportedOperationException(); + } +} diff --git a/tests/CoreTests/android/core/SSLSocketTest.java b/tests/CoreTests/android/core/SSLSocketTest.java index 922090af19a791409462b701c99322ad311c4b93..088fa8c7a9a1a0bda547a89bd22d0811d6aab857 100644 --- a/tests/CoreTests/android/core/SSLSocketTest.java +++ b/tests/CoreTests/android/core/SSLSocketTest.java @@ -19,9 +19,13 @@ package android.core; import junit.framework.TestCase; import org.apache.commons.codec.binary.Base64; +import org.apache.harmony.xnet.provider.jsse.SSLContextImpl; +import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; +import org.apache.harmony.xnet.provider.jsse.FileClientSessionCache; import java.io.ByteArrayInputStream; import java.io.DataInputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -29,18 +33,28 @@ import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.security.KeyStore; +import java.security.KeyManagementException; import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Random; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +/** + * SSL integration tests that hit real servers. + */ public class SSLSocketTest extends TestCase { private static SSLSocketFactory clientFactory = @@ -61,13 +75,15 @@ public class SSLSocketTest extends TestCase { * @param delay The delay after each request (in seconds). * @throws IOException When a problem occurs. */ - private void fetch(String host, int port, boolean secure, String path, - int outerLoop, int innerLoop, int delay, int timeout) throws IOException { + private void fetch(SSLSocketFactory socketFactory, String host, int port, + boolean secure, String path, int outerLoop, int innerLoop, + int delay, int timeout) throws IOException { InetSocketAddress address = new InetSocketAddress(host, port); for (int i = 0; i < outerLoop; i++) { // Connect to the remote host - Socket socket = secure ? clientFactory.createSocket() : new Socket(); + Socket socket = secure ? socketFactory.createSocket() + : new Socket(); if (timeout >= 0) { socket.setKeepAlive(true); socket.setSoTimeout(timeout * 1000); @@ -158,6 +174,16 @@ public class SSLSocketTest extends TestCase { } } + /** + * Invokes fetch() with the default socket factory. + */ + private void fetch(String host, int port, boolean secure, String path, + int outerLoop, int innerLoop, + int delay, int timeout) throws IOException { + fetch(clientFactory, host, port, secure, path, outerLoop, innerLoop, + delay, timeout); + } + /** * Does a single request for each of the hosts. Consumes the response. * @@ -619,13 +645,17 @@ public class SSLSocketTest extends TestCase { public void run() { try { - KeyManager[] keyManagers = provideKeys ? getKeyManagers(SERVER_KEYS_BKS) : null; - TrustManager[] trustManagers = new TrustManager[] { trustManager }; + KeyManager[] keyManagers = provideKeys + ? getKeyManagers(SERVER_KEYS_BKS) : null; + TrustManager[] trustManagers = new TrustManager[] { + trustManager }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); - SSLServerSocket serverSocket = (SSLServerSocket)sslContext.getServerSocketFactory().createServerSocket(); + SSLServerSocket serverSocket + = (SSLServerSocket) sslContext.getServerSocketFactory() + .createServerSocket(); if (clientAuth == CLIENT_AUTH_WANTED) { serverSocket.setWantClientAuth(true); @@ -637,14 +667,15 @@ public class SSLSocketTest extends TestCase { serverSocket.bind(new InetSocketAddress(port)); - SSLSocket clientSocket = (SSLSocket)serverSocket.accept(); + SSLSocket clientSocket = (SSLSocket) serverSocket.accept(); InputStream stream = clientSocket.getInputStream(); for (int i = 0; i < 256; i++) { int j = stream.read(); if (i != j) { - throw new RuntimeException("Error reading socket, expected " + i + ", got " + j); + throw new RuntimeException("Error reading socket," + + " expected " + i + ", got " + j); } } @@ -690,13 +721,16 @@ public class SSLSocketTest extends TestCase { public void run() { try { - KeyManager[] keyManagers = provideKeys ? getKeyManagers(CLIENT_KEYS_BKS) : null; - TrustManager[] trustManagers = new TrustManager[] { trustManager }; + KeyManager[] keyManagers = provideKeys + ? getKeyManagers(CLIENT_KEYS_BKS) : null; + TrustManager[] trustManagers = new TrustManager[] { + trustManager }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); - SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket(); + SSLSocket socket = (SSLSocket) sslContext.getSocketFactory() + .createSocket(); socket.connect(new InetSocketAddress(port)); socket.startHandshake(); @@ -867,6 +901,189 @@ public class SSLSocketTest extends TestCase { fail("SSL handshake should have failed."); } } - - + + /** + * Tests our in-memory and persistent caching support. + */ + public void testClientSessionCaching() throws IOException, + KeyManagementException { + SSLContextImpl context = new SSLContextImpl(); + + // Cache size = 2. + FakeClientSessionCache fakeCache = new FakeClientSessionCache(); + context.engineInit(null, null, null, fakeCache, null); + SSLSocketFactory socketFactory = context.engineGetSocketFactory(); + context.engineGetClientSessionContext().setSessionCacheSize(2); + makeRequests(socketFactory); + List smallCacheOps = Arrays.asList( + "get www.fortify.net", + "put www.fortify.net", + "get www.paypal.com", + "put www.paypal.com", + "get www.yellownet.ch", + "put www.yellownet.ch", + + // At this point, all in-memory cache requests should miss, + // but the sessions will still be in the persistent cache. + "get www.fortify.net", + "get www.paypal.com", + "get www.yellownet.ch" + ); + assertEquals(smallCacheOps, fakeCache.ops); + + // Cache size = 3. + fakeCache = new FakeClientSessionCache(); + context.engineInit(null, null, null, fakeCache, null); + socketFactory = context.engineGetSocketFactory(); + context.engineGetClientSessionContext().setSessionCacheSize(3); + makeRequests(socketFactory); + List bigCacheOps = Arrays.asList( + "get www.fortify.net", + "put www.fortify.net", + "get www.paypal.com", + "put www.paypal.com", + "get www.yellownet.ch", + "put www.yellownet.ch" + + // At this point, all results should be in the in-memory + // cache, and the persistent cache shouldn't be hit anymore. + ); + assertEquals(bigCacheOps, fakeCache.ops); + + // Cache size = 4. + fakeCache = new FakeClientSessionCache(); + context.engineInit(null, null, null, fakeCache, null); + socketFactory = context.engineGetSocketFactory(); + context.engineGetClientSessionContext().setSessionCacheSize(4); + makeRequests(socketFactory); + assertEquals(bigCacheOps, fakeCache.ops); + } + + /** + * Executes sequence of requests twice using given socket factory. + */ + private void makeRequests(SSLSocketFactory socketFactory) + throws IOException { + for (int i = 0; i < 2; i++) { + fetch(socketFactory, "www.fortify.net", 443, true, "/sslcheck.html", + 1, 1, 0, 60); + fetch(socketFactory, "www.paypal.com", 443, true, "/", + 1, 1, 0, 60); + fetch(socketFactory, "www.yellownet.ch", 443, true, "/", + 1, 1, 0, 60); + } + } + + /** + * Fake in the sense that it doesn't actually persist anything. + */ + static class FakeClientSessionCache implements SSLClientSessionCache { + + List ops = new ArrayList(); + Map sessions = new HashMap(); + + public byte[] getSessionData(String host, int port) { + ops.add("get " + host); + return sessions.get(host); + } + + public void putSessionData(SSLSession session, byte[] sessionData) { + String host = session.getPeerHost(); + System.err.println("length: " + sessionData.length); + ops.add("put " + host); + sessions.put(host, sessionData); + } + } + + public void testFileBasedClientSessionCache() throws IOException, + KeyManagementException { + SSLContextImpl context = new SSLContextImpl(); + String tmpDir = System.getProperty("java.io.tmpdir"); + if (tmpDir == null) { + fail("Please set 'java.io.tmpdir' system property."); + } + File cacheDir = new File(tmpDir + + "/" + SSLSocketTest.class.getName() + "/cache"); + deleteDir(cacheDir); + SSLClientSessionCache fileCache + = FileClientSessionCache.usingDirectory(cacheDir); + try { + ClientSessionCacheProxy cacheProxy + = new ClientSessionCacheProxy(fileCache); + context.engineInit(null, null, null, cacheProxy, null); + SSLSocketFactory socketFactory = context.engineGetSocketFactory(); + context.engineGetClientSessionContext().setSessionCacheSize(1); + makeRequests(socketFactory); + List expected = Arrays.asList( + "unsuccessful get www.fortify.net", + "put www.fortify.net", + "unsuccessful get www.paypal.com", + "put www.paypal.com", + "unsuccessful get www.yellownet.ch", + "put www.yellownet.ch", + + // At this point, all in-memory cache requests should miss, + // but the sessions will still be in the persistent cache. + "successful get www.fortify.net", + "successful get www.paypal.com", + "successful get www.yellownet.ch" + ); + assertEquals(expected, cacheProxy.ops); + + // Try again now that file-based cache is populated. + fileCache = FileClientSessionCache.usingDirectory(cacheDir); + cacheProxy = new ClientSessionCacheProxy(fileCache); + context.engineInit(null, null, null, cacheProxy, null); + socketFactory = context.engineGetSocketFactory(); + context.engineGetClientSessionContext().setSessionCacheSize(1); + makeRequests(socketFactory); + expected = Arrays.asList( + "successful get www.fortify.net", + "successful get www.paypal.com", + "successful get www.yellownet.ch", + "successful get www.fortify.net", + "successful get www.paypal.com", + "successful get www.yellownet.ch" + ); + assertEquals(expected, cacheProxy.ops); + } finally { + deleteDir(cacheDir); + } + } + + private static void deleteDir(File directory) { + if (!directory.exists()) { + return; + } + for (File file : directory.listFiles()) { + file.delete(); + } + directory.delete(); + } + + static class ClientSessionCacheProxy implements SSLClientSessionCache { + + final SSLClientSessionCache delegate; + final List ops = new ArrayList(); + + ClientSessionCacheProxy(SSLClientSessionCache delegate) { + this.delegate = delegate; + } + + public byte[] getSessionData(String host, int port) { + byte[] sessionData = delegate.getSessionData(host, port); + ops.add((sessionData == null ? "unsuccessful" : "successful") + + " get " + host); + return sessionData; + } + + public void putSessionData(SSLSession session, byte[] sessionData) { + delegate.putSessionData(session, sessionData); + ops.add("put " + session.getPeerHost()); + } + } + + public static void main(String[] args) throws KeyManagementException, IOException { + new SSLSocketTest().testFileBasedClientSessionCache(); + } } diff --git a/tests/CoreTests/android/core/TestHandler.java b/tests/CoreTests/android/core/TestHandler.java deleted file mode 100644 index 4ff2e6e4d8b6ee4746f3b9e246c47ad3db65851f..0000000000000000000000000000000000000000 --- a/tests/CoreTests/android/core/TestHandler.java +++ /dev/null @@ -1,174 +0,0 @@ -/* //device/java/android/com/android/tests/TestHandler.java -** -** Copyright 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. -*/ - -package android.core; - -import com.android.internal.os.HandlerHelper; -import android.os.HandlerInterface; -import android.os.Looper; -import android.os.Message; -import android.os.SystemClock; - -/** - * Naive class that implements a getNextMessage() - * by running a Handler in a new thread.

            - *

            - * This class blocks the Handler thread when the getNextMessage() thread - * is not in getNextMessage(). This allows the getNextMessage() thread to - * inspect state that is otherwise unguarded and would otherwise be prone to - * race conditions.

            - *

            - * Please note that both threads are allowed to run unsynchronized until - * the first message is posted to this handler. - *

            - * Please call hh.looper.quit() when done to clean this up - */ -public class TestHandler implements Runnable, HandlerInterface { - //***** Instance Variables - - public HandlerHelper hh; - public Looper looper; - - Runnable setupRoutine; - Message nextMessage; - long failTimeoutMillis; - boolean waitBeforeReturning = true; - - //***** Class Methods - - public static TestHandler create() { - return create("TestHandler", null); - } - - public static TestHandler create(String name) { - return create(name, null); - } - - public static TestHandler create(String name, Runnable doSetup) { - TestHandler ret; - - ret = new TestHandler(); - - ret.setupRoutine = doSetup; - - synchronized (ret) { - new Thread(ret, name).start(); - while (ret.looper == null) { - try { - ret.wait(); - } catch (InterruptedException ex) { - } - } - } - - return ret; - } - - //***** Public Methods - - /** - * Maximum time to wait for a message before failing - * by throwing exception - */ - public void setFailTimeoutMillis(long msec) { - failTimeoutMillis = msec; - } - - /** - * Waits for the next message to be sent to this handler and returns it. - * Blocks the Handler's looper thread until another call to getNextMessage() - * is made - */ - - public Message getNextMessage() { - Message ret; - - synchronized (this) { - long time = SystemClock.uptimeMillis(); - - waitBeforeReturning = false; - this.notifyAll(); - - try { - while (nextMessage == null) { - if (failTimeoutMillis > 0 - && ((SystemClock.uptimeMillis() - time) - > failTimeoutMillis)) { - throw new RuntimeException("Timeout exceeded exceeded"); - } - - try { - this.wait(failTimeoutMillis); - } catch (InterruptedException ex) { - } - } - ret = nextMessage; - nextMessage = null; - } finally { - waitBeforeReturning = true; - } - } - - return ret; - } - - //***** Overridden from Runnable - - public void run() { - Looper.prepare(); - hh = new HandlerHelper(this); - - if (setupRoutine != null) { - setupRoutine.run(); - } - - synchronized (this) { - looper = Looper.myLooper(); - this.notify(); - } - - Looper.loop(); - } - - //***** HandlerHelper implementation - - public void handleMessage(Message msg) { - synchronized (this) { - while (nextMessage != null) { - try { - this.wait(); - } catch (InterruptedException ex) { - } - } - - // msg will be recycled when this method returns. - // so we need to make a copy of it. - nextMessage = Message.obtain(); - nextMessage.copyFrom(msg); - this.notifyAll(); - - while (waitBeforeReturning) { - try { - this.wait(); - } catch (InterruptedException ex) { - } - } - } - } -} - - diff --git a/tests/CoreTests/android/location/LocationManagerProximityTest.java b/tests/CoreTests/android/location/LocationManagerProximityTest.java index 5f629833f73ed03713116d80e419231e0f8eb2e4..e1501e34e528dc1cc3b12d7af27d23be8eb712c4 100644 --- a/tests/CoreTests/android/location/LocationManagerProximityTest.java +++ b/tests/CoreTests/android/location/LocationManagerProximityTest.java @@ -23,6 +23,7 @@ import android.content.IntentFilter; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; +import android.provider.Settings; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.util.Log; @@ -33,8 +34,10 @@ import android.util.Log; * TODO: add tests for more scenarios * * To run: - * adb shell am instrument -e class com.google.android.mapstests.api.LocationProximityTest \ - * -w com.google.android.mapstests/.MapInstrumentationTestRunner + * adb shell am instrument -e class android.location.LocationManagerProximityTest \ + * -w android.core/android.test.InstrumentationTestRunner + * + * This test requires that the "Allow mock locations" setting be enabled * */ @MediumTest @@ -46,8 +49,6 @@ public class LocationManagerProximityTest extends AndroidTestCase { private LocationManager mLocationManager; private PendingIntent mPendingIntent; private TestIntentReceiver mIntentReceiver; - private String mOriginalAllowedProviders; - private int mOriginalMocksAllowed; private static final String LOG_TAG = "LocationProximityTest"; @@ -60,27 +61,13 @@ public class LocationManagerProximityTest extends AndroidTestCase { @Override protected void setUp() throws Exception { super.setUp(); - - // allow mock locations - mOriginalMocksAllowed = - android.provider.Settings.Secure.getInt(getContext().getContentResolver(), - android.provider.Settings.Secure.ALLOW_MOCK_LOCATION, 0); - - android.provider.Settings.Secure.putInt(getContext().getContentResolver(), - android.provider.Settings.Secure.ALLOW_MOCK_LOCATION, 1); - - mOriginalAllowedProviders = - android.provider.Settings.Secure.getString( - getContext().getContentResolver(), - android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED); - - // ensure 'only' the mock provider is enabled - // need to do this so the proximity listener does not ignore the mock - // updates in favor of gps updates - android.provider.Settings.Secure.putString( - getContext().getContentResolver(), - android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED, - PROVIDER_NAME); + + // test that mock locations are allowed so a more descriptive error message can be logged + if (Settings.Secure.getInt(getContext().getContentResolver(), + Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 0) { + fail("Mock locations are currently disabled in Settings - this test requires " + + "mock locations"); + } mLocationManager = (LocationManager) getContext(). getSystemService(Context.LOCATION_SERVICE); @@ -109,18 +96,6 @@ public class LocationManagerProximityTest extends AndroidTestCase { if (mIntentReceiver != null) { getContext().unregisterReceiver(mIntentReceiver); } - - android.provider.Settings.Secure.putInt(getContext().getContentResolver(), - android.provider.Settings.Secure.ALLOW_MOCK_LOCATION, mOriginalMocksAllowed); - - if (mOriginalAllowedProviders != null) { - // restore original settings - android.provider.Settings.Secure.putString( - getContext().getContentResolver(), - android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED, - mOriginalAllowedProviders); - mLocationManager.updateProviders(); - } } /** diff --git a/tests/CoreTests/android/test/InstrumentationTestRunnerTest.java b/tests/CoreTests/android/test/InstrumentationTestRunnerTest.java index 359c902762e6492866d897da4cb8c7f6ace49e4f..d9afd545f822bcdcd8c5df2e14c97bb3c415dd88 100644 --- a/tests/CoreTests/android/test/InstrumentationTestRunnerTest.java +++ b/tests/CoreTests/android/test/InstrumentationTestRunnerTest.java @@ -89,6 +89,26 @@ public class InstrumentationTestRunnerTest extends TestCase { } + public void testDelayParameter() throws Exception { + int delayMsec = 1000; + Bundle args = new Bundle(); + args.putInt(InstrumentationTestRunner.ARGUMENT_DELAY_MSEC, delayMsec); + args.putString(InstrumentationTestRunner.ARGUMENT_TEST_CLASS, + PlaceHolderTest.class.getName() + "," + + PlaceHolderTest2.class.getName()); + mInstrumentationTestRunner.onCreate(args); + Thread t = new Thread() { public void run() { mInstrumentationTestRunner.onStart(); } }; + + // Should delay three times: before, between, and after the two tests. + long beforeTest = System.currentTimeMillis(); + t.start(); + t.join(); + assertTrue(System.currentTimeMillis() > beforeTest + delayMsec * 3); + assertTrue(mInstrumentationTestRunner.isStarted()); + assertTrue(mInstrumentationTestRunner.isFinished()); + assertTrue(mStubAndroidTestRunner.isRun()); + } + private void assertContentsInOrder(List actual, TestDescriptor... source) { TestDescriptor[] clonedSource = source.clone(); assertEquals("Unexpected number of items.", clonedSource.length, actual.size()); @@ -217,6 +237,7 @@ public class InstrumentationTestRunnerTest extends TestCase { } public void runTest() { + super.runTest(); mRun = true; } } diff --git a/tests/CoreTests/android/webkit/CookieTest.java b/tests/CoreTests/android/webkit/CookieTest.java index 1c3d671993bddfc990bb53b4c451e20dc47c0b90..ea4422f8869832187d5f40eab0c1de3968ea2a14 100644 --- a/tests/CoreTests/android/webkit/CookieTest.java +++ b/tests/CoreTests/android/webkit/CookieTest.java @@ -55,6 +55,11 @@ public class CookieTest extends AndroidTestCase { mCookieManager.setCookie(url, "c=\"d;\""); cookie = mCookieManager.getCookie(url); assertTrue(cookie.equals("a=b; c=\"d;\"")); + + // empty + mCookieManager.setCookie(url, "; path=/"); + cookie = mCookieManager.getCookie(url); + assertTrue(cookie.equals("a=b; c=\"d;\"")); } public void testDomain() { diff --git a/tests/CoreTests/android/webkit/UrlInterceptRegistryTest.java b/tests/CoreTests/android/webkit/UrlInterceptRegistryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7504449939939206d45b3a9942709fe87a02d237 --- /dev/null +++ b/tests/CoreTests/android/webkit/UrlInterceptRegistryTest.java @@ -0,0 +1,88 @@ +/* + * 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. + */ + +package android.webkit; + +import android.test.AndroidTestCase; +import android.util.Log; +import android.webkit.CacheManager.CacheResult; +import android.webkit.PluginData; +import android.webkit.UrlInterceptHandler; + +import java.util.LinkedList; +import java.util.Map; + +public class UrlInterceptRegistryTest extends AndroidTestCase { + + /** + * To run these tests: $ mmm + * frameworks/base/tests/CoreTests/android && adb remount && adb + * sync $ adb shell am instrument -w -e class \ + * android.webkit.UrlInterceptRegistryTest \ + * android.core/android.test.InstrumentationTestRunner + */ + + private static class MockUrlInterceptHandler implements UrlInterceptHandler { + private PluginData mData; + private String mUrl; + + public MockUrlInterceptHandler(PluginData data, String url) { + mData = data; + mUrl = url; + } + + public CacheResult service(String url, Map headers) { + return null; + } + + public PluginData getPluginData(String url, + Map headers) { + if (mUrl.equals(url)) { + return mData; + } + + return null; + } + } + + public void testGetPluginData() { + PluginData data = new PluginData(null, 0 , null, 200); + String url = new String("url1"); + MockUrlInterceptHandler handler1 = + new MockUrlInterceptHandler(data, url); + + data = new PluginData(null, 0 , null, 404); + url = new String("url2"); + MockUrlInterceptHandler handler2 = + new MockUrlInterceptHandler(data, url); + + assertTrue(UrlInterceptRegistry.registerHandler(handler1)); + assertTrue(UrlInterceptRegistry.registerHandler(handler2)); + + data = UrlInterceptRegistry.getPluginData("url1", null); + assertTrue(data != null); + assertTrue(data.getStatusCode() == 200); + + data = UrlInterceptRegistry.getPluginData("url2", null); + assertTrue(data != null); + assertTrue(data.getStatusCode() == 404); + + assertTrue(UrlInterceptRegistry.unregisterHandler(handler1)); + assertTrue(UrlInterceptRegistry.unregisterHandler(handler2)); + + } +} diff --git a/tests/CoreTests/com/android/internal/telephony/gsm/GSMPhoneTest.java b/tests/CoreTests/com/android/internal/telephony/gsm/GSMPhoneTest.java index ec9b3ef90d76a076f9ca63f83ddeade5167ccad3..710741297613a139258e4b4de7bc4cc877475b08 100644 --- a/tests/CoreTests/com/android/internal/telephony/gsm/GSMPhoneTest.java +++ b/tests/CoreTests/com/android/internal/telephony/gsm/GSMPhoneTest.java @@ -9,19 +9,23 @@ * * 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. + * WITHOUT WARRANTIES OR CONDITIONS OF GSMTestHandler.ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony.gsm; -import android.core.TestHandler; import android.os.AsyncResult; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Looper; import android.os.Message; +import android.os.Process; import android.telephony.ServiceState; import android.test.AndroidTestCase; import android.test.PerformanceTestCase; +import android.util.Log; import com.android.internal.telephony.Call; import com.android.internal.telephony.CallStateException; @@ -29,15 +33,22 @@ import com.android.internal.telephony.Connection; import com.android.internal.telephony.MmiCode; import com.android.internal.telephony.Phone; import com.android.internal.telephony.TestPhoneNotifier; +import com.android.internal.telephony.gsm.CallFailCause; +import com.android.internal.telephony.gsm.GSMPhone; +import com.android.internal.telephony.gsm.GSMTestHandler; +import com.android.internal.telephony.gsm.GsmMmiCode; +import com.android.internal.telephony.gsm.SuppServiceNotification; import com.android.internal.telephony.test.SimulatedCommands; import com.android.internal.telephony.test.SimulatedRadioControl; import java.util.List; + public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase { private SimulatedRadioControl mRadioControl; - private TestHandler mTestHandler; private GSMPhone mGSMPhone; + private GSMTestHandler mGSMTestHandler; + private Handler mHandler; private static final int EVENT_PHONE_STATE_CHANGED = 1; private static final int EVENT_DISCONNECT = 2; @@ -51,78 +62,65 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase private static final int EVENT_IN_SERVICE = 10; private static final int SUPP_SERVICE_FAILED = 11; private static final int SERVICE_STATE_CHANGED = 12; - - private static final int FAIL_TIMEOUT_MILLIS = 5 * 1000; + private static final int EVENT_OEM_RIL_MESSAGE = 13; + public static final int ANY_MESSAGE = -1; @Override protected void setUp() throws Exception { super.setUp(); + mGSMTestHandler = new GSMTestHandler(mContext); + + mGSMTestHandler.start(); + synchronized (mGSMTestHandler) { + do { + mGSMTestHandler.wait(); + } while (mGSMTestHandler.getGSMPhone() == null); + } + + mGSMPhone = mGSMTestHandler.getGSMPhone(); + mRadioControl = mGSMTestHandler.getSimulatedCommands(); + + mHandler = mGSMTestHandler.getHandler(); + mGSMPhone.registerForPhoneStateChanged(mHandler, EVENT_PHONE_STATE_CHANGED, null); + mGSMPhone.registerForNewRingingConnection(mHandler, EVENT_RINGING, null); + mGSMPhone.registerForDisconnect(mHandler, EVENT_DISCONNECT, null); + + mGSMPhone.setOnPostDialCharacter(mHandler, EVENT_POST_DIAL, null); - mTestHandler = TestHandler.create("GSMPhoneTest TestHandler", - new Runnable() { - public void run() { - SimulatedCommands sc = new SimulatedCommands(); - mRadioControl = sc; - mGSMPhone = new GSMPhone( - mContext, sc, - new TestPhoneNotifier(), - true); - - } - } - ); - - mTestHandler.setFailTimeoutMillis(FAIL_TIMEOUT_MILLIS); - mGSMPhone.registerForPhoneStateChanged(mTestHandler.hh, EVENT_PHONE_STATE_CHANGED, null); - mGSMPhone.registerForNewRingingConnection(mTestHandler.hh, EVENT_RINGING, null); - mGSMPhone.registerForDisconnect(mTestHandler.hh, EVENT_DISCONNECT, null); - - mGSMPhone.setOnPostDialCharacter(mTestHandler.hh, EVENT_POST_DIAL, null); - - mGSMPhone.registerForSuppServiceNotification(mTestHandler.hh, EVENT_SSN, null); - mGSMPhone.registerForMmiInitiate(mTestHandler.hh, EVENT_MMI_INITIATE, null); - mGSMPhone.registerForMmiComplete(mTestHandler.hh, EVENT_MMI_COMPLETE, null); - mGSMPhone.registerForSuppServiceFailed(mTestHandler.hh, SUPP_SERVICE_FAILED, null); - - mGSMPhone.registerForServiceStateChanged(mTestHandler.hh, SERVICE_STATE_CHANGED, null); + mGSMPhone.registerForSuppServiceNotification(mHandler, EVENT_SSN, null); + mGSMPhone.registerForMmiInitiate(mHandler, EVENT_MMI_INITIATE, null); + mGSMPhone.registerForMmiComplete(mHandler, EVENT_MMI_COMPLETE, null); + mGSMPhone.registerForSuppServiceFailed(mHandler, SUPP_SERVICE_FAILED, null); + + mGSMPhone.registerForServiceStateChanged(mHandler, SERVICE_STATE_CHANGED, null); // wait until we get phone in both voice and data service Message msg; ServiceState state; + do { - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != SERVICE_STATE_CHANGED); - state = (ServiceState) ((AsyncResult) msg.obj).result; + msg = mGSMTestHandler.waitForMessage(SERVICE_STATE_CHANGED); + assertNotNull("Message Time Out", msg); + state = (ServiceState) ((AsyncResult) msg.obj).result; } while (state.getState() != ServiceState.STATE_IN_SERVICE); - } @Override protected void tearDown() throws Exception { - mGSMPhone.unregisterForPhoneStateChanged(mTestHandler.hh); - mGSMPhone.unregisterForNewRingingConnection(mTestHandler.hh); - mGSMPhone.unregisterForDisconnect(mTestHandler.hh); - mGSMPhone.setOnPostDialCharacter(null, 0, null); - mGSMPhone.unregisterForSuppServiceNotification(mTestHandler.hh); - mGSMPhone.unregisterForMmiInitiate(mTestHandler.hh); - mGSMPhone.unregisterForMmiComplete(mTestHandler.hh); - mRadioControl.shutdown(); - mTestHandler.hh.sendMessage(mTestHandler.hh.obtainMessage(EVENT_DONE)); - - Message msg; - - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DONE); - - mTestHandler.looper.quit(); + mGSMPhone.unregisterForPhoneStateChanged(mHandler); + mGSMPhone.unregisterForNewRingingConnection(mHandler); + mGSMPhone.unregisterForDisconnect(mHandler); + mGSMPhone.setOnPostDialCharacter(mHandler, 0, null); + mGSMPhone.unregisterForSuppServiceNotification(mHandler); + mGSMPhone.unregisterForMmiInitiate(mHandler); + mGSMPhone.unregisterForMmiComplete(mHandler); mGSMPhone = null; mRadioControl = null; - mTestHandler = null; + mHandler = null; + mGSMTestHandler.cleanup(); super.tearDown(); } @@ -136,7 +134,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase return false; } - + //This test is causing the emulator screen to turn off. I don't understand //why, but I'm removing it until we can figure it out. public void brokenTestGeneral() throws Exception { @@ -167,19 +165,16 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_PHONE_STATE_CHANGED); + msg = mGSMTestHandler.waitForMessage(EVENT_PHONE_STATE_CHANGED); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); assertEquals(Call.State.DIALING, mGSMPhone.getForegroundCall().getState()); assertTrue(mGSMPhone.getForegroundCall().isDialingOrAlerting()); - /* - do { - th.getNextMessage(); - } while (phone.getForegroundCall().getConnections().size() == 0); - */ + /*do { + mGSMTestHandler.waitForMessage(ANY_MESSAGE); + } while (mGSMPhone.getForegroundCall().getConnections().size() == 0);*/ assertEquals(0, mGSMPhone.getRingingCall().getConnections().size()); assertEquals(1, mGSMPhone.getForegroundCall().getConnections().size()); @@ -206,7 +201,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.progressConnectingCallState(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ALERTING); @@ -234,7 +229,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.progressConnectingCallState(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); @@ -259,9 +254,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // One disconnected connection mGSMPhone.getForegroundCall().hangup(); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); + msg = mGSMTestHandler.waitForMessage(EVENT_DISCONNECT); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -311,9 +305,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_RINGING); + msg = mGSMTestHandler.waitForMessage(EVENT_RINGING); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); assertTrue(mGSMPhone.getRingingCall().isRinging()); @@ -347,7 +340,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.acceptCall(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getRingingCall().getConnections().size() == 1); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); @@ -382,10 +375,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase fail("unexpected ex"); } - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); - + msg = mGSMTestHandler.waitForMessage(EVENT_DISCONNECT); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -444,7 +435,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getRingingCall().getConnections().isEmpty()); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); @@ -471,7 +462,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.rejectCall(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.IDLE); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -525,7 +516,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getRingingCall().getConnections().isEmpty()); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); @@ -539,7 +530,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerHangupForeground(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.IDLE); assertEquals(Connection.DisconnectCause.INCOMING_MISSED, cn.getDisconnectCause()); @@ -549,7 +540,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.RINGING); @@ -559,7 +550,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.acceptCall(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.OFFHOOK); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -569,7 +560,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.switchHoldingAndActive(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() == Call.State.IDLE); @@ -580,7 +571,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.switchHoldingAndActive(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() == Call.State.HOLDING); @@ -592,7 +583,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerHangupAll(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.IDLE); assertEquals(Call.State.DISCONNECTED, mGSMPhone.getForegroundCall().getState()); @@ -603,13 +594,13 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.RINGING); mGSMPhone.rejectCall(); do { - msg = mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (msg.what != EVENT_DISCONNECT); ar = (AsyncResult) msg.obj; @@ -624,7 +615,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.RINGING); cn = mGSMPhone.getRingingCall().getEarliestConnection(); @@ -632,7 +623,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.acceptCall(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.OFFHOOK); assertEquals(Connection.DisconnectCause.NOT_DISCONNECTED, cn.getDisconnectCause()); @@ -647,7 +638,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase } do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.DISCONNECTED); @@ -661,7 +652,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.dial("+13125551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.OFFHOOK); assertTrue(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -672,7 +663,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // One ACTIVE call do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -682,7 +673,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.RINGING); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -692,7 +683,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.acceptCall(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.OFFHOOK); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -706,7 +697,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.conference(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() != Call.State.IDLE); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -720,7 +711,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.switchHoldingAndActive(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() != Call.State.HOLDING); @@ -734,7 +725,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005558355"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.RINGING); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -750,7 +741,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.getBackgroundCall().hangup(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() != Call.State.DISCONNECTED); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); @@ -763,7 +754,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.rejectCall(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.IDLE); assertFalse(mGSMPhone.getForegroundCall().isDialingOrAlerting()); @@ -782,10 +773,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase Connection cn = mGSMPhone.dial("+13125551212"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); - + msg = mGSMTestHandler.waitForMessage(EVENT_DISCONNECT); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); assertEquals(Connection.DisconnectCause.NORMAL, cn.getDisconnectCause()); @@ -812,7 +801,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.dial("+13125551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.DIALING); @@ -820,10 +809,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.getForegroundCall().hangup(); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); - + msg = mGSMTestHandler.waitForMessage(EVENT_DISCONNECT); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); assertEquals(Call.State.DISCONNECTED, mGSMPhone.getForegroundCall().getState()); @@ -833,13 +820,13 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.dial("+13125551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.OFFHOOK); mRadioControl.progressConnectingCallState(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ALERTING); @@ -847,9 +834,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.getForegroundCall().hangup(); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); + msg = mGSMTestHandler.waitForMessage(EVENT_DISCONNECT); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); @@ -867,10 +853,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.resumeResponses(); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); - + msg = mGSMTestHandler.waitForMessage(EVENT_DISCONNECT); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); assertEquals(Call.State.DISCONNECTED, mGSMPhone.getForegroundCall().getState()); @@ -883,13 +867,13 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.dial("+13125551212"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getConnections().isEmpty()); mRadioControl.shutdown(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); mGSMPhone.clearDisconnected(); } while (!mGSMPhone.getForegroundCall().getConnections().isEmpty()); } @@ -902,7 +886,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase do { mRadioControl.progressConnectingCallState(); - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -912,9 +896,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_RINGING); + msg = mGSMTestHandler.waitForMessage(EVENT_RINGING); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); assertTrue(mGSMPhone.getRingingCall().isRinging()); @@ -927,7 +910,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("0"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getRingingCall().getState() == Call.State.WAITING); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); @@ -940,7 +923,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.switchHoldingAndActive(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() == Call.State.IDLE); @@ -952,7 +935,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("0"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() == Call.State.HOLDING); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); @@ -968,7 +951,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase do { mRadioControl.progressConnectingCallState(); - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -979,7 +962,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); do { - msg = mTestHandler.getNextMessage(); + msg = mGSMTestHandler.waitForMessage(ANY_MESSAGE); + assertNotNull("Message Time Out", msg); } while (msg.what != EVENT_RINGING); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); @@ -994,7 +978,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("1"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getRingingCall().getState() == Call.State.WAITING); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); @@ -1008,7 +992,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.switchHoldingAndActive(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() == Call.State.IDLE); assertEquals(Call.State.IDLE, mGSMPhone.getForegroundCall().getState()); @@ -1019,7 +1003,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("1"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() != Call.State.IDLE); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); @@ -1033,9 +1017,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("16505550100"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_RINGING); + msg = mGSMTestHandler.waitForMessage(EVENT_RINGING); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); assertTrue(mGSMPhone.getRingingCall().isRinging()); @@ -1048,7 +1031,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("12"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() == Call.State.ACTIVE); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); @@ -1060,7 +1043,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.acceptCall(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getState() != Phone.State.OFFHOOK); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); @@ -1075,7 +1058,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase do { mRadioControl.progressConnectingCallState(); - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE || mGSMPhone.getBackgroundCall().getState() != Call.State.HOLDING); @@ -1086,20 +1069,20 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // have the gsm index of 2 // Simulate entering "11" followed by SEND: release the call with - // gsm index equals to 1. This should not be allowed, and a + // gsm index equals to 1. This should not be allowed, and a // Supplementary Service notification must be received. mGSMPhone.handleInCallMmiCommands("11"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg != null && msg.what != SUPP_SERVICE_FAILED); + + msg = mGSMTestHandler.waitForMessage(SUPP_SERVICE_FAILED); + assertNotNull("Message Time Out", msg); assertFalse("IncallMmiCallWaiting: command should not work on holding call", msg == null); - + // Simulate entering "12" followed by SEND: release the call with // gsm index equals to 2. mGSMPhone.handleInCallMmiCommands("12"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() == Call.State.ACTIVE); assertEquals(Call.State.DISCONNECTED, mGSMPhone.getForegroundCall().getState()); @@ -1108,9 +1091,9 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Simulate entering 1 followed by SEND: release all active calls // (if any exist) and accepts the other (held or waiting) call. mGSMPhone.handleInCallMmiCommands("1"); - + do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() != Call.State.IDLE); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); @@ -1124,7 +1107,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("11"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() == Call.State.ACTIVE); assertEquals(Call.State.DISCONNECTED, mGSMPhone.getForegroundCall().getState()); @@ -1139,7 +1122,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase do { mRadioControl.progressConnectingCallState(); - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1149,9 +1132,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerRing("18005551212"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_RINGING); + msg = mGSMTestHandler.waitForMessage(EVENT_RINGING); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); assertTrue(mGSMPhone.getRingingCall().isRinging()); @@ -1166,7 +1148,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("2"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getRingingCall().getState() == Call.State.WAITING); @@ -1184,9 +1166,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // swap the active and holding calls mGSMPhone.handleInCallMmiCommands("2"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_PHONE_STATE_CHANGED); + msg = mGSMTestHandler.waitForMessage(EVENT_PHONE_STATE_CHANGED); + assertNotNull("Message Time Out", msg); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); assertEquals("13125551212", @@ -1199,7 +1180,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.conference(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() != Call.State.IDLE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1212,20 +1193,19 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Simulate entering "23" followed by SEND: places all active call // on hold except call 3. This should fail and a supplementary service // failed notification should be received. - + mGSMPhone.handleInCallMmiCommands("23"); - - do { - msg = mTestHandler.getNextMessage(); - } while (msg != null && msg.what != SUPP_SERVICE_FAILED); + + msg = mGSMTestHandler.waitForMessage(SUPP_SERVICE_FAILED); + assertNotNull("Message Time Out", msg); assertFalse("IncallMmiCallHold: separate should have failed!", msg == null); - + // Simulate entering "21" followed by SEND: places all active call // on hold except call 1. mGSMPhone.handleInCallMmiCommands("21"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() == Call.State.IDLE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1242,7 +1222,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase do { mRadioControl.progressConnectingCallState(); - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1253,7 +1233,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase do { mRadioControl.progressConnectingCallState(); - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1262,7 +1242,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("3"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() != Call.State.IDLE); assertEquals(Phone.State.OFFHOOK, mGSMPhone.getState()); @@ -1282,7 +1262,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase do { mRadioControl.progressConnectingCallState(); - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1297,7 +1277,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase do { mRadioControl.progressConnectingCallState(); - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1310,7 +1290,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.conference(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getBackgroundCall().getState() != Call.State.IDLE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1326,9 +1306,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // of 7 mRadioControl.triggerRing("18005551212"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_RINGING); + msg = mGSMTestHandler.waitForMessage(EVENT_RINGING); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.RINGING, mGSMPhone.getState()); assertTrue(mGSMPhone.getRingingCall().isRinging()); @@ -1341,7 +1320,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.acceptCall(); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getRingingCall().getState() != Call.State.IDLE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1354,7 +1333,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("17"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() == Call.State.ACTIVE); assertEquals(Call.State.DISCONNECTED, mGSMPhone.getForegroundCall().getState()); @@ -1366,7 +1345,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("1"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() != Call.State.ACTIVE); assertEquals(Call.State.ACTIVE, mGSMPhone.getForegroundCall().getState()); @@ -1375,7 +1354,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.handleInCallMmiCommands("16"); do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (mGSMPhone.getForegroundCall().getState() == Call.State.ACTIVE); assertEquals(Call.State.DISCONNECTED, mGSMPhone.getForegroundCall().getState()); @@ -1389,53 +1368,44 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.dial("+13125551212,1234;5N8xx"); - do { - msg = mTestHandler.getNextMessage(); - mRadioControl.progressConnectingToActive(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) (msg.obj); cn = (Connection) (ar.result); assertEquals(',', msg.arg1); assertEquals("1234;5N8", cn.getRemainingPostDialString()); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals('1', msg.arg1); ar = (AsyncResult) (msg.obj); assertEquals(Connection.PostDialState.STARTED, ar.userObj); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals('2', msg.arg1); ar = (AsyncResult) (msg.obj); assertEquals(Connection.PostDialState.STARTED, ar.userObj); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals('3', msg.arg1); ar = (AsyncResult) (msg.obj); assertEquals(Connection.PostDialState.STARTED, ar.userObj); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals('4', msg.arg1); ar = (AsyncResult) (msg.obj); assertEquals(Connection.PostDialState.STARTED, ar.userObj); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals(';', msg.arg1); ar = (AsyncResult) (msg.obj); cn = (Connection) (ar.result); @@ -1443,18 +1413,15 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase assertEquals(Connection.PostDialState.WAIT, ar.userObj); cn.proceedAfterWaitChar(); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals('5', msg.arg1); ar = (AsyncResult) (msg.obj); assertEquals(Connection.PostDialState.STARTED, ar.userObj); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); assertEquals('N', msg.arg1); ar = (AsyncResult) (msg.obj); cn = (Connection) (ar.result); @@ -1462,27 +1429,22 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase assertEquals(Connection.PostDialState.WILD, ar.userObj); cn.proceedAfterWildChar(",6;7"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) (msg.obj); cn = (Connection) (ar.result); assertEquals(',', msg.arg1); assertEquals("6;78", cn.getRemainingPostDialString()); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals('6', msg.arg1); ar = (AsyncResult) (msg.obj); assertEquals(Connection.PostDialState.STARTED, ar.userObj); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals(';', msg.arg1); ar = (AsyncResult) (msg.obj); cn = (Connection) (ar.result); @@ -1490,28 +1452,21 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase assertEquals(Connection.PostDialState.WAIT, ar.userObj); cn.proceedAfterWaitChar(); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals('7', msg.arg1); ar = (AsyncResult) (msg.obj); assertEquals(Connection.PostDialState.STARTED, ar.userObj); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals('8', msg.arg1); ar = (AsyncResult) (msg.obj); assertEquals(Connection.PostDialState.STARTED, ar.userObj); // Bogus chars at end should be ignored - - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals(0, msg.arg1); ar = (AsyncResult) (msg.obj); cn = (Connection) (ar.result); @@ -1530,16 +1485,11 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.progressConnectingToActive(); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); + assertNotNull("Message Time Out", msg); assertEquals(',', msg.arg1); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_POST_DIAL); - + msg = mGSMTestHandler.waitForMessage(EVENT_POST_DIAL); assertEquals('N', msg.arg1); ar = (AsyncResult) (msg.obj); cn = (Connection) (ar.result); @@ -1567,16 +1517,13 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Normally these failure conditions would happen in DIALING // not ALERTING do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (cn.getState() == Call.State.DIALING); mRadioControl.triggerHangupAll(); - - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); - + msg = mGSMTestHandler.waitForMessage(EVENT_DISCONNECT); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); assertEquals(Connection.DisconnectCause.NORMAL, cn.getDisconnectCause()); @@ -1608,16 +1555,13 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Normally these failure conditions would happen in DIALING // not ALERTING do { - mTestHandler.getNextMessage(); + assertNotNull("Message Time Out", mGSMTestHandler.waitForMessage(ANY_MESSAGE)); } while (cn.getState() == Call.State.DIALING); mRadioControl.triggerHangupAll(); - - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); - + msg = mGSMTestHandler.waitForMessage(EVENT_DISCONNECT); + assertNotNull("Message Time Out", msg); assertEquals(Phone.State.IDLE, mGSMPhone.getState()); assertEquals(Connection.DisconnectCause.BUSY, cn.getDisconnectCause()); @@ -1650,7 +1594,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Normally these failure conditions would happen in DIALING // not ALERTING do { - mTestHandler.getNextMessage(); + msg = mGSMTestHandler.waitForMessage(ANY_MESSAGE); + assertNotNull("Message Time Out", msg); } while (cn.getState() == Call.State.DIALING); @@ -1659,7 +1604,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Unlike the while loops above, this one waits // for a "phone state changed" message back to "idle" do { - msg = mTestHandler.getNextMessage(); + msg = mGSMTestHandler.waitForMessage(ANY_MESSAGE); + assertNotNull("Message Time Out", msg); } while (!(msg.what == EVENT_PHONE_STATE_CHANGED && mGSMPhone.getState() == Phone.State.IDLE)); @@ -1696,10 +1642,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mRadioControl.triggerSsn(type, code); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_SSN); - + msg = mGSMTestHandler.waitForMessage(EVENT_SSN); + assertNotNull("Message Time Out", msg); AsyncResult ar = (AsyncResult) msg.obj; assertNull(ar.exception); @@ -1714,7 +1658,7 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase public void testUssd() throws Exception { // Quick hack to work around a race condition in this test: // We may initiate a USSD MMI before GSMPhone receives its initial - // EVENT_RADIO_OFF_OR_NOT_AVAILABLE event. When the phone sees this + // GSMTestHandler.EVENT_RADIO_OFF_OR_NOT_AVAILABLE event. When the phone sees this // event, it will cancel the just issued USSD MMI, which we don't // want. So sleep a little first. try { @@ -1735,10 +1679,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Receive an incoming NOTIFY mRadioControl.triggerIncomingUssd("0", "NOTIFY message"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_COMPLETE); - + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_COMPLETE); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) msg.obj; mmi = (MmiCode) ar.result; @@ -1746,29 +1688,23 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Receive a REQUEST and send response mRadioControl.triggerIncomingUssd("1", "REQUEST Message"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_COMPLETE); + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_COMPLETE); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) msg.obj; mmi = (MmiCode) ar.result; assertTrue(mmi.isUssdRequest()); mGSMPhone.sendUssdResponse("## TEST: TEST_GSMPhone responding..."); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_INITIATE); - + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_INITIATE); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) msg.obj; mmi = (MmiCode) ar.result; GsmMmiCode gsmMmi = (GsmMmiCode) mmi; assertTrue(gsmMmi.isPendingUSSD()); - - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_COMPLETE); - + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_COMPLETE); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) msg.obj; mmi = (MmiCode) ar.result; @@ -1777,19 +1713,16 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // Receive a REQUEST and cancel mRadioControl.triggerIncomingUssd("1", "REQUEST Message"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_COMPLETE); + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_COMPLETE); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) msg.obj; mmi = (MmiCode) ar.result; assertTrue(mmi.isUssdRequest()); mmi.cancel(); - - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_COMPLETE); + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_COMPLETE); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) msg.obj; mmi = (MmiCode) ar.result; @@ -1808,13 +1741,11 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase mGSMPhone.dial("#646#"); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_INITIATE); + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_INITIATE); + assertNotNull("Message Time Out", msg); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_COMPLETE); + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_COMPLETE); + assertNotNull("Message Time Out", msg); ar = (AsyncResult) msg.obj; mmi = (MmiCode) ar.result; @@ -1842,13 +1773,11 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase assertTrue(mmi.isCancelable()); mmi.cancel(); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_INITIATE); + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_INITIATE); + assertNotNull("Message Time Out", msg); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_COMPLETE); + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_COMPLETE); + assertNotNull("Message Time Out", msg); AsyncResult ar = (AsyncResult) msg.obj; mmi = (MmiCode) ar.result; @@ -1867,11 +1796,10 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // null byte array - mGSMPhone.invokeOemRilRequestRaw(null, mTestHandler.hh.obtainMessage(999)); + mGSMPhone.invokeOemRilRequestRaw(null, mHandler.obtainMessage(EVENT_OEM_RIL_MESSAGE)); - do { - msg = mTestHandler.getNextMessage(); - } while (!(msg.what == 999)); + msg = mGSMTestHandler.waitForMessage(EVENT_OEM_RIL_MESSAGE); + assertNotNull("Message Time Out", msg); ar = ((AsyncResult) msg.obj); @@ -1880,11 +1808,10 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // empty byte array - mGSMPhone.invokeOemRilRequestRaw(new byte[0], mTestHandler.hh.obtainMessage(999)); + mGSMPhone.invokeOemRilRequestRaw(new byte[0], mHandler.obtainMessage(EVENT_OEM_RIL_MESSAGE)); - do { - msg = mTestHandler.getNextMessage(); - } while (!(msg.what == 999)); + msg = mGSMTestHandler.waitForMessage(EVENT_OEM_RIL_MESSAGE); + assertNotNull("Message Time Out", msg); ar = ((AsyncResult) msg.obj); @@ -1894,11 +1821,10 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // byte array with data mGSMPhone.invokeOemRilRequestRaw("Hello".getBytes("utf-8"), - mTestHandler.hh.obtainMessage(999)); + mHandler.obtainMessage(EVENT_OEM_RIL_MESSAGE)); - do { - msg = mTestHandler.getNextMessage(); - } while (!(msg.what == 999)); + msg = mGSMTestHandler.waitForMessage(EVENT_OEM_RIL_MESSAGE); + assertNotNull("Message Time Out", msg); ar = ((AsyncResult) msg.obj); @@ -1907,11 +1833,10 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // null strings - mGSMPhone.invokeOemRilRequestStrings(null, mTestHandler.hh.obtainMessage(999)); + mGSMPhone.invokeOemRilRequestStrings(null, mHandler.obtainMessage(EVENT_OEM_RIL_MESSAGE)); - do { - msg = mTestHandler.getNextMessage(); - } while (!(msg.what == 999)); + msg = mGSMTestHandler.waitForMessage(EVENT_OEM_RIL_MESSAGE); + assertNotNull("Message Time Out", msg); ar = ((AsyncResult) msg.obj); @@ -1921,11 +1846,10 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase // empty byte array mGSMPhone.invokeOemRilRequestStrings(new String[0], - mTestHandler.hh.obtainMessage(999)); + mHandler.obtainMessage(EVENT_OEM_RIL_MESSAGE)); - do { - msg = mTestHandler.getNextMessage(); - } while (!(msg.what == 999)); + msg = mGSMTestHandler.waitForMessage(EVENT_OEM_RIL_MESSAGE); + assertNotNull("Message Time Out", msg); ar = ((AsyncResult) msg.obj); @@ -1938,11 +1862,10 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase s[0] = "Hello"; - mGSMPhone.invokeOemRilRequestStrings(s, mTestHandler.hh.obtainMessage(999)); + mGSMPhone.invokeOemRilRequestStrings(s, mHandler.obtainMessage(EVENT_OEM_RIL_MESSAGE)); - do { - msg = mTestHandler.getNextMessage(); - } while (!(msg.what == 999)); + msg = mGSMTestHandler.waitForMessage(EVENT_OEM_RIL_MESSAGE); + assertNotNull("Message Time Out", msg); ar = ((AsyncResult) msg.obj); @@ -1976,21 +1899,15 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase private void runValidMmi(String dialString, boolean cancelable) throws CallStateException { Connection c = mGSMPhone.dial(dialString); assertNull(c); - - Message msg; - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_INITIATE); - + Message msg = mGSMTestHandler.waitForMessage(EVENT_MMI_INITIATE); + assertNotNull("Message Time Out", msg); // Should not be cancelable. AsyncResult ar = (AsyncResult) msg.obj; MmiCode mmi = (MmiCode) ar.result; assertEquals(cancelable, mmi.isCancelable()); - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_MMI_COMPLETE); - + msg = mGSMTestHandler.waitForMessage(EVENT_MMI_COMPLETE); + assertNotNull("Message Time Out", msg); } private void runValidMmiWithConnect(String dialString) throws CallStateException { @@ -2006,11 +1923,8 @@ public class GSMPhoneTest extends AndroidTestCase implements PerformanceTestCase cn.hangup(); mRadioControl.resumeResponses(); + assertNotNull(mGSMTestHandler.waitForMessage(EVENT_DISCONNECT)); - Message msg; - do { - msg = mTestHandler.getNextMessage(); - } while (msg.what != EVENT_DISCONNECT); } private void runNotMmi(String dialString) throws CallStateException { diff --git a/tests/CoreTests/com/android/internal/telephony/gsm/GSMTestHandler.java b/tests/CoreTests/com/android/internal/telephony/gsm/GSMTestHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..fb8a5d9eb936643bbb21df9263f1359e5b9346c4 --- /dev/null +++ b/tests/CoreTests/com/android/internal/telephony/gsm/GSMTestHandler.java @@ -0,0 +1,118 @@ +/* + * 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. + */ + +package com.android.internal.telephony.gsm; + +import android.content.Context; + +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Looper; +import android.os.Message; +import android.util.Log; + +import com.android.internal.telephony.gsm.GSMPhone; +import com.android.internal.telephony.test.SimulatedCommands; +import com.android.internal.telephony.TestPhoneNotifier; + +/** + * This class creates a HandlerThread which waits for the various messages. + */ +public class GSMTestHandler extends HandlerThread implements Handler.Callback { + + private Handler mHandler; + private Message mCurrentMessage; + + private Boolean mMsgConsumed; + private SimulatedCommands sc; + private GSMPhone mGSMPhone; + private Context mContext; + + private static final int FAIL_TIMEOUT_MILLIS = 5 * 1000; + + public GSMTestHandler(Context context) { + super("GSMPhoneTest"); + mMsgConsumed = false; + mContext = context; + } + + @Override + protected void onLooperPrepared() { + sc = new SimulatedCommands(); + mGSMPhone = new GSMPhone(mContext, sc, new TestPhoneNotifier(), true); + mHandler = new Handler(getLooper(), this); + synchronized (this) { + notifyAll(); + } + } + + public boolean handleMessage(Message msg) { + synchronized (this) { + mCurrentMessage = msg; + this.notifyAll(); + while(!mMsgConsumed) { + try { + this.wait(); + } catch (InterruptedException e) {} + } + mMsgConsumed = false; + } + return true; + } + + + public void cleanup() { + Looper looper = getLooper(); + if (looper != null) looper.quit(); + mHandler = null; + } + + public Handler getHandler() { + return mHandler; + } + + public SimulatedCommands getSimulatedCommands() { + return sc; + } + + public GSMPhone getGSMPhone() { + return mGSMPhone; + } + + public Message waitForMessage(int code) { + Message msg; + while(true) { + msg = null; + synchronized (this) { + try { + this.wait(FAIL_TIMEOUT_MILLIS); + } catch (InterruptedException e) { + } + + // Check if timeout has occurred. + if (mCurrentMessage != null) { + // Consume the message + msg = Message.obtain(); + msg.copyFrom(mCurrentMessage); + mCurrentMessage = null; + mMsgConsumed = true; + this.notifyAll(); + } + } + if (msg == null || code == GSMPhoneTest.ANY_MESSAGE || msg.what == code) return msg; + } + } +} diff --git a/tests/CoreTests/com/android/internal/telephony/gsm/SMSDispatcherTest.java b/tests/CoreTests/com/android/internal/telephony/gsm/SMSDispatcherTest.java index 84974ef4e2e5ee3c3790337c145dcd369ed7a8d2..6db230ffdc95cddd80d1f9076e9bd8f8d6bb0724 100644 --- a/tests/CoreTests/com/android/internal/telephony/gsm/SMSDispatcherTest.java +++ b/tests/CoreTests/com/android/internal/telephony/gsm/SMSDispatcherTest.java @@ -16,7 +16,6 @@ package com.android.internal.telephony.gsm; -import android.core.TestHandler; import android.test.suitebuilder.annotation.MediumTest; import com.android.internal.telephony.TestPhoneNotifier; import com.android.internal.telephony.test.SimulatedCommands; @@ -38,24 +37,24 @@ public class SMSDispatcherTest extends AndroidTestCase { Iterator elements; String[] lines = new String[2]; - - lines[0] = "+CMT: ,158"; + + lines[0] = "+CMT: ,158"; lines[1] = "07914140279510F6440A8111110301003BF56080426101748A8C0B05040B" + "8423F000035502010106276170706C69636174696F6E2F766E642E776170" + "2E6D6D732D6D65737361676500AF848D0185B4848C8298524F347839776F" + "7547514D4141424C3641414141536741415A4B554141414141008D908918" + "802B31363530323438363137392F545950453D504C4D4E008A808E028000" + "88058103093A8083687474703A2F2F36"; - + sms = SmsMessage.newFromCMT(lines); header = sms.getUserDataHeader(); assertNotNull(header); assertNotNull(sms.getUserData()); - + elements = header.getElements().iterator(); assertNotNull(elements); } - + @MediumTest public void testCMT2() throws Exception { SmsMessage sms; @@ -63,7 +62,7 @@ public class SMSDispatcherTest extends AndroidTestCase { Iterator elements; String[] lines = new String[2]; - + lines[0] = "+CMT: ,77"; lines[1] = "07914140279510F6440A8111110301003BF56080426101848A3B0B05040B8423F" @@ -75,7 +74,7 @@ public class SMSDispatcherTest extends AndroidTestCase { System.out.println("header = " + header); assertNotNull(header); assertNotNull(sms.getUserData()); - + elements = header.getElements().iterator(); assertNotNull(elements); } diff --git a/tests/CoreTests/com/android/internal/telephony/gsm/SimPhoneBookTest.java b/tests/CoreTests/com/android/internal/telephony/gsm/SimPhoneBookTest.java index 53fdd51ba6c265be7e19c7fb1c36bf2b29a2c111..db55bcae4f0eb15a954a57050037a44cfbd6589a 100644 --- a/tests/CoreTests/com/android/internal/telephony/gsm/SimPhoneBookTest.java +++ b/tests/CoreTests/com/android/internal/telephony/gsm/SimPhoneBookTest.java @@ -16,7 +16,6 @@ package com.android.internal.telephony.gsm; -import android.core.TestHandler; import android.os.ServiceManager; import android.test.suitebuilder.annotation.Suppress; @@ -48,21 +47,21 @@ public class SimPhoneBookTest extends TestCase { AdnRecord originalAdn = null; // We need to maintain the state of the SIM before and after the test. // Since this test doesn't mock the SIM we try to get a valid ADN record, - // for 3 tries and if this fails, we bail out. + // for 3 tries and if this fails, we bail out. for (adnIndex = 3 ; adnIndex >= 1; adnIndex--) { listIndex = adnIndex - 1; // listIndex is zero based. originalAdn = adnRecordList.get(listIndex); assertNotNull("Original Adn is Null.", originalAdn); assertNotNull("Original Adn alpha tag is null.", originalAdn.getAlphaTag()); assertNotNull("Original Adn number is null.", originalAdn.getNumber()); - - if (originalAdn.getNumber().length() > 0 && - originalAdn.getAlphaTag().length() > 0) { + + if (originalAdn.getNumber().length() > 0 && + originalAdn.getAlphaTag().length() > 0) { break; } } if (adnIndex == 0) return; - + AdnRecord emptyAdn = new AdnRecord("", ""); AdnRecord firstAdn = new AdnRecord("John", "4085550101"); AdnRecord secondAdn = new AdnRecord("Andy", "6505550102"); diff --git a/tests/CoreTests/run_core_test.sh b/tests/CoreTests/run_core_test.sh index 1fc33483b17f8a8811176ec6f60a57a545afab09..ffa31ed372bac9ea6429a4ec7c15ef2c09cac1a6 100755 --- a/tests/CoreTests/run_core_test.sh +++ b/tests/CoreTests/run_core_test.sh @@ -1,4 +1,6 @@ framework=/system/framework bpath=$framework/core.jar:$framework/ext.jar:$framework/framework.jar:$framework/android.test.runner.jar -adb shell exec dalvikvm -Xbootclasspath:$bpath -cp system/app/CoreTests.apk \ +adb shell exec dalvikvm -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=3001 \ + -Xbootclasspath:$bpath -cp /data/app/android.core.apk \ + -Djava.io.tmpdir=/sdcard/tmp \ com.android.internal.util.WithFramework junit.textui.TestRunner $* diff --git a/tests/DpiTest/Android.mk b/tests/DpiTest/Android.mk new file mode 100644 index 0000000000000000000000000000000000000000..3596c39a6b288fef054e4ea937f8d832d099227b --- /dev/null +++ b/tests/DpiTest/Android.mk @@ -0,0 +1,10 @@ +LOCAL_PATH:= $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := $(call all-subdir-java-files) + +LOCAL_PACKAGE_NAME := DensityTest + +LOCAL_MODULE_TAGS := tests + +include $(BUILD_PACKAGE) diff --git a/tests/DpiTest/AndroidManifest.xml b/tests/DpiTest/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..f71cff22811b0733775b397f0f6e7b651a400f76 --- /dev/null +++ b/tests/DpiTest/AndroidManifest.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + diff --git a/tests/DpiTest/res/drawable-120dpi/logo120dpi.png b/tests/DpiTest/res/drawable-120dpi/logo120dpi.png new file mode 100644 index 0000000000000000000000000000000000000000..46bbd5bd3d485ba132f14fd5b04a7c6b69004d0c Binary files /dev/null and b/tests/DpiTest/res/drawable-120dpi/logo120dpi.png differ diff --git a/tests/DpiTest/res/drawable-240dpi/logo240dpi.png b/tests/DpiTest/res/drawable-240dpi/logo240dpi.png new file mode 100644 index 0000000000000000000000000000000000000000..4d717a86143dd680bbdd9f6f54c6623d5a33b03b Binary files /dev/null and b/tests/DpiTest/res/drawable-240dpi/logo240dpi.png differ diff --git a/tests/DpiTest/res/drawable/logo160dpi.png b/tests/DpiTest/res/drawable/logo160dpi.png new file mode 100644 index 0000000000000000000000000000000000000000..c23b2ce83b43d984173a16be7fc25b46bf4fbd50 Binary files /dev/null and b/tests/DpiTest/res/drawable/logo160dpi.png differ diff --git a/tests/DpiTest/src/com/google/android/test/dpi/DpiTestActivity.java b/tests/DpiTest/src/com/google/android/test/dpi/DpiTestActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..3759622bbbec22d5c2bca5e404da48c1889953ea --- /dev/null +++ b/tests/DpiTest/src/com/google/android/test/dpi/DpiTestActivity.java @@ -0,0 +1,167 @@ +/* + * 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. + */ + +package com.google.android.test.dpi; + +import android.app.Activity; +import android.os.Bundle; +import android.graphics.BitmapFactory; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.ScrollView; +import android.view.View; +import android.content.Context; + +public class DpiTestActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + + LinearLayout layout = new LinearLayout(this); + addBitmapDrawable(layout, R.drawable.logo120dpi, true); + addBitmapDrawable(layout, R.drawable.logo160dpi, true); + addBitmapDrawable(layout, R.drawable.logo240dpi, true); + addLabelToRoot(root, "Prescaled bitmap in drawable"); + addChildToRoot(root, layout); + + layout = new LinearLayout(this); + addBitmapDrawable(layout, R.drawable.logo120dpi, false); + addBitmapDrawable(layout, R.drawable.logo160dpi, false); + addBitmapDrawable(layout, R.drawable.logo240dpi, false); + addLabelToRoot(root, "Autoscaled bitmap in drawable"); + addChildToRoot(root, layout); + + layout = new LinearLayout(this); + addResourceDrawable(layout, R.drawable.logo120dpi); + addResourceDrawable(layout, R.drawable.logo160dpi); + addResourceDrawable(layout, R.drawable.logo240dpi); + addLabelToRoot(root, "Prescaled resource drawable"); + addChildToRoot(root, layout); + + layout = new LinearLayout(this); + addCanvasBitmap(layout, R.drawable.logo120dpi, true); + addCanvasBitmap(layout, R.drawable.logo160dpi, true); + addCanvasBitmap(layout, R.drawable.logo240dpi, true); + addLabelToRoot(root, "Prescaled bitmap"); + addChildToRoot(root, layout); + + layout = new LinearLayout(this); + addCanvasBitmap(layout, R.drawable.logo120dpi, false); + addCanvasBitmap(layout, R.drawable.logo160dpi, false); + addCanvasBitmap(layout, R.drawable.logo240dpi, false); + addLabelToRoot(root, "Autoscaled bitmap"); + addChildToRoot(root, layout); + + setContentView(scrollWrap(root)); + } + + private View scrollWrap(View view) { + ScrollView scroller = new ScrollView(this); + scroller.addView(view, new ScrollView.LayoutParams(ScrollView.LayoutParams.FILL_PARENT, + ScrollView.LayoutParams.FILL_PARENT)); + return scroller; + } + + private void addLabelToRoot(LinearLayout root, String text) { + TextView label = new TextView(this); + label.setText(text); + root.addView(label, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT)); + } + + private void addChildToRoot(LinearLayout root, LinearLayout layout) { + root.addView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT)); + } + + private void addBitmapDrawable(LinearLayout layout, int resource, boolean scale) { + Bitmap bitmap; + bitmap = loadAndPrintDpi(resource, scale); + + View view = new View(this); + + final BitmapDrawable d = new BitmapDrawable(bitmap); + if (!scale) d.setDensityScale(getResources().getDisplayMetrics()); + view.setBackgroundDrawable(d); + + view.setLayoutParams(new LinearLayout.LayoutParams(d.getIntrinsicWidth(), + d.getIntrinsicHeight())); + layout.addView(view); + } + + private void addResourceDrawable(LinearLayout layout, int resource) { + View view = new View(this); + + final Drawable d = getResources().getDrawable(resource); + view.setBackgroundDrawable(d); + + view.setLayoutParams(new LinearLayout.LayoutParams(d.getIntrinsicWidth(), + d.getIntrinsicHeight())); + layout.addView(view); + } + + private void addCanvasBitmap(LinearLayout layout, int resource, boolean scale) { + Bitmap bitmap; + bitmap = loadAndPrintDpi(resource, scale); + + ScaledBitmapView view = new ScaledBitmapView(this, bitmap); + + view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT)); + layout.addView(view); + } + + private Bitmap loadAndPrintDpi(int id, boolean scale) { + Bitmap bitmap; + if (scale) { + bitmap = BitmapFactory.decodeResource(getResources(), id); + } else { + BitmapFactory.Options opts = new BitmapFactory.Options(); + opts.inScaled = false; + bitmap = BitmapFactory.decodeResource(getResources(), id, opts); + } + return bitmap; + } + + private class ScaledBitmapView extends View { + private Bitmap mBitmap; + + public ScaledBitmapView(Context context, Bitmap bitmap) { + super(context); + mBitmap = bitmap; + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + setMeasuredDimension(mBitmap.getScaledWidth(), mBitmap.getScaledHeight()); + } + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + + canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null); + } + } +} diff --git a/tests/DumpRenderTree/AndroidManifest.xml b/tests/DumpRenderTree/AndroidManifest.xml index 8e06cc83228e2f98e442c5ef6231a9bcd1665dc5..17c44adb9e3b87e40bbb6c16d30d9022d34f5a78 100644 --- a/tests/DumpRenderTree/AndroidManifest.xml +++ b/tests/DumpRenderTree/AndroidManifest.xml @@ -23,7 +23,7 @@ - + diff --git a/tests/DumpRenderTree/results/layout_tests_crashed.txt b/tests/DumpRenderTree/results/layout_tests_crashed.txt new file mode 100644 index 0000000000000000000000000000000000000000..5a38ed85f71db73d632d6807711c67bf033d4730 --- /dev/null +++ b/tests/DumpRenderTree/results/layout_tests_crashed.txt @@ -0,0 +1 @@ +/sdcard/android/layout_tests/fast/js/regexp-charclass-crash.html \ No newline at end of file diff --git a/tests/DumpRenderTree/results/layout_tests_failed.txt b/tests/DumpRenderTree/results/layout_tests_failed.txt new file mode 100644 index 0000000000000000000000000000000000000000..3cec40d20111019e865424b5c2563d821eb2110d --- /dev/null +++ b/tests/DumpRenderTree/results/layout_tests_failed.txt @@ -0,0 +1,280 @@ +/sdcard/android/layout_tests/fast/replaced/image-map-bug16782.html : different length +/sdcard/android/layout_tests/fast/replaced/table-percent-height.html : different length +/sdcard/android/layout_tests/fast/replaced/image-map.html : different length +/sdcard/android/layout_tests/fast/dynamic/paused-event-dispatch.html : @offset: 117 +/sdcard/android/layout_tests/fast/text/plain-text-line-breaks.html : different length +/sdcard/android/layout_tests/fast/text/zero-width-characters.html : different length +/sdcard/android/layout_tests/fast/text/reset-drag-on-mouse-down.html : TIMEDOUT +/sdcard/android/layout_tests/fast/encoding/invalid-xml.html : different length +/sdcard/android/layout_tests/fast/encoding/char-decoding-mac.html : different length +/sdcard/android/layout_tests/fast/encoding/frame-default-enc.html : @offset: 0 +/sdcard/android/layout_tests/fast/encoding/mailto-always-utf-8.html : different length +/sdcard/android/layout_tests/fast/encoding/char-decoding.html : different length +/sdcard/android/layout_tests/fast/encoding/url-host-name-non-ascii.html : different length +/sdcard/android/layout_tests/fast/encoding/idn-security.html : different length +/sdcard/android/layout_tests/fast/encoding/percent-escaping.html : TIMEDOUT +/sdcard/android/layout_tests/fast/encoding/xml-utf-8-default.xml : different length +/sdcard/android/layout_tests/fast/encoding/char-encoding-mac.html : different length +/sdcard/android/layout_tests/fast/encoding/charset-koi8-u.html : @offset: 147 +/sdcard/android/layout_tests/fast/encoding/preload-encoding.html : different length +/sdcard/android/layout_tests/fast/workers/worker-location.html : TIMEDOUT +/sdcard/android/layout_tests/fast/workers/worker-constructor.html : different length +/sdcard/android/layout_tests/fast/workers/worker-terminate.html : different length +/sdcard/android/layout_tests/fast/workers/worker-gc.html : different length +/sdcard/android/layout_tests/fast/workers/worker-navigator.html : different length +/sdcard/android/layout_tests/fast/workers/worker-replace-global-constructor.html : TIMEDOUT +/sdcard/android/layout_tests/fast/workers/worker-replace-self.html : TIMEDOUT +/sdcard/android/layout_tests/fast/workers/worker-event-listener.html : TIMEDOUT +/sdcard/android/layout_tests/fast/overflow/scroll-vertical-not-horizontal.html : different length +/sdcard/android/layout_tests/fast/events/onunload.html : different length +/sdcard/android/layout_tests/fast/events/mouseup-outside-document.html : different length +/sdcard/android/layout_tests/fast/events/offsetX-offsetY.html : different length +/sdcard/android/layout_tests/fast/events/scroll-event-does-not-bubble.html : different length +/sdcard/android/layout_tests/fast/events/mouseover-mouseout.html : different length +/sdcard/android/layout_tests/fast/events/option-tab.html : different length +/sdcard/android/layout_tests/fast/events/popup-blocking-click-in-iframe.html : different length +/sdcard/android/layout_tests/fast/events/onchange-passwordfield.html : different length +/sdcard/android/layout_tests/fast/events/drag-in-frames.html : different length +/sdcard/android/layout_tests/fast/events/frame-tab-focus.html : different length +/sdcard/android/layout_tests/fast/events/autoscroll-in-textfield.html : different length +/sdcard/android/layout_tests/fast/events/arrow-navigation.html : different length +/sdcard/android/layout_tests/fast/events/fire-scroll-event.html : different length +/sdcard/android/layout_tests/fast/events/mouseclick-target-and-positioning.html : different length +/sdcard/android/layout_tests/fast/events/keydown-keypress-focus-change.html : @offset: 172 +/sdcard/android/layout_tests/fast/events/input-image-scrolled-x-y.html : TIMEDOUT +/sdcard/android/layout_tests/fast/events/dblclick-addEventListener.html : different length +/sdcard/android/layout_tests/fast/events/frame-programmatic-focus.html : different length +/sdcard/android/layout_tests/fast/events/related-target.html : different length +/sdcard/android/layout_tests/fast/events/content-changed-during-drop.html : different length +/sdcard/android/layout_tests/fast/events/onload-fires-twice.html : different length +/sdcard/android/layout_tests/fast/events/autoscroll-with-non-scrollable-parent.html : different length +/sdcard/android/layout_tests/fast/events/window-events-capture.html : different length +/sdcard/android/layout_tests/fast/events/onchange-click-hang.html : TIMEDOUT +/sdcard/android/layout_tests/fast/events/onload-webkit-before-webcore.html : @offset: 105 +/sdcard/android/layout_tests/fast/events/window-events-bubble2.html : different length +/sdcard/android/layout_tests/fast/events/js-keyboard-event-creation.html : different length +/sdcard/android/layout_tests/fast/events/event-view-toString.html : TIMEDOUT +/sdcard/android/layout_tests/fast/events/onchange-select-popup.html : different length +/sdcard/android/layout_tests/fast/events/access-key-self-destruct.html : different length +/sdcard/android/layout_tests/fast/events/scrollbar-double-click.html : different length +/sdcard/android/layout_tests/fast/events/onunload-clears-onbeforeunload.html : different length +/sdcard/android/layout_tests/fast/events/tabindex-focus-chain.html : @offset: 0 +/sdcard/android/layout_tests/fast/events/capture-on-target.html : different length +/sdcard/android/layout_tests/fast/events/window-events-bubble.html : different length +/sdcard/android/layout_tests/fast/events/mouseup-from-button2.html : different length +/sdcard/android/layout_tests/fast/events/frame-click-focus.html : different length +/sdcard/android/layout_tests/fast/events/mouseout-on-window.html : different length +/sdcard/android/layout_tests/fast/events/keypress-insert-tab.html : @offset: 85 +/sdcard/android/layout_tests/fast/events/mouseout-dead-subframe.html : TIMEDOUT +/sdcard/android/layout_tests/fast/events/iframe-object-onload.html : different length +/sdcard/android/layout_tests/fast/events/onunload-not-on-body.html : different length +/sdcard/android/layout_tests/fast/events/mousemove-after-drag-over-scrollbar.html : different length +/sdcard/android/layout_tests/fast/events/contextmenu-scrolled-page-with-frame.html : different length +/sdcard/android/layout_tests/fast/events/key-events-in-input-button.html : different length +/sdcard/android/layout_tests/fast/events/arrow-keys-on-body.html : different length +/sdcard/android/layout_tests/fast/events/ondragenter.html : different length +/sdcard/android/layout_tests/fast/events/scroll-to-anchor-in-overflow-hidden.html : different length +/sdcard/android/layout_tests/fast/events/autoscroll-nonscrollable-iframe-in-scrollable-div.html : different length +/sdcard/android/layout_tests/fast/events/keypress-focus-change.html : different length +/sdcard/android/layout_tests/fast/events/key-events-in-input-text.html : different length +/sdcard/android/layout_tests/fast/events/drag-outside-window.html : @offset: 20 +/sdcard/android/layout_tests/fast/events/selectstart-during-autoscroll.html : different length +/sdcard/android/layout_tests/fast/events/click-count.html : different length +/sdcard/android/layout_tests/fast/events/onchange-searchfield.html : different length +/sdcard/android/layout_tests/fast/events/special-key-events-in-input-text.html : different length +/sdcard/android/layout_tests/fast/events/keydown-keypress-preventDefault.html : @offset: 228 +/sdcard/android/layout_tests/fast/events/mouse-click-events.html : different length +/sdcard/android/layout_tests/fast/events/onsearch-enter.html : different length +/sdcard/android/layout_tests/fast/events/mouseover-mouseout2.html : different length +/sdcard/android/layout_tests/fast/events/open-window-from-another-frame.html : different length +/sdcard/android/layout_tests/fast/events/init-events.html : different length +/sdcard/android/layout_tests/fast/events/onchange-textfield.html : different length +/sdcard/android/layout_tests/fast/events/onclick-list-marker.html : different length +/sdcard/android/layout_tests/fast/events/anchor-image-scrolled-x-y.html : TIMEDOUT +/sdcard/android/layout_tests/fast/html/tab-order.html : @offset: 246 +/sdcard/android/layout_tests/fast/js/exception-sequencing-binops.html : TIMEDOUT +/sdcard/android/layout_tests/fast/js/recursion-limit-equal.html : different length +/sdcard/android/layout_tests/fast/js/exception-sequencing-binops2.html : TIMEDOUT +/sdcard/android/layout_tests/fast/js/math-transforms.html : TIMEDOUT +/sdcard/android/layout_tests/fast/js/try-catch-crash.html : TIMEDOUT +/sdcard/android/layout_tests/fast/js/navigator-mimeTypes-length.html : different length +/sdcard/android/layout_tests/fast/js/global-constructors.html : different length +/sdcard/android/layout_tests/fast/js/uncaught-exception-line-number.html : different length +/sdcard/android/layout_tests/fast/js/exceptions-thrown-in-callbacks.html : TIMEDOUT +/sdcard/android/layout_tests/fast/js/toString-and-valueOf-override.html : TIMEDOUT +/sdcard/android/layout_tests/fast/js/exception-sequencing.html : TIMEDOUT +/sdcard/android/layout_tests/fast/js/exception-codegen-crash.html : different length +/sdcard/android/layout_tests/fast/dom/HTMLDocument/activeElement.html : different length +/sdcard/android/layout_tests/fast/dom/HTMLDocument/hasFocus.html : different length +/sdcard/android/layout_tests/fast/dom/HTMLSelectElement/listbox-select-reset.html : different length +/sdcard/android/layout_tests/fast/dom/Element/offsetLeft-offsetTop-body-quirk.html : different length +/sdcard/android/layout_tests/fast/dom/DOMException/XPathException.html : different length +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/010.xml : different length +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/011.xml : different length +/sdcard/android/layout_tests/fast/dom/Window/window-resize-and-move-arguments.html : different length +/sdcard/android/layout_tests/fast/dom/Window/window-function-name-getter-precedence.html : different length +/sdcard/android/layout_tests/fast/dom/Window/window-xy-properties.html : different length +/sdcard/android/layout_tests/fast/dom/Window/console-functions.html : different length +/sdcard/android/layout_tests/fast/dom/Window/window-screen-properties.html : @offset: 65 +/sdcard/android/layout_tests/fast/dom/Window/window-properties.html : TIMEDOUT +/sdcard/android/layout_tests/fast/dom/Window/window-onFocus.html : different length +/sdcard/android/layout_tests/fast/dom/Window/new-window-opener.html : TIMEDOUT +/sdcard/android/layout_tests/fast/dom/Window/window-open-pending-url.html : different length +/sdcard/android/layout_tests/fast/dom/Window/setting-properties-on-closed-window.html : TIMEDOUT +/sdcard/android/layout_tests/fast/dom/Window/dom-access-from-closure-window.html : different length +/sdcard/android/layout_tests/fast/dom/Window/window-resize.html : different length +/sdcard/android/layout_tests/fast/dom/Window/window-custom-prototype.html : different length +/sdcard/android/layout_tests/fast/dom/Window/dom-access-from-closure-iframe.html : different length +/sdcard/android/layout_tests/fast/dom/Window/Plug-ins.html : different length +/sdcard/android/layout_tests/fast/dom/Window/get-set-properties.html : different length +/sdcard/android/layout_tests/fast/dom/Window/window-scroll-arguments.html : different length +/sdcard/android/layout_tests/fast/dom/Window/window-early-properties.html : different length +/sdcard/android/layout_tests/fast/dom/StyleSheet/ownerNode-lifetime-2.html : different length +/sdcard/android/layout_tests/fast/dom/dom-constructors.html : different length +/sdcard/android/layout_tests/fast/dom/assign-to-window-status.html : different length +/sdcard/android/layout_tests/fast/dom/gc-8.html : different length +/sdcard/android/layout_tests/fast/dom/object-embed-plugin-scripting.html : different length +/sdcard/android/layout_tests/fast/dom/gc-9.html : different length +/sdcard/android/layout_tests/fast/dom/NamedNodeMap-setNamedItem-crash.html : different length +/sdcard/android/layout_tests/fast/dom/wrapper-classes.html : different length +/sdcard/android/layout_tests/fast/dom/select-selectedIndex.html : different length +/sdcard/android/layout_tests/fast/dom/document-width-height-force-layout.html : @offset: 142 +/sdcard/android/layout_tests/fast/dom/client-width-height.html : @offset: 119 +/sdcard/android/layout_tests/fast/dom/clone-node-form-elements-with-attr.html : different length +/sdcard/android/layout_tests/fast/dom/dom-add-optionelement.html : different length +/sdcard/android/layout_tests/fast/dom/location-assign.html : different length +/sdcard/android/layout_tests/fast/dom/javascript-backslash.html : different length +/sdcard/android/layout_tests/fast/dom/global-constructors.html : different length +/sdcard/android/layout_tests/fast/dom/client-width-height-quirks.html : @offset: 115 +/sdcard/android/layout_tests/fast/dom/javascript-url-crash-function.html : different length +/sdcard/android/layout_tests/fast/dom/location-hash.html : different length +/sdcard/android/layout_tests/fast/dom/constructors-cached.html : different length +/sdcard/android/layout_tests/fast/dom/documenturi-can-hold-arbitrary-string.html : different length +/sdcard/android/layout_tests/fast/dom/documenturi-not-affected-by-base-tag.html : different length +/sdcard/android/layout_tests/fast/dom/open-and-close-by-DOM.html : different length +/sdcard/android/layout_tests/fast/dom/document_write_params.html : TIMEDOUT +/sdcard/android/layout_tests/fast/dom/tabindex-clamp.html : different length +/sdcard/android/layout_tests/fast/dom/constructors-cached-navigate.html : different length +/sdcard/android/layout_tests/fast/dom/frame-loading-via-document-write.html : TIMEDOUT +/sdcard/android/layout_tests/fast/dom/ImageDocument-image-deletion.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/get-non-ascii-text-plain.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/advanced-get.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/get-non-ascii-text-plain-latin-1.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/post-multiple-items-multipart-form-data.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/get-multiple-items.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/get-non-ascii-always-utf-8.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/post-multiple-items.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/post-append-query.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/get-multiple-items-x-www-form-urlencoded.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/get-overwrite-query.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/post-multiple-items-x-www-form-urlencoded.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/get-multiple-items-text-plain.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/post-multiple-items-text-plain.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/get-non-ascii.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/post-text-plain-with-accept-charset.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/post-text-plain.html : different length +/sdcard/android/layout_tests/fast/forms/mailto/advanced-put.html : different length +/sdcard/android/layout_tests/fast/forms/listbox-typeahead-scroll.html : different length +/sdcard/android/layout_tests/fast/forms/select-empty-list.html : different length +/sdcard/android/layout_tests/fast/forms/select-accesskey.html : different length +/sdcard/android/layout_tests/fast/forms/focus2.html : different length +/sdcard/android/layout_tests/fast/forms/password-doubleclick-selection.html : different length +/sdcard/android/layout_tests/fast/forms/textfield-inside-anchor.html : different length +/sdcard/android/layout_tests/fast/forms/input-maxlength.html : different length +/sdcard/android/layout_tests/fast/forms/input-text-option-delete.html : TIMEDOUT +/sdcard/android/layout_tests/fast/forms/selection-functions.html : @offset: 306 +/sdcard/android/layout_tests/fast/forms/textfield-to-password-on-focus.html : different length +/sdcard/android/layout_tests/fast/forms/focus-selection-textarea.html : different length +/sdcard/android/layout_tests/fast/forms/enter-clicks-buttons.html : different length +/sdcard/android/layout_tests/fast/forms/menulist-no-renderer-onmousedown.html : different length +/sdcard/android/layout_tests/fast/forms/select-display-none-style-resolve.html : TIMEDOUT +/sdcard/android/layout_tests/fast/forms/radio_checked_name.html : @offset: 303 +/sdcard/android/layout_tests/fast/forms/select-double-onchange.html : different length +/sdcard/android/layout_tests/fast/forms/button-enter-click.html : different length +/sdcard/android/layout_tests/fast/forms/11423.html : different length +/sdcard/android/layout_tests/fast/forms/search-click-in-placeholder.html : @offset: 1 +/sdcard/android/layout_tests/fast/forms/autofocus-opera-003.html : @offset: 51 +/sdcard/android/layout_tests/fast/forms/search-hidden-cancel-button.html : different length +/sdcard/android/layout_tests/fast/forms/willvalidate-004.html : different length +/sdcard/android/layout_tests/fast/forms/textarea-paste-newline.html : different length +/sdcard/android/layout_tests/fast/forms/drag-into-textarea.html : different length +/sdcard/android/layout_tests/fast/forms/onselect-textfield.html : different length +/sdcard/android/layout_tests/fast/forms/input-implicit-length-limit.html : TIMEDOUT +/sdcard/android/layout_tests/fast/forms/form-and-frame-interaction-retains-values.html : different length +/sdcard/android/layout_tests/fast/forms/input-appearance-focus.html : TIMEDOUT +/sdcard/android/layout_tests/fast/forms/slider-transformed.html : different length +/sdcard/android/layout_tests/fast/forms/listbox-select-all.html : different length +/sdcard/android/layout_tests/fast/forms/textfield-onchange-deletion.html : different length +/sdcard/android/layout_tests/fast/forms/focus-control-to-page.html : different length +/sdcard/android/layout_tests/fast/forms/select-type-ahead-non-latin.html : different length +/sdcard/android/layout_tests/fast/forms/textarea-no-scroll-on-blur.html : @offset: 79 +/sdcard/android/layout_tests/fast/forms/focus-selection-input.html : different length +/sdcard/android/layout_tests/fast/forms/listbox-onchange.html : different length +/sdcard/android/layout_tests/fast/forms/button-spacebar-click.html : different length +/sdcard/android/layout_tests/fast/forms/search-event-delay.html : different length +/sdcard/android/layout_tests/fast/forms/search-cancel-button-mouseup.html : different length +/sdcard/android/layout_tests/fast/forms/select-enter-key.html : different length +/sdcard/android/layout_tests/fast/forms/drag-out-of-textarea.html : different length +/sdcard/android/layout_tests/fast/forms/textarea-hard-linewrap.html : different length +/sdcard/android/layout_tests/fast/forms/input-type-change-in-onfocus-keyboard.html : different length +/sdcard/android/layout_tests/fast/forms/dragging-to-disabled-file-input.html : different length +/sdcard/android/layout_tests/fast/forms/input-radio-checked-tab.html : @offset: 115 +/sdcard/android/layout_tests/fast/forms/plaintext-mode-1.html : different length +/sdcard/android/layout_tests/fast/forms/option-in-optgroup-removal.html : different length +/sdcard/android/layout_tests/fast/forms/search-display-none-cancel-button.html : TIMEDOUT +/sdcard/android/layout_tests/fast/forms/check-box-enter-key.html : different length +/sdcard/android/layout_tests/fast/forms/input-select-on-click.html : different length +/sdcard/android/layout_tests/fast/forms/button-state-restore.html : different length +/sdcard/android/layout_tests/fast/forms/access-key.html : different length +/sdcard/android/layout_tests/fast/forms/textarea-scrolled-endline-caret.html : different length +/sdcard/android/layout_tests/fast/forms/textarea-type-spaces.html : different length +/sdcard/android/layout_tests/fast/forms/slider-mouse-events.html : different length +/sdcard/android/layout_tests/fast/forms/textarea-selection-preservation.html : different length +/sdcard/android/layout_tests/fast/forms/slider-onchange-event.html : different length +/sdcard/android/layout_tests/fast/forms/textarea-appearance-wrap.html : different length +/sdcard/android/layout_tests/fast/forms/onselect-textarea.html : different length +/sdcard/android/layout_tests/fast/forms/textarea-initial-caret-position.html : different length +/sdcard/android/layout_tests/fast/forms/listbox-selection.html : different length +/sdcard/android/layout_tests/fast/css/variables/color-hex-test.html : different length +/sdcard/android/layout_tests/fast/css/dashboard-region-parser.html : different length +/sdcard/android/layout_tests/fast/css/hover-affects-child.html : different length +/sdcard/android/layout_tests/fast/css/html-attr-case-sensitivity.html : TIMEDOUT +/sdcard/android/layout_tests/fast/css/computed-style.html : different length +/sdcard/android/layout_tests/fast/css/getComputedStyle-transform.html : different length +/sdcard/android/layout_tests/fast/css/computed-style-without-renderer.html : different length +/sdcard/android/layout_tests/fast/parser/entity-comment-in-iframe.html : @offset: 0 +/sdcard/android/layout_tests/fast/parser/external-entities.xml : different length +/sdcard/android/layout_tests/fast/parser/script-tag-with-trailing-slash.html : different length +/sdcard/android/layout_tests/fast/parser/comment-in-iframe.html : @offset: 0 +/sdcard/android/layout_tests/fast/parser/xml-declaration-missing-ending-mark.html : different length +/sdcard/android/layout_tests/fast/parser/entity-end-script-tag.html : different length +/sdcard/android/layout_tests/fast/parser/tabindex-parsing.html : different length +/sdcard/android/layout_tests/fast/history/subframe-is-visited.html : different length +/sdcard/android/layout_tests/fast/history/window-open.html : TIMEDOUT +/sdcard/android/layout_tests/fast/history/go-back-to-changed-name.html : different length +/sdcard/android/layout_tests/fast/loader/cancel-load-during-port-block-timer.html : TIMEDOUT +/sdcard/android/layout_tests/fast/loader/local-iFrame-source-from-local.html : different length +/sdcard/android/layout_tests/fast/loader/null-request-after-willSendRequest.html : different length +/sdcard/android/layout_tests/fast/loader/stop-provisional-loads.html : different length +/sdcard/android/layout_tests/fast/loader/xmlhttprequest-missing-file-exception.html : different length +/sdcard/android/layout_tests/fast/loader/onunload-form-submit-crash-2.html : different length +/sdcard/android/layout_tests/fast/loader/plain-text-document.html : different length +/sdcard/android/layout_tests/fast/loader/onunload-form-submit-crash.html : different length +/sdcard/android/layout_tests/fast/loader/local-image-from-local.html : different length +/sdcard/android/layout_tests/fast/loader/local-CSS-from-local.html : TIMEDOUT +/sdcard/android/layout_tests/fast/loader/local-JavaScript-from-local.html : different length +/sdcard/android/layout_tests/fast/loader/data-url-encoding-svg.html : different length +/sdcard/android/layout_tests/fast/loader/opaque-base-url.html : @offset: 129 +/sdcard/android/layout_tests/fast/canvas/canvas-alphaImageData-behavior.html : different length +/sdcard/android/layout_tests/fast/canvas/pointInPath.html : different length +/sdcard/android/layout_tests/fast/canvas/toDataURL-supportedTypes.html : different length +/sdcard/android/layout_tests/fast/canvas/canvas-getImageData.html : different length +/sdcard/android/layout_tests/fast/canvas/canvas-longlived-context.html : TIMEDOUT +/sdcard/android/layout_tests/fast/canvas/canvas-save-restore-with-path.html : different length +/sdcard/android/layout_tests/fast/canvas/set-colors.html : different length +/sdcard/android/layout_tests/fast/frames/viewsource-empty-attribute-value.html : different length +/sdcard/android/layout_tests/fast/frames/frame-deep-nested-resize.html : different length +/sdcard/android/layout_tests/fast/frames/iframe-window-focus.html : different length +/sdcard/android/layout_tests/fast/frames/frameElement-widthheight.html : different length +/sdcard/android/layout_tests/fast/frames/removal-before-attach-crash.html : different length +/sdcard/android/layout_tests/fast/frames/frame-js-url-clientWidth.html : different length diff --git a/tests/DumpRenderTree/results/layout_tests_nontext.txt b/tests/DumpRenderTree/results/layout_tests_nontext.txt new file mode 100644 index 0000000000000000000000000000000000000000..c9e166cbeed9fe9ed97fb81835a2596a4420020c --- /dev/null +++ b/tests/DumpRenderTree/results/layout_tests_nontext.txt @@ -0,0 +1,1753 @@ +/sdcard/android/layout_tests/fast/media/mq-relative-constraints-05.html +/sdcard/android/layout_tests/fast/media/mq-grid-02.html +/sdcard/android/layout_tests/fast/media/mq-compound-query-02.html +/sdcard/android/layout_tests/fast/media/mq-relative-constraints-09.html +/sdcard/android/layout_tests/fast/media/mq-width-absolute-03.html +/sdcard/android/layout_tests/fast/media/mq-invalid-media-feature-02.html +/sdcard/android/layout_tests/fast/media/mq-simple-query-04.html +/sdcard/android/layout_tests/fast/media/mq-min-pixel-ratio.html +/sdcard/android/layout_tests/fast/media/implicit-media-all.html +/sdcard/android/layout_tests/fast/media/media-descriptor-syntax-01.html +/sdcard/android/layout_tests/fast/media/mq-simple-neg-query-03.html +/sdcard/android/layout_tests/fast/media/viewport-media-query.html +/sdcard/android/layout_tests/fast/media/media-descriptor-syntax-05.html +/sdcard/android/layout_tests/fast/media/mq-invalid-syntax-01.html +/sdcard/android/layout_tests/fast/media/mq-transition.html +/sdcard/android/layout_tests/fast/media/mq-transform-04.html +/sdcard/android/layout_tests/fast/media/mq-invalid-syntax-05.html +/sdcard/android/layout_tests/fast/media/mq-js-media-except-02.html +/sdcard/android/layout_tests/fast/media/mq-relative-constraints-02.html +/sdcard/android/layout_tests/fast/media/mq-js-stylesheet-media-03.html +/sdcard/android/layout_tests/fast/media/mq-relative-constraints-06.html +/sdcard/android/layout_tests/fast/media/mq-valueless.html +/sdcard/android/layout_tests/fast/media/mq-compound-query-03.html +/sdcard/android/layout_tests/fast/media/mq-simple-query-01.html +/sdcard/android/layout_tests/fast/media/mq-invalid-media-feature-03.html +/sdcard/android/layout_tests/fast/media/mq-width-absolute-04.html +/sdcard/android/layout_tests/fast/media/mq-simple-query-05.html +/sdcard/android/layout_tests/fast/media/mq-animation.html +/sdcard/android/layout_tests/fast/media/media-descriptor-syntax-02.html +/sdcard/android/layout_tests/fast/media/mq-simple-neg-query-04.html +/sdcard/android/layout_tests/fast/media/media-type-syntax-01.html +/sdcard/android/layout_tests/fast/media/media-descriptor-syntax-06.html +/sdcard/android/layout_tests/fast/media/mq-invalid-syntax-02.html +/sdcard/android/layout_tests/fast/media/mq-transform-01.html +/sdcard/android/layout_tests/fast/media/monochrome.html +/sdcard/android/layout_tests/fast/media/mq-pixel-ratio.html +/sdcard/android/layout_tests/fast/media/mq-js-media-except-03.html +/sdcard/android/layout_tests/fast/media/mq-relative-constraints-03.html +/sdcard/android/layout_tests/fast/media/mq-js-stylesheet-media-04.html +/sdcard/android/layout_tests/fast/media/mq-relative-constraints-07.html +/sdcard/android/layout_tests/fast/media/mq-compound-query-04.html +/sdcard/android/layout_tests/fast/media/mq-width-absolute-01.html +/sdcard/android/layout_tests/fast/media/mq-simple-query-02.html +/sdcard/android/layout_tests/fast/media/mq-invalid-media-feature-04.html +/sdcard/android/layout_tests/fast/media/mq-max-pixel-ratio.html +/sdcard/android/layout_tests/fast/media/mq-simple-neg-query-01.html +/sdcard/android/layout_tests/fast/media/media-descriptor-syntax-03.html +/sdcard/android/layout_tests/fast/media/mq-simple-neg-query-05.html +/sdcard/android/layout_tests/fast/media/media-type-syntax-02.html +/sdcard/android/layout_tests/fast/media/mq-invalid-syntax-03.html +/sdcard/android/layout_tests/fast/media/mq-transform-02.html +/sdcard/android/layout_tests/fast/media/mq-js-stylesheet-media-01.html +/sdcard/android/layout_tests/fast/media/mq-relative-constraints-04.html +/sdcard/android/layout_tests/fast/media/mq-grid-01.html +/sdcard/android/layout_tests/fast/media/mq-compound-query-01.html +/sdcard/android/layout_tests/fast/media/mq-min-constraint.html +/sdcard/android/layout_tests/fast/media/mq-relative-constraints-08.html +/sdcard/android/layout_tests/fast/media/mq-compound-query-05.html +/sdcard/android/layout_tests/fast/media/mq-width-absolute-02.html +/sdcard/android/layout_tests/fast/media/mq-invalid-media-feature-01.html +/sdcard/android/layout_tests/fast/media/mq-simple-query-03.html +/sdcard/android/layout_tests/fast/media/mq-js-media-forward-syntax.html +/sdcard/android/layout_tests/fast/media/mq-simple-neg-query-02.html +/sdcard/android/layout_tests/fast/media/media-descriptor-syntax-04.html +/sdcard/android/layout_tests/fast/media/mq-transform-03.html +/sdcard/android/layout_tests/fast/media/mq-invalid-syntax-04.html +/sdcard/android/layout_tests/fast/media/mq-js-media-except-01.html +/sdcard/android/layout_tests/fast/media/mq-js-stylesheet-media-02.html +/sdcard/android/layout_tests/fast/replaced/width100percent-radio.html +/sdcard/android/layout_tests/fast/replaced/object-align-hspace-vspace.html +/sdcard/android/layout_tests/fast/replaced/width100percent-menulist.html +/sdcard/android/layout_tests/fast/replaced/selection-rect.html +/sdcard/android/layout_tests/fast/replaced/image-sizing.html +/sdcard/android/layout_tests/fast/replaced/minheight-pxs.html +/sdcard/android/layout_tests/fast/replaced/maxheight-pxs.html +/sdcard/android/layout_tests/fast/replaced/inline-box-wrapper-handover.html +/sdcard/android/layout_tests/fast/replaced/width100percent-searchfield.html +/sdcard/android/layout_tests/fast/replaced/selection-rect-transform.html +/sdcard/android/layout_tests/fast/replaced/pdf-as-image.html +/sdcard/android/layout_tests/fast/replaced/replaced-breaking-mixture.html +/sdcard/android/layout_tests/fast/replaced/minwidth-pxs.html +/sdcard/android/layout_tests/fast/replaced/width100percent-textarea.html +/sdcard/android/layout_tests/fast/replaced/maxwidth-pxs.html +/sdcard/android/layout_tests/fast/replaced/max-width-percent.html +/sdcard/android/layout_tests/fast/replaced/absolute-position-percentage-height.html +/sdcard/android/layout_tests/fast/replaced/002.html +/sdcard/android/layout_tests/fast/replaced/004.html +/sdcard/android/layout_tests/fast/replaced/width100percent-checkbox.html +/sdcard/android/layout_tests/fast/replaced/applet-disabled-positioned.html +/sdcard/android/layout_tests/fast/replaced/006.html +/sdcard/android/layout_tests/fast/replaced/008.html +/sdcard/android/layout_tests/fast/replaced/percent-height-in-anonymous-block-widget.html +/sdcard/android/layout_tests/fast/replaced/minheight-percent.html +/sdcard/android/layout_tests/fast/replaced/maxheight-percent.html +/sdcard/android/layout_tests/fast/replaced/absolute-position-with-auto-width-and-left-and-right.html +/sdcard/android/layout_tests/fast/replaced/minwidth-percent.html +/sdcard/android/layout_tests/fast/replaced/maxwidth-percent.html +/sdcard/android/layout_tests/fast/replaced/applet-rendering-java-disabled.html +/sdcard/android/layout_tests/fast/replaced/selection-rect-in-table-cell.html +/sdcard/android/layout_tests/fast/replaced/percent-height-in-anonymous-block.html +/sdcard/android/layout_tests/fast/replaced/three-selects-break.html +/sdcard/android/layout_tests/fast/replaced/width100percent-button.html +/sdcard/android/layout_tests/fast/replaced/image-tag.html +/sdcard/android/layout_tests/fast/replaced/image-onload.html +/sdcard/android/layout_tests/fast/replaced/image-resize-width.html +/sdcard/android/layout_tests/fast/replaced/absolute-image-sizing.html +/sdcard/android/layout_tests/fast/replaced/replaced-breaking.html +/sdcard/android/layout_tests/fast/replaced/001.html +/sdcard/android/layout_tests/fast/replaced/width100percent-image.html +/sdcard/android/layout_tests/fast/replaced/image-solid-color-with-alpha.html +/sdcard/android/layout_tests/fast/replaced/003.html +/sdcard/android/layout_tests/fast/replaced/replaced-child-of-absolute-with-auto-height.html +/sdcard/android/layout_tests/fast/replaced/005.html +/sdcard/android/layout_tests/fast/replaced/007.html +/sdcard/android/layout_tests/fast/replaced/absolute-position-with-auto-height-and-top-and-bottom.html +/sdcard/android/layout_tests/fast/replaced/width100percent-textfield.html +/sdcard/android/layout_tests/fast/replaced/absolute-position-percentage-width.html +/sdcard/android/layout_tests/fast/dynamic/positioned-movement-with-positioned-children.html +/sdcard/android/layout_tests/fast/dynamic/subtree-table-cell-height.html +/sdcard/android/layout_tests/fast/dynamic/move-node-with-selection.html +/sdcard/android/layout_tests/fast/dynamic/create-renderer-for-whitespace-only-text.html +/sdcard/android/layout_tests/fast/dynamic/outerHTML-doc.html +/sdcard/android/layout_tests/fast/dynamic/floating-to-positioned-2.html +/sdcard/android/layout_tests/fast/dynamic/012.html +/sdcard/android/layout_tests/fast/dynamic/004.html +/sdcard/android/layout_tests/fast/dynamic/008.html +/sdcard/android/layout_tests/fast/dynamic/float-no-longer-overhanging.html +/sdcard/android/layout_tests/fast/dynamic/float-withdrawal-2.html +/sdcard/android/layout_tests/fast/dynamic/float-in-trailing-whitespace-after-last-line-break.html +/sdcard/android/layout_tests/fast/dynamic/selection-highlight-adjust.html +/sdcard/android/layout_tests/fast/dynamic/subtree-no-common-root-static-y.html +/sdcard/android/layout_tests/fast/dynamic/genContentDestroyChildren.html +/sdcard/android/layout_tests/fast/dynamic/001.html +/sdcard/android/layout_tests/fast/dynamic/link-href-change.html +/sdcard/android/layout_tests/fast/dynamic/013.html +/sdcard/android/layout_tests/fast/dynamic/005.html +/sdcard/android/layout_tests/fast/dynamic/009.html +/sdcard/android/layout_tests/fast/dynamic/float-withdrawal.html +/sdcard/android/layout_tests/fast/dynamic/anonymous-block-layer-lost.html +/sdcard/android/layout_tests/fast/dynamic/layer-hit-test-crash.html +/sdcard/android/layout_tests/fast/dynamic/view-overflow.html +/sdcard/android/layout_tests/fast/dynamic/010.html +/sdcard/android/layout_tests/fast/dynamic/002.html +/sdcard/android/layout_tests/fast/dynamic/014.html +/sdcard/android/layout_tests/fast/dynamic/006.html +/sdcard/android/layout_tests/fast/dynamic/flash-replacement-test.html +/sdcard/android/layout_tests/fast/dynamic/insert-before-table-part-in-continuation.html +/sdcard/android/layout_tests/fast/dynamic/staticY.html +/sdcard/android/layout_tests/fast/dynamic/anonymous-block-orphaned-lines.html +/sdcard/android/layout_tests/fast/dynamic/noninlinebadness.html +/sdcard/android/layout_tests/fast/dynamic/subtree-parent-static-y.html +/sdcard/android/layout_tests/fast/dynamic/outerHTML-img.html +/sdcard/android/layout_tests/fast/dynamic/staticY-marking-parents-regression.html +/sdcard/android/layout_tests/fast/dynamic/floating-to-positioned.html +/sdcard/android/layout_tests/fast/dynamic/subtree-boundary-percent-height.html +/sdcard/android/layout_tests/fast/dynamic/011.html +/sdcard/android/layout_tests/fast/dynamic/containing-block-change.html +/sdcard/android/layout_tests/fast/dynamic/015.html +/sdcard/android/layout_tests/fast/dynamic/007.html +/sdcard/android/layout_tests/fast/text/firstline/001.html +/sdcard/android/layout_tests/fast/text/firstline/002.html +/sdcard/android/layout_tests/fast/text/firstline/003.html +/sdcard/android/layout_tests/fast/text/international/wrap-CJK-001.html +/sdcard/android/layout_tests/fast/text/international/bidi-listbox-atsui.html +/sdcard/android/layout_tests/fast/text/international/hindi-spacing.html +/sdcard/android/layout_tests/fast/text/international/thai-line-breaks.html +/sdcard/android/layout_tests/fast/text/international/bidi-neutral-run.html +/sdcard/android/layout_tests/fast/text/international/bidi-L2-run-reordering.html +/sdcard/android/layout_tests/fast/text/international/bidi-override.html +/sdcard/android/layout_tests/fast/text/international/bidi-innertext.html +/sdcard/android/layout_tests/fast/text/international/bidi-european-terminators.html +/sdcard/android/layout_tests/fast/text/international/bidi-listbox.html +/sdcard/android/layout_tests/fast/text/international/bidi-LDB-2-formatting-characters.html +/sdcard/android/layout_tests/fast/text/international/bidi-AN-after-L.html +/sdcard/android/layout_tests/fast/text/international/bidi-LDB-2-CSS.html +/sdcard/android/layout_tests/fast/text/international/bidi-control-chars-treated-as-ZWS.html +/sdcard/android/layout_tests/fast/text/international/rtl-caret.html +/sdcard/android/layout_tests/fast/text/international/bidi-neutral-directionality-paragraph-start.html +/sdcard/android/layout_tests/fast/text/international/bidi-AN-after-empty-run.html +/sdcard/android/layout_tests/fast/text/international/001.html +/sdcard/android/layout_tests/fast/text/international/002.html +/sdcard/android/layout_tests/fast/text/international/bidi-ignored-for-first-child-inline.html +/sdcard/android/layout_tests/fast/text/international/bidi-explicit-embedding.html +/sdcard/android/layout_tests/fast/text/international/003.html +/sdcard/android/layout_tests/fast/text/international/rtl-white-space-pre-wrap.html +/sdcard/android/layout_tests/fast/text/international/bidi-layout-across-linebreak.html +/sdcard/android/layout_tests/fast/text/international/bidi-CS-after-AN.html +/sdcard/android/layout_tests/fast/text/international/bidi-menulist.html +/sdcard/android/layout_tests/fast/text/international/bidi-LDB-2-HTML.html +/sdcard/android/layout_tests/fast/text/international/complex-character-based-fallback.html +/sdcard/android/layout_tests/fast/text/whitespace/pre-wrap-overflow-selection.html +/sdcard/android/layout_tests/fast/text/whitespace/pre-newline-box-test.html +/sdcard/android/layout_tests/fast/text/whitespace/span-in-word-space-causes-overflow.html +/sdcard/android/layout_tests/fast/text/whitespace/nowrap-clear-float.html +/sdcard/android/layout_tests/fast/text/whitespace/pre-wrap-line-test.html +/sdcard/android/layout_tests/fast/text/whitespace/010.html +/sdcard/android/layout_tests/fast/text/whitespace/020.html +/sdcard/android/layout_tests/fast/text/whitespace/002.html +/sdcard/android/layout_tests/fast/text/whitespace/030.html +/sdcard/android/layout_tests/fast/text/whitespace/012.html +/sdcard/android/layout_tests/fast/text/whitespace/022.html +/sdcard/android/layout_tests/fast/text/whitespace/004.html +/sdcard/android/layout_tests/fast/text/whitespace/014.html +/sdcard/android/layout_tests/fast/text/whitespace/024.html +/sdcard/android/layout_tests/fast/text/whitespace/006.html +/sdcard/android/layout_tests/fast/text/whitespace/016.html +/sdcard/android/layout_tests/fast/text/whitespace/008.html +/sdcard/android/layout_tests/fast/text/whitespace/026.html +/sdcard/android/layout_tests/fast/text/whitespace/018.html +/sdcard/android/layout_tests/fast/text/whitespace/028.html +/sdcard/android/layout_tests/fast/text/whitespace/normal-after-nowrap-breaking.html +/sdcard/android/layout_tests/fast/text/whitespace/pre-break-word.html +/sdcard/android/layout_tests/fast/text/whitespace/nbsp-mode-and-linewraps.html +/sdcard/android/layout_tests/fast/text/whitespace/001.html +/sdcard/android/layout_tests/fast/text/whitespace/011.html +/sdcard/android/layout_tests/fast/text/whitespace/tab-character-basics.html +/sdcard/android/layout_tests/fast/text/whitespace/003.html +/sdcard/android/layout_tests/fast/text/whitespace/021.html +/sdcard/android/layout_tests/fast/text/whitespace/013.html +/sdcard/android/layout_tests/fast/text/whitespace/005.html +/sdcard/android/layout_tests/fast/text/whitespace/023.html +/sdcard/android/layout_tests/fast/text/whitespace/015.html +/sdcard/android/layout_tests/fast/text/whitespace/025.html +/sdcard/android/layout_tests/fast/text/whitespace/007.html +/sdcard/android/layout_tests/fast/text/whitespace/017.html +/sdcard/android/layout_tests/fast/text/whitespace/pre-wrap-spaces-after-newline.html +/sdcard/android/layout_tests/fast/text/whitespace/027.html +/sdcard/android/layout_tests/fast/text/whitespace/009.html +/sdcard/android/layout_tests/fast/text/whitespace/019.html +/sdcard/android/layout_tests/fast/text/whitespace/pre-wrap-last-char.html +/sdcard/android/layout_tests/fast/text/whitespace/029.html +/sdcard/android/layout_tests/fast/text/basic/001.html +/sdcard/android/layout_tests/fast/text/basic/002.html +/sdcard/android/layout_tests/fast/text/basic/011.html +/sdcard/android/layout_tests/fast/text/basic/generic-family-changes.html +/sdcard/android/layout_tests/fast/text/basic/003.html +/sdcard/android/layout_tests/fast/text/basic/012.html +/sdcard/android/layout_tests/fast/text/basic/004.html +/sdcard/android/layout_tests/fast/text/basic/013.html +/sdcard/android/layout_tests/fast/text/basic/005.html +/sdcard/android/layout_tests/fast/text/basic/014.html +/sdcard/android/layout_tests/fast/text/basic/006.html +/sdcard/android/layout_tests/fast/text/basic/015.html +/sdcard/android/layout_tests/fast/text/basic/007.html +/sdcard/android/layout_tests/fast/text/basic/008.html +/sdcard/android/layout_tests/fast/text/basic/009.html +/sdcard/android/layout_tests/fast/text/basic/generic-family-reset.html +/sdcard/android/layout_tests/fast/text/in-rendered-text-rtl.html +/sdcard/android/layout_tests/fast/text/selection-painted-separately.html +/sdcard/android/layout_tests/fast/text/bidi-embedding-pop-and-push-same.html +/sdcard/android/layout_tests/fast/text/wbr-in-pre-crash.html +/sdcard/android/layout_tests/fast/text/atsui-spacing-features.html +/sdcard/android/layout_tests/fast/text/textIteratorNilRenderer.html +/sdcard/android/layout_tests/fast/text/drawBidiText.html +/sdcard/android/layout_tests/fast/text/selection-hard-linebreak.html +/sdcard/android/layout_tests/fast/text/word-break.html +/sdcard/android/layout_tests/fast/text/font-initial.html +/sdcard/android/layout_tests/fast/text/break-word.html +/sdcard/android/layout_tests/fast/text/stroking.html +/sdcard/android/layout_tests/fast/text/midword-break-hang.html +/sdcard/android/layout_tests/fast/text/atsui-partial-selection.html +/sdcard/android/layout_tests/fast/text/embed-at-end-of-pre-wrap-line.html +/sdcard/android/layout_tests/fast/text/atsui-multiple-renderers.html +/sdcard/android/layout_tests/fast/text/apply-start-width-after-skipped-text.html +/sdcard/android/layout_tests/fast/text/capitalize-preserve-nbsp.html +/sdcard/android/layout_tests/fast/text/updateNewFont.html +/sdcard/android/layout_tests/fast/text/atsui-rtl-override-selection.html +/sdcard/android/layout_tests/fast/text/align-center-rtl-spill.html +/sdcard/android/layout_tests/fast/text/wbr.html +/sdcard/android/layout_tests/fast/text/cg-vs-atsui.html +/sdcard/android/layout_tests/fast/text/monospace-width-cache.html +/sdcard/android/layout_tests/fast/text/soft-hyphen-2.html +/sdcard/android/layout_tests/fast/text/justified-selection.html +/sdcard/android/layout_tests/fast/text/atsui-pointtooffset-calls-cg.html +/sdcard/android/layout_tests/fast/text/atsui-kerning-and-ligatures.html +/sdcard/android/layout_tests/fast/text/wbr-pre.html +/sdcard/android/layout_tests/fast/text/capitalize-boundaries.html +/sdcard/android/layout_tests/fast/text/trailing-white-space.html +/sdcard/android/layout_tests/fast/text/capitalize-empty-generated-string.html +/sdcard/android/layout_tests/fast/text/stripNullFromText.html +/sdcard/android/layout_tests/fast/text/letter-spacing-negative-opacity.html +/sdcard/android/layout_tests/fast/text/atsui-small-caps-punctuation-size.html +/sdcard/android/layout_tests/fast/text/word-break-soft-hyphen.html +/sdcard/android/layout_tests/fast/text/fixed-pitch-control-characters.html +/sdcard/android/layout_tests/fast/text/cg-fallback-bolding.html +/sdcard/android/layout_tests/fast/text/line-breaks-after-white-space.html +/sdcard/android/layout_tests/fast/text/soft-hyphen-3.html +/sdcard/android/layout_tests/fast/text/wide-zero-width-space.html +/sdcard/android/layout_tests/fast/text/should-use-atsui.html +/sdcard/android/layout_tests/fast/text/justified-selection-at-edge.html +/sdcard/android/layout_tests/fast/text/trailing-white-space-2.html +/sdcard/android/layout_tests/fast/text/word-break-run-rounding.html +/sdcard/android/layout_tests/fast/text/softHyphen.html +/sdcard/android/layout_tests/fast/text/delete-hard-break-character.html +/sdcard/android/layout_tests/fast/text/line-breaks.html +/sdcard/android/layout_tests/fast/text/wbr-styled.html +/sdcard/android/layout_tests/fast/text/large-text-composed-char.html +/sdcard/android/layout_tests/fast/text/shadow-no-blur.html +/sdcard/android/layout_tests/fast/text/reset-emptyRun.html +/sdcard/android/layout_tests/fast/text/word-space.html +/sdcard/android/layout_tests/fast/text/midword-break-after-breakable-char.html +/sdcard/android/layout_tests/fast/text/stroking-decorations.html +/sdcard/android/layout_tests/fast/encoding/utf-16-little-endian.html +/sdcard/android/layout_tests/fast/encoding/denormalised-voiced-japanese-chars.html +/sdcard/android/layout_tests/fast/encoding/utf-16-no-bom.xml +/sdcard/android/layout_tests/fast/encoding/utf-16-big-endian.html +/sdcard/android/layout_tests/fast/encoding/xmacroman-encoding-test.html +/sdcard/android/layout_tests/fast/encoding/invalid-UTF-8.html +/sdcard/android/layout_tests/fast/multicol/negativeColumnWidth.html +/sdcard/android/layout_tests/fast/multicol/column-rules.html +/sdcard/android/layout_tests/fast/multicol/zeroColumnCount.html +/sdcard/android/layout_tests/fast/multicol/columns-shorthand-parsing.html +/sdcard/android/layout_tests/fast/multicol/float-multicol.html +/sdcard/android/layout_tests/fast/doctypes/001.html +/sdcard/android/layout_tests/fast/doctypes/002.html +/sdcard/android/layout_tests/fast/doctypes/003.html +/sdcard/android/layout_tests/fast/doctypes/004.html +/sdcard/android/layout_tests/fast/css-generated-content/table-row-group-to-inline.html +/sdcard/android/layout_tests/fast/css-generated-content/spellingToolTip-assert.html +/sdcard/android/layout_tests/fast/css-generated-content/no-openclose-quote.html +/sdcard/android/layout_tests/fast/css-generated-content/before-with-first-letter.html +/sdcard/android/layout_tests/fast/css-generated-content/table-row-group-with-before.html +/sdcard/android/layout_tests/fast/css-generated-content/010.html +/sdcard/android/layout_tests/fast/css-generated-content/table-with-before.html +/sdcard/android/layout_tests/fast/css-generated-content/002.html +/sdcard/android/layout_tests/fast/css-generated-content/012.html +/sdcard/android/layout_tests/fast/css-generated-content/004.html +/sdcard/android/layout_tests/fast/css-generated-content/014.html +/sdcard/android/layout_tests/fast/css-generated-content/016.html +/sdcard/android/layout_tests/fast/css-generated-content/008.html +/sdcard/android/layout_tests/fast/css-generated-content/after-order.html +/sdcard/android/layout_tests/fast/css-generated-content/table-cell-before-content.html +/sdcard/android/layout_tests/fast/css-generated-content/visibleContentHiddenParent.html +/sdcard/android/layout_tests/fast/css-generated-content/inline-display-types.html +/sdcard/android/layout_tests/fast/css-generated-content/positioned-background-hit-test-crash.html +/sdcard/android/layout_tests/fast/css-generated-content/001.html +/sdcard/android/layout_tests/fast/css-generated-content/011.html +/sdcard/android/layout_tests/fast/css-generated-content/003.html +/sdcard/android/layout_tests/fast/css-generated-content/013.html +/sdcard/android/layout_tests/fast/css-generated-content/005.html +/sdcard/android/layout_tests/fast/css-generated-content/hover-style-change.html +/sdcard/android/layout_tests/fast/css-generated-content/absolute-position-inside-inline.html +/sdcard/android/layout_tests/fast/css-generated-content/015.html +/sdcard/android/layout_tests/fast/css-generated-content/table-row-with-before.html +/sdcard/android/layout_tests/fast/css-generated-content/007.html +/sdcard/android/layout_tests/fast/css-generated-content/009.html +/sdcard/android/layout_tests/fast/css-generated-content/wbr-with-before-content.html +/sdcard/android/layout_tests/fast/workers/stress-js-execution.html : has expected results +/sdcard/android/layout_tests/fast/lists/decimal-leading-zero.html +/sdcard/android/layout_tests/fast/lists/ol-display-types.html +/sdcard/android/layout_tests/fast/lists/li-style-alpha-huge-value-crash.html +/sdcard/android/layout_tests/fast/lists/ol-start-dynamic.html +/sdcard/android/layout_tests/fast/lists/numeric-markers-outside-list.html +/sdcard/android/layout_tests/fast/lists/marker-image-error.html +/sdcard/android/layout_tests/fast/lists/marker-before-empty-inline.html +/sdcard/android/layout_tests/fast/lists/scrolled-marker-paint.html +/sdcard/android/layout_tests/fast/lists/li-values.html +/sdcard/android/layout_tests/fast/lists/002.html +/sdcard/android/layout_tests/fast/lists/dynamic-marker-crash.html +/sdcard/android/layout_tests/fast/lists/list-item-line-height.html +/sdcard/android/layout_tests/fast/lists/004.html +/sdcard/android/layout_tests/fast/lists/drag-into-marker.html +/sdcard/android/layout_tests/fast/lists/list-style-none-crash.html +/sdcard/android/layout_tests/fast/lists/alpha-list-wrap.html +/sdcard/android/layout_tests/fast/lists/006.html +/sdcard/android/layout_tests/fast/lists/008.html +/sdcard/android/layout_tests/fast/lists/inlineBoxWrapperNullCheck.html +/sdcard/android/layout_tests/fast/lists/w3-list-styles.html +/sdcard/android/layout_tests/fast/lists/item-not-in-list-line-wrapping.html +/sdcard/android/layout_tests/fast/lists/olstart.html +/sdcard/android/layout_tests/fast/lists/big-list-marker.html +/sdcard/android/layout_tests/fast/lists/markers-in-selection.html +/sdcard/android/layout_tests/fast/lists/list-style-type-dynamic-change.html +/sdcard/android/layout_tests/fast/lists/001.html +/sdcard/android/layout_tests/fast/lists/ordered-list-with-no-ol-tag.html +/sdcard/android/layout_tests/fast/lists/003.html +/sdcard/android/layout_tests/fast/lists/005.html +/sdcard/android/layout_tests/fast/lists/li-br.html +/sdcard/android/layout_tests/fast/lists/007.html +/sdcard/android/layout_tests/fast/lists/009.html +/sdcard/android/layout_tests/fast/transforms/transform-overflow.html +/sdcard/android/layout_tests/fast/transforms/transforms-with-opacity.html +/sdcard/android/layout_tests/fast/transforms/transformed-caret.html +/sdcard/android/layout_tests/fast/transforms/matrix-01.html +/sdcard/android/layout_tests/fast/transforms/transform-positioned-ancestor.html +/sdcard/android/layout_tests/fast/transforms/matrix-02.html +/sdcard/android/layout_tests/fast/transforms/skew-with-unitless-zero.html +/sdcard/android/layout_tests/fast/transforms/overflow-with-transform.html +/sdcard/android/layout_tests/fast/transforms/transformed-document-element.html +/sdcard/android/layout_tests/fast/transforms/shadows.html +/sdcard/android/layout_tests/fast/transforms/transformed-focused-text-input.html +/sdcard/android/layout_tests/fast/transforms/diamond.html +/sdcard/android/layout_tests/fast/transforms/identity-matrix.html +/sdcard/android/layout_tests/fast/innerHTML/001.html +/sdcard/android/layout_tests/fast/innerHTML/002.html +/sdcard/android/layout_tests/fast/innerHTML/003.html +/sdcard/android/layout_tests/fast/innerHTML/006.html +/sdcard/android/layout_tests/fast/borders/borderRadiusSolid01.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDouble01.html +/sdcard/android/layout_tests/fast/borders/block-mask-overlay-image.html +/sdcard/android/layout_tests/fast/borders/borderRadiusSolid03.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDouble03.html +/sdcard/android/layout_tests/fast/borders/border-color-inherit.html +/sdcard/android/layout_tests/fast/borders/svg-as-border-image-2.html +/sdcard/android/layout_tests/fast/borders/borderRadiusInvalidColor.html +/sdcard/android/layout_tests/fast/borders/border-image-scale-transform.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDotted02.html +/sdcard/android/layout_tests/fast/borders/border-fit.html +/sdcard/android/layout_tests/fast/borders/borderRadiusArcs01.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDashed01.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDashed03.html +/sdcard/android/layout_tests/fast/borders/fieldsetBorderRadius.html +/sdcard/android/layout_tests/fast/borders/borderRadiusAllStylesAllCorners.html +/sdcard/android/layout_tests/fast/borders/borderRadiusGroove01.html +/sdcard/android/layout_tests/fast/borders/border-image-omit-right-slice.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDouble02.html +/sdcard/android/layout_tests/fast/borders/borderRadiusSolid02.html +/sdcard/android/layout_tests/fast/borders/outline-offset-min-assert.html +/sdcard/android/layout_tests/fast/borders/borderRadiusSolid04.html +/sdcard/android/layout_tests/fast/borders/border-radius-huge-assert.html +/sdcard/android/layout_tests/fast/borders/borderRadiusInset01.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDotted01.html +/sdcard/android/layout_tests/fast/borders/borderRadiusOutset01.html +/sdcard/android/layout_tests/fast/borders/svg-as-border-image.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDotted03.html +/sdcard/android/layout_tests/fast/borders/borderRadiusDashed02.html +/sdcard/android/layout_tests/fast/borders/borderRadiusRidge01.html +/sdcard/android/layout_tests/fast/borders/border-image-rotate-transform.html +/sdcard/android/layout_tests/fast/borders/inline-mask-overlay-image.html +/sdcard/android/layout_tests/fast/borders/borderRadiusGroove02.html +/sdcard/android/layout_tests/fast/borders/border-image-01.html +/sdcard/android/layout_tests/fast/selectors/175a.html +/sdcard/android/layout_tests/fast/selectors/155c.html +/sdcard/android/layout_tests/fast/selectors/059.html +/sdcard/android/layout_tests/fast/selectors/066b.html +/sdcard/android/layout_tests/fast/selectors/168.html +/sdcard/android/layout_tests/fast/selectors/177a.html +/sdcard/android/layout_tests/fast/selectors/087b.html +/sdcard/android/layout_tests/fast/selectors/020.html +/sdcard/android/layout_tests/fast/selectors/012.html +/sdcard/android/layout_tests/fast/selectors/040.html +/sdcard/android/layout_tests/fast/selectors/004.html +/sdcard/android/layout_tests/fast/selectors/032.html +/sdcard/android/layout_tests/fast/selectors/060.html +/sdcard/android/layout_tests/fast/selectors/016.html +/sdcard/android/layout_tests/fast/selectors/044.html +/sdcard/android/layout_tests/fast/selectors/008.html +/sdcard/android/layout_tests/fast/selectors/072.html +/sdcard/android/layout_tests/fast/selectors/lang-inheritance.html : has expected results +/sdcard/android/layout_tests/fast/selectors/064.html +/sdcard/android/layout_tests/fast/selectors/056.html +/sdcard/android/layout_tests/fast/selectors/018b.html +/sdcard/android/layout_tests/fast/selectors/090b.html +/sdcard/android/layout_tests/fast/selectors/045c.html +/sdcard/android/layout_tests/fast/selectors/170d.html +/sdcard/android/layout_tests/fast/selectors/157.html +/sdcard/android/layout_tests/fast/selectors/039b.html +/sdcard/android/layout_tests/fast/selectors/156b.html +/sdcard/android/layout_tests/fast/selectors/175b.html +/sdcard/android/layout_tests/fast/selectors/155d.html +/sdcard/android/layout_tests/fast/selectors/167a.html +/sdcard/android/layout_tests/fast/selectors/169.html +/sdcard/android/layout_tests/fast/selectors/077b.html +/sdcard/android/layout_tests/fast/selectors/177b.html +/sdcard/android/layout_tests/fast/selectors/169a.html +/sdcard/android/layout_tests/fast/selectors/lang-vs-xml-lang.html : has expected results +/sdcard/android/layout_tests/fast/selectors/lang-inheritance2.html : has expected results +/sdcard/android/layout_tests/fast/selectors/001.html +/sdcard/android/layout_tests/fast/selectors/021.html +/sdcard/android/layout_tests/fast/selectors/unqualified-hover-quirks.html +/sdcard/android/layout_tests/fast/selectors/013.html +/sdcard/android/layout_tests/fast/selectors/041.html +/sdcard/android/layout_tests/fast/selectors/021b.html +/sdcard/android/layout_tests/fast/selectors/005.html +/sdcard/android/layout_tests/fast/selectors/061.html +/sdcard/android/layout_tests/fast/selectors/170.html +/sdcard/android/layout_tests/fast/selectors/017.html +/sdcard/android/layout_tests/fast/selectors/170a.html +/sdcard/android/layout_tests/fast/selectors/009.html +/sdcard/android/layout_tests/fast/selectors/045.html +/sdcard/android/layout_tests/fast/selectors/154.html +/sdcard/android/layout_tests/fast/selectors/044b.html +/sdcard/android/layout_tests/fast/selectors/065.html +/sdcard/android/layout_tests/fast/selectors/155a.html +/sdcard/android/layout_tests/fast/selectors/166.html +/sdcard/android/layout_tests/fast/selectors/158.html +/sdcard/android/layout_tests/fast/selectors/077.html +/sdcard/android/layout_tests/fast/selectors/175c.html +/sdcard/android/layout_tests/fast/selectors/089.html +/sdcard/android/layout_tests/fast/selectors/088b.html +/sdcard/android/layout_tests/fast/selectors/nondeterministic-combinators.html +/sdcard/android/layout_tests/fast/selectors/unqualified-hover-strict.html +/sdcard/android/layout_tests/fast/selectors/010.html +/sdcard/android/layout_tests/fast/selectors/002.html +/sdcard/android/layout_tests/fast/selectors/014.html +/sdcard/android/layout_tests/fast/selectors/042.html +/sdcard/android/layout_tests/fast/selectors/006.html +/sdcard/android/layout_tests/fast/selectors/034.html +/sdcard/android/layout_tests/fast/selectors/062.html +/sdcard/android/layout_tests/fast/selectors/007a.html +/sdcard/android/layout_tests/fast/selectors/054.html +/sdcard/android/layout_tests/fast/selectors/018.html +/sdcard/android/layout_tests/fast/selectors/046.html +/sdcard/android/layout_tests/fast/selectors/170b.html +/sdcard/android/layout_tests/fast/selectors/072b.html +/sdcard/android/layout_tests/fast/selectors/044c.html +/sdcard/android/layout_tests/fast/selectors/038.html +/sdcard/android/layout_tests/fast/selectors/155.html +/sdcard/android/layout_tests/fast/selectors/066.html +/sdcard/android/layout_tests/fast/selectors/058.html +/sdcard/android/layout_tests/fast/selectors/155b.html +/sdcard/android/layout_tests/fast/selectors/166a.html +/sdcard/android/layout_tests/fast/selectors/167.html +/sdcard/android/layout_tests/fast/selectors/159.html +/sdcard/android/layout_tests/fast/selectors/168a.html +/sdcard/android/layout_tests/fast/selectors/078b.html +/sdcard/android/layout_tests/fast/selectors/011.html +/sdcard/android/layout_tests/fast/selectors/003.html +/sdcard/android/layout_tests/fast/selectors/015.html +/sdcard/android/layout_tests/fast/selectors/043.html +/sdcard/android/layout_tests/fast/selectors/160.html +/sdcard/android/layout_tests/fast/selectors/063.html +/sdcard/android/layout_tests/fast/selectors/043b.html +/sdcard/android/layout_tests/fast/selectors/007b.html +/sdcard/android/layout_tests/fast/selectors/027.html +/sdcard/android/layout_tests/fast/selectors/019.html +/sdcard/android/layout_tests/fast/selectors/083.html +/sdcard/android/layout_tests/fast/selectors/045b.html +/sdcard/android/layout_tests/fast/selectors/170c.html +/sdcard/android/layout_tests/fast/selectors/044d.html +/sdcard/android/layout_tests/fast/selectors/039.html +/sdcard/android/layout_tests/fast/overflow/overflow-focus-ring.html +/sdcard/android/layout_tests/fast/overflow/overflow-x-y.html +/sdcard/android/layout_tests/fast/overflow/overflow-text-hit-testing.html +/sdcard/android/layout_tests/fast/overflow/unreachable-overflow-rtl-bug.html +/sdcard/android/layout_tests/fast/overflow/overflow-auto-position-absolute.html +/sdcard/android/layout_tests/fast/overflow/scrollRevealButton.html +/sdcard/android/layout_tests/fast/overflow/overflow-rtl-inline-scrollbar.html +/sdcard/android/layout_tests/fast/overflow/002.html +/sdcard/android/layout_tests/fast/overflow/overflow-rtl.html +/sdcard/android/layout_tests/fast/overflow/004.html +/sdcard/android/layout_tests/fast/overflow/006.html +/sdcard/android/layout_tests/fast/overflow/scrollbar-position-update.html +/sdcard/android/layout_tests/fast/overflow/008.html +/sdcard/android/layout_tests/fast/overflow/scroll-nested-positioned-layer-in-overflow.html +/sdcard/android/layout_tests/fast/overflow/image-selection-highlight.html +/sdcard/android/layout_tests/fast/overflow/childFocusRingClip.html +/sdcard/android/layout_tests/fast/overflow/dynamic-hidden.html +/sdcard/android/layout_tests/fast/overflow/position-relative.html +/sdcard/android/layout_tests/fast/overflow/clip-rects-fixed-ancestor.html +/sdcard/android/layout_tests/fast/overflow/overflow_hidden.html +/sdcard/android/layout_tests/fast/overflow/infiniteRecursionGuard.html +/sdcard/android/layout_tests/fast/overflow/float-in-relpositioned.html +/sdcard/android/layout_tests/fast/overflow/table-overflow-float.html +/sdcard/android/layout_tests/fast/overflow/unreachable-content-test.html +/sdcard/android/layout_tests/fast/overflow/003.xml +/sdcard/android/layout_tests/fast/overflow/overflow-auto-table.html +/sdcard/android/layout_tests/fast/overflow/infiniteRecursion.html +/sdcard/android/layout_tests/fast/overflow/001.html +/sdcard/android/layout_tests/fast/overflow/hit-test-overflow-controls.html +/sdcard/android/layout_tests/fast/overflow/005.html +/sdcard/android/layout_tests/fast/overflow/007.html +/sdcard/android/layout_tests/fast/overflow/hidden-scrollbar-resize.html +/sdcard/android/layout_tests/fast/events/autoscroll.html +/sdcard/android/layout_tests/fast/events/5056619.html +/sdcard/android/layout_tests/fast/events/attempt-scroll-with-no-scrollbars.html : has expected results +/sdcard/android/layout_tests/fast/events/updateLayoutForHitTest.html +/sdcard/android/layout_tests/fast/events/label-focus.html +/sdcard/android/layout_tests/fast/events/context-onmousedown-event.html : has expected results +/sdcard/android/layout_tests/fast/events/onsubmit-bubbling.html : has expected results +/sdcard/android/layout_tests/fast/events/onloadFrameCrash.html +/sdcard/android/layout_tests/fast/events/event-listener-on-link.html +/sdcard/android/layout_tests/fast/events/keydown-1.html +/sdcard/android/layout_tests/fast/events/onload-re-entry.html +/sdcard/android/layout_tests/fast/events/standalone-image-drag-to-editable.html +/sdcard/android/layout_tests/fast/events/pointer-events.html : has expected results +/sdcard/android/layout_tests/fast/events/pointer-events-2.html : has expected results +/sdcard/android/layout_tests/fast/events/nested-window-event.html : has expected results +/sdcard/android/layout_tests/fast/events/focusingUnloadedFrame.html +/sdcard/android/layout_tests/fast/events/event-sender-mouse-moved.html +/sdcard/android/layout_tests/fast/events/mouseout-dead-node.html +/sdcard/android/layout_tests/fast/events/reveal-link-when-focused.html +/sdcard/android/layout_tests/fast/html/keygen.html +/sdcard/android/layout_tests/fast/html/link-rel-stylesheet.html +/sdcard/android/layout_tests/fast/html/listing.html +/sdcard/android/layout_tests/fast/html/marquee-scroll.html +/sdcard/android/layout_tests/fast/images/svg-as-tiled-background.html +/sdcard/android/layout_tests/fast/images/svg-as-background.html +/sdcard/android/layout_tests/fast/images/svg-as-image.html +/sdcard/android/layout_tests/fast/images/pdf-as-image-landscape.html +/sdcard/android/layout_tests/fast/images/pdf-as-tiled-background.html +/sdcard/android/layout_tests/fast/images/object-image.html +/sdcard/android/layout_tests/fast/images/pdf-as-background.html +/sdcard/android/layout_tests/fast/images/svg-as-relative-image.html +/sdcard/android/layout_tests/fast/images/imagemap-case.html +/sdcard/android/layout_tests/fast/images/pdf-as-image.html +/sdcard/android/layout_tests/fast/images/image-map-anchor-children.html +/sdcard/android/layout_tests/fast/images/embed-image.html +/sdcard/android/layout_tests/fast/images/animated-svg-as-image.html +/sdcard/android/layout_tests/fast/images/image-in-map.html +/sdcard/android/layout_tests/fast/images/animated-gif-with-offsets.html +/sdcard/android/layout_tests/fast/images/favicon-as-image.html +/sdcard/android/layout_tests/fast/images/svg-width-100p-as-background.html +/sdcard/android/layout_tests/fast/inline-block/14498-positionForCoordinates.html +/sdcard/android/layout_tests/fast/inline-block/001.html +/sdcard/android/layout_tests/fast/inline-block/002.html +/sdcard/android/layout_tests/fast/inline-block/003.html +/sdcard/android/layout_tests/fast/inline-block/004.html +/sdcard/android/layout_tests/fast/inline-block/005.html +/sdcard/android/layout_tests/fast/inline-block/contenteditable-baseline.html +/sdcard/android/layout_tests/fast/inline-block/006.html +/sdcard/android/layout_tests/fast/inline-block/inline-block-vertical-align.html +/sdcard/android/layout_tests/fast/inline-block/tricky-baseline.html +/sdcard/android/layout_tests/fast/inline-block/overflow-clip.html +/sdcard/android/layout_tests/fast/inspector/matchedrules.html +/sdcard/android/layout_tests/fast/inspector/style.html +/sdcard/android/layout_tests/fast/flexbox/001.html +/sdcard/android/layout_tests/fast/flexbox/010.html +/sdcard/android/layout_tests/fast/flexbox/020.html +/sdcard/android/layout_tests/fast/flexbox/002.html +/sdcard/android/layout_tests/fast/flexbox/011.html +/sdcard/android/layout_tests/fast/flexbox/021.html +/sdcard/android/layout_tests/fast/flexbox/003.html +/sdcard/android/layout_tests/fast/flexbox/012.html +/sdcard/android/layout_tests/fast/flexbox/022.html +/sdcard/android/layout_tests/fast/flexbox/004.html +/sdcard/android/layout_tests/fast/flexbox/013.html +/sdcard/android/layout_tests/fast/flexbox/023.html +/sdcard/android/layout_tests/fast/flexbox/005.html +/sdcard/android/layout_tests/fast/flexbox/014.html +/sdcard/android/layout_tests/fast/flexbox/015.html +/sdcard/android/layout_tests/fast/flexbox/006.html +/sdcard/android/layout_tests/fast/flexbox/024.html +/sdcard/android/layout_tests/fast/flexbox/016.html +/sdcard/android/layout_tests/fast/flexbox/007.html +/sdcard/android/layout_tests/fast/flexbox/025.html +/sdcard/android/layout_tests/fast/flexbox/008.html +/sdcard/android/layout_tests/fast/flexbox/017.html +/sdcard/android/layout_tests/fast/flexbox/026.html +/sdcard/android/layout_tests/fast/flexbox/009.html +/sdcard/android/layout_tests/fast/flexbox/018.html +/sdcard/android/layout_tests/fast/flexbox/019.html +/sdcard/android/layout_tests/fast/flexbox/flex-hang.html +/sdcard/android/layout_tests/fast/tokenizer/missing-style-end-tag-1.html +/sdcard/android/layout_tests/fast/tokenizer/002.html +/sdcard/android/layout_tests/fast/tokenizer/missing-title-end-tag-2.html +/sdcard/android/layout_tests/fast/tokenizer/script-after-frameset.html +/sdcard/android/layout_tests/fast/tokenizer/missing-style-end-tag-2.html +/sdcard/android/layout_tests/fast/tokenizer/external-script-document-write.html +/sdcard/android/layout_tests/fast/tokenizer/script_extra_close.html +/sdcard/android/layout_tests/fast/tokenizer/001.html +/sdcard/android/layout_tests/fast/tokenizer/003.html +/sdcard/android/layout_tests/fast/tokenizer/missing-title-end-tag-1.html +/sdcard/android/layout_tests/fast/tokenizer/external-script-document-write_2.html +/sdcard/android/layout_tests/fast/box-shadow/border-radius-big.html +/sdcard/android/layout_tests/fast/box-shadow/basic-shadows.html +/sdcard/android/layout_tests/fast/js/exception-linenums-in-html-3.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/001.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/002.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/003.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/004.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/005.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/006.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/007.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/008.html +/sdcard/android/layout_tests/fast/body-propagation/background-image/009.html +/sdcard/android/layout_tests/fast/body-propagation/overflow/001.html +/sdcard/android/layout_tests/fast/body-propagation/overflow/002.html +/sdcard/android/layout_tests/fast/body-propagation/overflow/003.html +/sdcard/android/layout_tests/fast/body-propagation/overflow/004.html +/sdcard/android/layout_tests/fast/body-propagation/overflow/005.html +/sdcard/android/layout_tests/fast/body-propagation/overflow/006.html +/sdcard/android/layout_tests/fast/body-propagation/overflow/007.html +/sdcard/android/layout_tests/fast/body-propagation/background-color/001.html +/sdcard/android/layout_tests/fast/body-propagation/background-color/002.html +/sdcard/android/layout_tests/fast/body-propagation/background-color/003.html +/sdcard/android/layout_tests/fast/body-propagation/background-color/004.html +/sdcard/android/layout_tests/fast/body-propagation/background-color/005.html +/sdcard/android/layout_tests/fast/body-propagation/background-color/006.html +/sdcard/android/layout_tests/fast/body-propagation/background-color/007.html +/sdcard/android/layout_tests/fast/body-propagation/background-color/008.html +/sdcard/android/layout_tests/fast/inline/continuation-outlines-with-layers.html +/sdcard/android/layout_tests/fast/inline/inline-padding-disables-text-quirk.html +/sdcard/android/layout_tests/fast/inline/emptyInlinesWithinLists.html +/sdcard/android/layout_tests/fast/inline/drawStyledEmptyInlines.html +/sdcard/android/layout_tests/fast/inline/drawStyledEmptyInlinesWithWS.html +/sdcard/android/layout_tests/fast/inline/positionedLifetime.html +/sdcard/android/layout_tests/fast/inline/dirtyLinesForInline.html +/sdcard/android/layout_tests/fast/inline/001.html +/sdcard/android/layout_tests/fast/inline/002.html +/sdcard/android/layout_tests/fast/inline/inline-text-quirk-bpm.html +/sdcard/android/layout_tests/fast/inline/inline-borders-with-bidi-override.html +/sdcard/android/layout_tests/fast/inline/styledEmptyInlinesWithBRs.html +/sdcard/android/layout_tests/fast/inline/continuation-outlines.html +/sdcard/android/layout_tests/fast/inline/outline-continuations.html +/sdcard/android/layout_tests/fast/inline/br-text-decoration.html +/sdcard/android/layout_tests/fast/inline/percentage-margins.html +/sdcard/android/layout_tests/fast/dom/HTMLTableElement/colSpan.html +/sdcard/android/layout_tests/fast/dom/HTMLTableElement/createCaption.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/frameless-location-bugzilla10837.html +/sdcard/android/layout_tests/fast/dom/Document/early-document-access.html : has expected results +/sdcard/android/layout_tests/fast/dom/Element/null-offset-parent.html +/sdcard/android/layout_tests/fast/dom/Element/class-attribute-whitespace.html +/sdcard/android/layout_tests/fast/dom/HTMLLinkElement/pending-stylesheet-count.html +/sdcard/android/layout_tests/fast/dom/HTMLStyleElement/insert-parser-generated.html +/sdcard/android/layout_tests/fast/dom/HTMLInputElement/input-image-alt-text.html +/sdcard/android/layout_tests/fast/dom/Window/timeout-released-on-close.html : has expected results +/sdcard/android/layout_tests/fast/dom/Window/open-existing-pop-up-blocking.html +/sdcard/android/layout_tests/fast/dom/Window/global-opener-function.html : has expected results +/sdcard/android/layout_tests/fast/dom/Window/window-property-shadowing.html : has expected results +/sdcard/android/layout_tests/fast/dom/Window/closure-access-after-navigation-window.html : has expected results +/sdcard/android/layout_tests/fast/dom/Window/remove-timeout-crash.html : has expected results +/sdcard/android/layout_tests/fast/dom/Window/window-special-properties.html : has expected results +/sdcard/android/layout_tests/fast/dom/Window/timeout-callback-scope.html : has expected results +/sdcard/android/layout_tests/fast/dom/Window/window-property-shadowing-name.html : has expected results +/sdcard/android/layout_tests/fast/dom/HTMLObjectElement/vspace-hspace-as-number.html +/sdcard/android/layout_tests/fast/dom/HTMLElement/bdo.html +/sdcard/android/layout_tests/fast/dom/Range/surroundContents-1.html +/sdcard/android/layout_tests/fast/dom/Range/create-contextual-fragment.html +/sdcard/android/layout_tests/fast/dom/HTMLHeadElement/textInHead1.html +/sdcard/android/layout_tests/fast/dom/HTMLHeadElement/textInHead2.html +/sdcard/android/layout_tests/fast/dom/HTMLHeadElement/textInHead3.html +/sdcard/android/layout_tests/fast/dom/HTMLHeadElement/textInHead4.html +/sdcard/android/layout_tests/fast/dom/HTMLHeadElement/textInHead5.html +/sdcard/android/layout_tests/fast/dom/HTMLHeadElement/head-link-style-href-check.html +/sdcard/android/layout_tests/fast/dom/HTMLTextAreaElement/reset-textarea.html +/sdcard/android/layout_tests/fast/dom/HTMLImageElement/image-alt-text.html +/sdcard/android/layout_tests/fast/dom/dom-parse-serialize.html +/sdcard/android/layout_tests/fast/dom/focus-contenteditable.html +/sdcard/android/layout_tests/fast/dom/jsDevicePixelRatio.html +/sdcard/android/layout_tests/fast/dom/isindex-001.html +/sdcard/android/layout_tests/fast/dom/css-cached-import-rule.html +/sdcard/android/layout_tests/fast/dom/dom-parse-serialize-display.html +/sdcard/android/layout_tests/fast/dom/css-rule-functions.html +/sdcard/android/layout_tests/fast/dom/createDocumentType.html +/sdcard/android/layout_tests/fast/dom/clientWidthAfterDocumentIsRemoved.html +/sdcard/android/layout_tests/fast/dom/css-inline-style-important.html +/sdcard/android/layout_tests/fast/dom/replaceChild.html +/sdcard/android/layout_tests/fast/dom/anchor-text.html +/sdcard/android/layout_tests/fast/dom/importNodeHTML.html +/sdcard/android/layout_tests/fast/dom/gc-10.html +/sdcard/android/layout_tests/fast/dom/inner-text.html +/sdcard/android/layout_tests/fast/dom/isindex-002.html +/sdcard/android/layout_tests/fast/dom/outerText.html +/sdcard/android/layout_tests/fast/dom/setAttributeNS.html : has expected results +/sdcard/android/layout_tests/fast/dom/anchor-toString.html : has expected results +/sdcard/android/layout_tests/fast/dom/documenturi-affects-relative-paths.html : has expected results +/sdcard/android/layout_tests/fast/dom/setAttribute-using-initial-input-value.html : has expected results +/sdcard/android/layout_tests/fast/dom/blur-contenteditable.html +/sdcard/android/layout_tests/fast/dom/setPrimitiveValue.html +/sdcard/android/layout_tests/fast/dom/delete-contents.html +/sdcard/android/layout_tests/fast/dom/children-nodes.html +/sdcard/android/layout_tests/fast/dom/css-mediarule-deleteRule-update.html +/sdcard/android/layout_tests/fast/dom/attr_dead_doc.html +/sdcard/android/layout_tests/fast/dom/clone-contents-0-end-offset.html +/sdcard/android/layout_tests/fast/dom/comment-not-documentElement.html +/sdcard/android/layout_tests/fast/dom/clone-node-dynamic-style.html +/sdcard/android/layout_tests/fast/dom/css-mediarule-insertRule-update.html +/sdcard/android/layout_tests/fast/dom/set-frame-src-while-running-script-in-frame.html : has expected results +/sdcard/android/layout_tests/fast/dom/stripNullFromTextNodes.html +/sdcard/android/layout_tests/fast/dom/null-document-location-put-crash.html : has expected results +/sdcard/android/layout_tests/fast/dom/document-scripts.html : has expected results +/sdcard/android/layout_tests/fast/invalid/test-case-tr-th-td-should-not-close-dl-list.html : has expected results +/sdcard/android/layout_tests/fast/invalid/table-inside-stray-table-content.html +/sdcard/android/layout_tests/fast/invalid/010.html +/sdcard/android/layout_tests/fast/invalid/002.html +/sdcard/android/layout_tests/fast/invalid/012.html +/sdcard/android/layout_tests/fast/invalid/004.html +/sdcard/android/layout_tests/fast/invalid/014.html +/sdcard/android/layout_tests/fast/invalid/006.html +/sdcard/android/layout_tests/fast/invalid/016.html +/sdcard/android/layout_tests/fast/invalid/008.html +/sdcard/android/layout_tests/fast/invalid/018.html +/sdcard/android/layout_tests/fast/invalid/junk-data.xml +/sdcard/android/layout_tests/fast/invalid/missing-dl-end-tag.html +/sdcard/android/layout_tests/fast/invalid/td-inside-object.html +/sdcard/android/layout_tests/fast/invalid/table-residual-style-crash.html +/sdcard/android/layout_tests/fast/invalid/missing-font-end-tag.html +/sdcard/android/layout_tests/fast/invalid/missing-dt-end-tag.html +/sdcard/android/layout_tests/fast/invalid/020.xml +/sdcard/android/layout_tests/fast/invalid/001.html +/sdcard/android/layout_tests/fast/invalid/nestedh3s.html +/sdcard/android/layout_tests/fast/invalid/011.html +/sdcard/android/layout_tests/fast/invalid/003.html +/sdcard/android/layout_tests/fast/invalid/021.html +/sdcard/android/layout_tests/fast/invalid/013.html +/sdcard/android/layout_tests/fast/invalid/005.html +/sdcard/android/layout_tests/fast/invalid/015.html +/sdcard/android/layout_tests/fast/invalid/007.html +/sdcard/android/layout_tests/fast/invalid/residual-style.html +/sdcard/android/layout_tests/fast/invalid/017.html +/sdcard/android/layout_tests/fast/invalid/009.html +/sdcard/android/layout_tests/fast/invalid/missing-address-end-tag.html +/sdcard/android/layout_tests/fast/invalid/019.html +/sdcard/android/layout_tests/fast/forms/input-width.html +/sdcard/android/layout_tests/fast/forms/select-item-background-clip.html +/sdcard/android/layout_tests/fast/forms/radio-nested-labels.html +/sdcard/android/layout_tests/fast/forms/thumbslider-crash.html +/sdcard/android/layout_tests/fast/forms/input-first-letter.html +/sdcard/android/layout_tests/fast/forms/input-appearance-preventDefault.html +/sdcard/android/layout_tests/fast/forms/plaintext-mode-2.html +/sdcard/android/layout_tests/fast/forms/input-double-click-selection-gap-bug.html +/sdcard/android/layout_tests/fast/forms/preserveFormDuringResidualStyle.html +/sdcard/android/layout_tests/fast/forms/select-change-popup-to-listbox.html +/sdcard/android/layout_tests/fast/forms/input-text-maxlength.html +/sdcard/android/layout_tests/fast/forms/blankbuttons.html +/sdcard/android/layout_tests/fast/forms/password-placeholder-text-security.html +/sdcard/android/layout_tests/fast/forms/HTMLOptionElement_label05.html +/sdcard/android/layout_tests/fast/forms/visual-hebrew-text-field.html +/sdcard/android/layout_tests/fast/forms/textarea-trailing-newline.html : has expected results +/sdcard/android/layout_tests/fast/forms/legend-access-key.html : has expected results +/sdcard/android/layout_tests/fast/forms/textfield-overflow.html +/sdcard/android/layout_tests/fast/forms/005.html +/sdcard/android/layout_tests/fast/forms/HTMLOptionElement_label02.html +/sdcard/android/layout_tests/fast/forms/file-input-disabled.html +/sdcard/android/layout_tests/fast/forms/input-appearance-visibility.html +/sdcard/android/layout_tests/fast/forms/select-disabled-appearance.html +/sdcard/android/layout_tests/fast/forms/input-type-change2.html +/sdcard/android/layout_tests/fast/forms/select-block-background.html +/sdcard/android/layout_tests/fast/forms/file-input-direction.html +/sdcard/android/layout_tests/fast/forms/select-visual-hebrew.html +/sdcard/android/layout_tests/fast/forms/select-change-listbox-size.html +/sdcard/android/layout_tests/fast/forms/002.html +/sdcard/android/layout_tests/fast/forms/textarea-align.html +/sdcard/android/layout_tests/fast/forms/control-restrict-line-height.html +/sdcard/android/layout_tests/fast/forms/textAreaLineHeight.html +/sdcard/android/layout_tests/fast/forms/button-generated-content.html +/sdcard/android/layout_tests/fast/forms/option-text-clip.html +/sdcard/android/layout_tests/fast/forms/textfield-drag-into-disabled.html +/sdcard/android/layout_tests/fast/forms/input-text-paste-maxlength.html +/sdcard/android/layout_tests/fast/forms/tabs-with-modifiers.html : has expected results +/sdcard/android/layout_tests/fast/forms/saved-state-adoptNode-crash.html : has expected results +/sdcard/android/layout_tests/fast/forms/input-readonly-autoscroll.html +/sdcard/android/layout_tests/fast/forms/thumbslider-no-parent-slider.html +/sdcard/android/layout_tests/fast/forms/textfield-outline.html +/sdcard/android/layout_tests/fast/forms/button-text-transform.html +/sdcard/android/layout_tests/fast/forms/radio-check-click-and-drag.html : has expected results +/sdcard/android/layout_tests/fast/forms/textarea-scroll-height.html +/sdcard/android/layout_tests/fast/forms/button-table-styles.html +/sdcard/android/layout_tests/fast/forms/textarea-setinnerhtml.html +/sdcard/android/layout_tests/fast/forms/input-align.html +/sdcard/android/layout_tests/fast/forms/box-shadow-override.html +/sdcard/android/layout_tests/fast/forms/button-cannot-be-nested.html +/sdcard/android/layout_tests/fast/forms/input-type-change.html +/sdcard/android/layout_tests/fast/forms/checkbox-radio-onchange.html +/sdcard/android/layout_tests/fast/forms/input-spaces.html +/sdcard/android/layout_tests/fast/forms/dragging-to-file-input.html : has expected results +/sdcard/android/layout_tests/fast/forms/menulist-option-wrap.html +/sdcard/android/layout_tests/fast/forms/float-before-fieldset.html +/sdcard/android/layout_tests/fast/forms/radio_checked.html +/sdcard/android/layout_tests/fast/forms/minWidthPercent.html +/sdcard/android/layout_tests/fast/forms/form-post-urlencoded.html : has expected results +/sdcard/android/layout_tests/fast/forms/input-value.html +/sdcard/android/layout_tests/fast/forms/HTMLOptionElement_label06.html +/sdcard/android/layout_tests/fast/forms/placeholder-pseudo-style.html +/sdcard/android/layout_tests/fast/forms/menulist-width-change.html +/sdcard/android/layout_tests/fast/forms/option-strip-whitespace.html +/sdcard/android/layout_tests/fast/forms/input-text-drag-down.html +/sdcard/android/layout_tests/fast/forms/select-selected.html +/sdcard/android/layout_tests/fast/forms/006.html +/sdcard/android/layout_tests/fast/forms/control-clip-overflow.html +/sdcard/android/layout_tests/fast/forms/input-appearance-default-bkcolor.html +/sdcard/android/layout_tests/fast/forms/HTMLOptionElement_label03.html +/sdcard/android/layout_tests/fast/forms/003.html +/sdcard/android/layout_tests/fast/forms/button-default-title.html +/sdcard/android/layout_tests/fast/forms/hidden-listbox.html +/sdcard/android/layout_tests/fast/forms/input-no-renderer.html +/sdcard/android/layout_tests/fast/forms/input-text-click-outside.html +/sdcard/android/layout_tests/fast/forms/input-baseline.html +/sdcard/android/layout_tests/fast/forms/targeted-frame-submission.html +/sdcard/android/layout_tests/fast/forms/input-table.html +/sdcard/android/layout_tests/fast/forms/select-change-listbox-to-popup.html +/sdcard/android/layout_tests/fast/forms/select-align.html +/sdcard/android/layout_tests/fast/forms/radio_checked_dynamic.html +/sdcard/android/layout_tests/fast/forms/select-writing-direction-natural.html +/sdcard/android/layout_tests/fast/forms/hidden-input-file.html +/sdcard/android/layout_tests/fast/forms/menulist-deselect-update.html +/sdcard/android/layout_tests/fast/forms/button-sizes.html +/sdcard/android/layout_tests/fast/forms/slider-thumb-stylability.html +/sdcard/android/layout_tests/fast/forms/input-readonly-dimmed.html +/sdcard/android/layout_tests/fast/forms/input-appearance-width.html +/sdcard/android/layout_tests/fast/forms/listbox-scrollbar-incremental-load.html +/sdcard/android/layout_tests/fast/forms/password-placeholder.html +/sdcard/android/layout_tests/fast/forms/select-list-box-with-height.html +/sdcard/android/layout_tests/fast/forms/button-align.html +/sdcard/android/layout_tests/fast/forms/textarea-rows-cols.html +/sdcard/android/layout_tests/fast/forms/listbox-deselect-scroll.html +/sdcard/android/layout_tests/fast/forms/input-appearance-readonly.html +/sdcard/android/layout_tests/fast/forms/select-initial-position.html +/sdcard/android/layout_tests/fast/forms/menulist-no-overflow.html +/sdcard/android/layout_tests/fast/forms/formmove2.html +/sdcard/android/layout_tests/fast/forms/placeholder-set-attribute.html +/sdcard/android/layout_tests/fast/forms/radio-attr-order.html +/sdcard/android/layout_tests/fast/forms/input-disabled-color.html +/sdcard/android/layout_tests/fast/forms/fieldset-align.html +/sdcard/android/layout_tests/fast/forms/select-baseline.html +/sdcard/android/layout_tests/fast/forms/input-text-word-wrap.html +/sdcard/android/layout_tests/fast/forms/stuff-on-my-optgroup.html +/sdcard/android/layout_tests/fast/forms/listbox-selection-2.html +/sdcard/android/layout_tests/fast/forms/input-readonly-empty.html +/sdcard/android/layout_tests/fast/forms/input-align-image.html +/sdcard/android/layout_tests/fast/forms/input-selection-hidden.html : has expected results +/sdcard/android/layout_tests/fast/forms/option-index.html +/sdcard/android/layout_tests/fast/forms/indeterminate.html +/sdcard/android/layout_tests/fast/forms/negativeLineHeight.html +/sdcard/android/layout_tests/fast/forms/007.html +/sdcard/android/layout_tests/fast/forms/HTMLOptionElement_label04.html +/sdcard/android/layout_tests/fast/forms/select-style.html +/sdcard/android/layout_tests/fast/forms/select-size.html +/sdcard/android/layout_tests/fast/forms/input-appearance-disabled.html +/sdcard/android/layout_tests/fast/forms/input-appearance-height.html +/sdcard/android/layout_tests/fast/forms/004.html +/sdcard/android/layout_tests/fast/forms/menulist-separator-painting.html +/sdcard/android/layout_tests/fast/forms/HTMLOptionElement_label01.html +/sdcard/android/layout_tests/fast/forms/fieldset-with-float.html +/sdcard/android/layout_tests/fast/forms/search-placeholder-value-changed.html +/sdcard/android/layout_tests/fast/forms/input-field-text-truncated.html +/sdcard/android/layout_tests/fast/forms/floating-textfield-relayout.html +/sdcard/android/layout_tests/fast/forms/add-remove-form-elements-stress-test.html : has expected results +/sdcard/android/layout_tests/fast/forms/button-inner-block-reuse.html +/sdcard/android/layout_tests/fast/forms/input-type-text-min-width.html +/sdcard/android/layout_tests/fast/forms/onchange-enter-submit.html : has expected results +/sdcard/android/layout_tests/fast/forms/slider-thumb-shared-style.html +/sdcard/android/layout_tests/fast/forms/option-script.html +/sdcard/android/layout_tests/fast/forms/input-paste-undo.html +/sdcard/android/layout_tests/fast/forms/input-text-click-inside.html +/sdcard/android/layout_tests/fast/forms/input-appearance-selection.html +/sdcard/android/layout_tests/fast/forms/button-white-space.html +/sdcard/android/layout_tests/fast/forms/menulist-narrow-width.html +/sdcard/android/layout_tests/fast/forms/slider-padding.html +/sdcard/android/layout_tests/fast/forms/menulist-restrict-line-height.html +/sdcard/android/layout_tests/fast/forms/textarea-width.html +/sdcard/android/layout_tests/fast/forms/input-text-double-click.html +/sdcard/android/layout_tests/fast/forms/button-submit.html +/sdcard/android/layout_tests/fast/forms/disabled-select-change-index.html +/sdcard/android/layout_tests/fast/forms/formmove3.html +/sdcard/android/layout_tests/fast/forms/listbox-width-change.html +/sdcard/android/layout_tests/fast/forms/input-text-self-emptying-click.html +/sdcard/android/layout_tests/fast/forms/input-appearance-bkcolor.html +/sdcard/android/layout_tests/fast/forms/button-positioned.html +/sdcard/android/layout_tests/fast/forms/search-transformed.html +/sdcard/android/layout_tests/fast/forms/image-border.html +/sdcard/android/layout_tests/fast/forms/encoding-test.html +/sdcard/android/layout_tests/fast/forms/input-type-change-in-onfocus-mouse.html : has expected results +/sdcard/android/layout_tests/fast/compact/001.html +/sdcard/android/layout_tests/fast/compact/002.html +/sdcard/android/layout_tests/fast/compact/003.html +/sdcard/android/layout_tests/fast/clip/nestedTransparencyClip.html +/sdcard/android/layout_tests/fast/clip/outline-overflowClip.html +/sdcard/android/layout_tests/fast/clip/001.html +/sdcard/android/layout_tests/fast/clip/010.html +/sdcard/android/layout_tests/fast/clip/002.html +/sdcard/android/layout_tests/fast/clip/011.html +/sdcard/android/layout_tests/fast/clip/003.html +/sdcard/android/layout_tests/fast/clip/012.html +/sdcard/android/layout_tests/fast/clip/004.html +/sdcard/android/layout_tests/fast/clip/013.html +/sdcard/android/layout_tests/fast/clip/005.html +/sdcard/android/layout_tests/fast/clip/014.html +/sdcard/android/layout_tests/fast/clip/006.html +/sdcard/android/layout_tests/fast/clip/015.html +/sdcard/android/layout_tests/fast/clip/007.html +/sdcard/android/layout_tests/fast/clip/016.html +/sdcard/android/layout_tests/fast/clip/008.html +/sdcard/android/layout_tests/fast/clip/017.html +/sdcard/android/layout_tests/fast/clip/009.html +/sdcard/android/layout_tests/fast/table/border-collapsing/001.html +/sdcard/android/layout_tests/fast/table/border-collapsing/002.html +/sdcard/android/layout_tests/fast/table/border-collapsing/003.html +/sdcard/android/layout_tests/fast/table/border-collapsing/004.html +/sdcard/android/layout_tests/fast/table/border-collapsing/equal-precedence-resolution.html +/sdcard/android/layout_tests/fast/table/border-collapsing/rtl-border-collapsing.html +/sdcard/android/layout_tests/fast/table/border-collapsing/border-collapsing-head-foot.html +/sdcard/android/layout_tests/fast/table/fixed-nested.html +/sdcard/android/layout_tests/fast/table/frame-and-rules.html +/sdcard/android/layout_tests/fast/table/empty-table-percent-height.html +/sdcard/android/layout_tests/fast/table/100-percent-cell-width.html +/sdcard/android/layout_tests/fast/table/stale-grid-crash.html +/sdcard/android/layout_tests/fast/table/div-as-col-span.html +/sdcard/android/layout_tests/fast/table/nobr.html +/sdcard/android/layout_tests/fast/table/012.html +/sdcard/android/layout_tests/fast/table/040.html +/sdcard/android/layout_tests/fast/table/growCellForImageQuirk.html +/sdcard/android/layout_tests/fast/table/024.html +/sdcard/android/layout_tests/fast/table/cell-pref-width-invalidation.html +/sdcard/android/layout_tests/fast/table/008.html +/sdcard/android/layout_tests/fast/table/036.html +/sdcard/android/layout_tests/fast/table/nested-percent-height-table.html +/sdcard/android/layout_tests/fast/table/rules-attr-dynchange1.html +/sdcard/android/layout_tests/fast/table/wide-column.html +/sdcard/android/layout_tests/fast/table/fixed-with-auto-with-colspan.html +/sdcard/android/layout_tests/fast/table/percent-heights.html +/sdcard/android/layout_tests/fast/table/021.html +/sdcard/android/layout_tests/fast/table/colspanMinWidth.html +/sdcard/android/layout_tests/fast/table/005.html +/sdcard/android/layout_tests/fast/table/033.html +/sdcard/android/layout_tests/fast/table/017.html +/sdcard/android/layout_tests/fast/table/floatingTablePaintBackground.html +/sdcard/android/layout_tests/fast/table/029.html +/sdcard/android/layout_tests/fast/table/cell-absolute-child.html +/sdcard/android/layout_tests/fast/table/click-near-anonymous-table.html +/sdcard/android/layout_tests/fast/table/auto-with-percent-height.html +/sdcard/android/layout_tests/fast/table/insert-before-anonymous-ancestors.html +/sdcard/android/layout_tests/fast/table/append-cells2.html +/sdcard/android/layout_tests/fast/table/unused-percent-heights.html +/sdcard/android/layout_tests/fast/table/max-width-integer-overflow.html +/sdcard/android/layout_tests/fast/table/vertical-align-baseline-readjust.html +/sdcard/android/layout_tests/fast/table/empty-row-crash.html +/sdcard/android/layout_tests/fast/table/002.html +/sdcard/android/layout_tests/fast/table/030.html +/sdcard/android/layout_tests/fast/table/cell-width-auto.html +/sdcard/android/layout_tests/fast/table/014.html +/sdcard/android/layout_tests/fast/table/037.xml +/sdcard/android/layout_tests/fast/table/large-width.html +/sdcard/android/layout_tests/fast/table/026.html +/sdcard/android/layout_tests/fast/table/unbreakable-images-quirk.html +/sdcard/android/layout_tests/fast/table/038.html +/sdcard/android/layout_tests/fast/table/dynamic-cellpadding.html +/sdcard/android/layout_tests/fast/table/generated-caption.html +/sdcard/android/layout_tests/fast/table/empty-cells.html +/sdcard/android/layout_tests/fast/table/add-before-anonymous-child.html +/sdcard/android/layout_tests/fast/table/011.html +/sdcard/android/layout_tests/fast/table/table-display-types-strict.html +/sdcard/android/layout_tests/fast/table/023.html +/sdcard/android/layout_tests/fast/table/007.html +/sdcard/android/layout_tests/fast/table/cellindex.html +/sdcard/android/layout_tests/fast/table/035.html +/sdcard/android/layout_tests/fast/table/colgroup-spanning-groups-rules.html +/sdcard/android/layout_tests/fast/table/insert-row-before-form.html +/sdcard/android/layout_tests/fast/table/rowspan-paint-order.html +/sdcard/android/layout_tests/fast/table/rtl-cell-display-none-assert.html +/sdcard/android/layout_tests/fast/table/insert-cell-before-form.html +/sdcard/android/layout_tests/fast/table/replaced-percent-height.html +/sdcard/android/layout_tests/fast/table/text-field-baseline.html +/sdcard/android/layout_tests/fast/table/table-display-types.html +/sdcard/android/layout_tests/fast/table/table-hspace-align-center.html +/sdcard/android/layout_tests/fast/table/caption-relayout.html +/sdcard/android/layout_tests/fast/table/020.html +/sdcard/android/layout_tests/fast/table/fixed-table-non-cell-in-row.html +/sdcard/android/layout_tests/fast/table/004.html +/sdcard/android/layout_tests/fast/table/032.html +/sdcard/android/layout_tests/fast/table/row-height-recalc.html +/sdcard/android/layout_tests/fast/table/016.html +/sdcard/android/layout_tests/fast/table/absolute-table-at-bottom.html +/sdcard/android/layout_tests/fast/table/028.html +/sdcard/android/layout_tests/fast/table/spanOverlapRepaint.html +/sdcard/android/layout_tests/fast/table/invisible-cell-background.html +/sdcard/android/layout_tests/fast/table/vertical-align-baseline.html +/sdcard/android/layout_tests/fast/table/wide-colspan.html +/sdcard/android/layout_tests/fast/table/rowindex.html +/sdcard/android/layout_tests/fast/table/001.html +/sdcard/android/layout_tests/fast/table/remove-td-display-none.html +/sdcard/android/layout_tests/fast/table/013.html +/sdcard/android/layout_tests/fast/table/041.html +/sdcard/android/layout_tests/fast/table/colgroup-preceded-by-caption.html +/sdcard/android/layout_tests/fast/table/025.html +/sdcard/android/layout_tests/fast/table/giantCellspacing.html +/sdcard/android/layout_tests/fast/table/009.html +/sdcard/android/layout_tests/fast/table/edge-offsets.html +/sdcard/android/layout_tests/fast/table/giantRowspan.html +/sdcard/android/layout_tests/fast/table/010.html +/sdcard/android/layout_tests/fast/table/inline-form-assert.html +/sdcard/android/layout_tests/fast/table/overflowHidden.html +/sdcard/android/layout_tests/fast/table/rules-attr-dynchange2.html +/sdcard/android/layout_tests/fast/table/height-percent-test.html +/sdcard/android/layout_tests/fast/table/multiple-percent-height-rows.html +/sdcard/android/layout_tests/fast/table/giantRowspan2.html +/sdcard/android/layout_tests/fast/table/tableInsideCaption.html +/sdcard/android/layout_tests/fast/table/022.html +/sdcard/android/layout_tests/fast/table/006.html +/sdcard/android/layout_tests/fast/table/034.html +/sdcard/android/layout_tests/fast/table/append-cells.html +/sdcard/android/layout_tests/fast/table/018.html +/sdcard/android/layout_tests/fast/table/percent-widths-stretch.html +/sdcard/android/layout_tests/fast/table/prepend-in-anonymous-table.html +/sdcard/android/layout_tests/fast/table/floating-th.html +/sdcard/android/layout_tests/fast/table/empty-section-crash.html +/sdcard/android/layout_tests/fast/table/form-with-table-style.html +/sdcard/android/layout_tests/fast/table/003.html +/sdcard/android/layout_tests/fast/table/031.html +/sdcard/android/layout_tests/fast/table/015.html +/sdcard/android/layout_tests/fast/table/027.html +/sdcard/android/layout_tests/fast/table/039.html +/sdcard/android/layout_tests/fast/css/counters/invalidate-cached-counter-node.html +/sdcard/android/layout_tests/fast/css/counters/counter-text-security.html +/sdcard/android/layout_tests/fast/css/counters/counter-text-transform.html +/sdcard/android/layout_tests/fast/css/variables/multiple-term-test.html +/sdcard/android/layout_tests/fast/css/variables/colors-test.html +/sdcard/android/layout_tests/fast/css/variables/font-test.html +/sdcard/android/layout_tests/fast/css/variables/multiple-blocks-test.html +/sdcard/android/layout_tests/fast/css/variables/misplaced-variables-test.html +/sdcard/android/layout_tests/fast/css/variables/invalid-variable-test.html +/sdcard/android/layout_tests/fast/css/variables/misplaced-import-test.html +/sdcard/android/layout_tests/fast/css/variables/import-test.html +/sdcard/android/layout_tests/fast/css/variables/inline-style-test.html +/sdcard/android/layout_tests/fast/css/variables/declaration-block-test.html +/sdcard/android/layout_tests/fast/css/variables/margin-test.html +/sdcard/android/layout_tests/fast/css/variables/set-variable-test.html +/sdcard/android/layout_tests/fast/css/variables/override-test.html +/sdcard/android/layout_tests/fast/css/variables/remove-variable-test.html +/sdcard/android/layout_tests/fast/css/variables/variable-iteration-test.html +/sdcard/android/layout_tests/fast/css/variables/image-test.html +/sdcard/android/layout_tests/fast/css/variables/block-cycle-test.html +/sdcard/android/layout_tests/fast/css/variables/shorthand-test.html +/sdcard/android/layout_tests/fast/css/variables/print-test.html +/sdcard/android/layout_tests/fast/css/namespaces/001.xml +/sdcard/android/layout_tests/fast/css/namespaces/002.xml +/sdcard/android/layout_tests/fast/css/namespaces/003.xml +/sdcard/android/layout_tests/fast/css/namespaces/004.xml +/sdcard/android/layout_tests/fast/css/namespaces/005.xml +/sdcard/android/layout_tests/fast/css/namespaces/006.xml +/sdcard/android/layout_tests/fast/css/namespaces/007.xml +/sdcard/android/layout_tests/fast/css/font-face-in-media-rule.html +/sdcard/android/layout_tests/fast/css/font-face-default-font.html +/sdcard/android/layout_tests/fast/css/first-letter-float-after-float.html +/sdcard/android/layout_tests/fast/css/invalidation-errors-2.html +/sdcard/android/layout_tests/fast/css/line-height-negative.html +/sdcard/android/layout_tests/fast/css/only-child-pseudo-class.html +/sdcard/android/layout_tests/fast/css/008.html +/sdcard/android/layout_tests/fast/css/first-of-type-pseudo-class.html +/sdcard/android/layout_tests/fast/css/ZeroOpacityLayers2.html +/sdcard/android/layout_tests/fast/css/target-fragment-match.html +/sdcard/android/layout_tests/fast/css/marginComputedStyle.html +/sdcard/android/layout_tests/fast/css/live-cssrules.html +/sdcard/android/layout_tests/fast/css/zoom-font-size.html +/sdcard/android/layout_tests/fast/css/005.html +/sdcard/android/layout_tests/fast/css/first-letter-hover.html +/sdcard/android/layout_tests/fast/css/color-quirk.html +/sdcard/android/layout_tests/fast/css/resize-corner-tracking-transformed.html +/sdcard/android/layout_tests/fast/css/selector-set-attribute.html +/sdcard/android/layout_tests/fast/css/attribute-selector-empty-value.html +/sdcard/android/layout_tests/fast/css/line-height-overflow.html +/sdcard/android/layout_tests/fast/css/002.html +/sdcard/android/layout_tests/fast/css/empty-generated-content.html +/sdcard/android/layout_tests/fast/css/background-image-with-baseurl.html +/sdcard/android/layout_tests/fast/css/border-radius-outline-offset.html +/sdcard/android/layout_tests/fast/css/hsla-color.html +/sdcard/android/layout_tests/fast/css/first-letter-skip-out-of-flow.html +/sdcard/android/layout_tests/fast/css/font-face-multiple-remote-sources.html +/sdcard/android/layout_tests/fast/css/hover-subselector.html +/sdcard/android/layout_tests/fast/css/text-align.html : has expected results +/sdcard/android/layout_tests/fast/css/margin-bottom-form-element-strict.html +/sdcard/android/layout_tests/fast/css/shadow-multiple.html +/sdcard/android/layout_tests/fast/css/import_with_baseurl.html +/sdcard/android/layout_tests/fast/css/list-outline.html +/sdcard/android/layout_tests/fast/css/apple-prefix.html +/sdcard/android/layout_tests/fast/css/line-height.html +/sdcard/android/layout_tests/fast/css/first-letter-visibility.html +/sdcard/android/layout_tests/fast/css/acid2.html +/sdcard/android/layout_tests/fast/css/font_property_normal.html +/sdcard/android/layout_tests/fast/css/css-imports.html +/sdcard/android/layout_tests/fast/css/last-of-type-pseudo-class.html +/sdcard/android/layout_tests/fast/css/last-child-pseudo-class.html +/sdcard/android/layout_tests/fast/css/visibility-hit-test.html +/sdcard/android/layout_tests/fast/css/absolute-poition-in-rtl-parent.html +/sdcard/android/layout_tests/fast/css/content-dynamic.html +/sdcard/android/layout_tests/fast/css/acid2-pixel.html +/sdcard/android/layout_tests/fast/css/transition-color-unspecified.html +/sdcard/android/layout_tests/fast/css/table-text-align-strict.html +/sdcard/android/layout_tests/fast/css/transform-default-parameter.html +/sdcard/android/layout_tests/fast/css/contentImage.html +/sdcard/android/layout_tests/fast/css/value-list-out-of-bounds-crash.html +/sdcard/android/layout_tests/fast/css/color-strict.html +/sdcard/android/layout_tests/fast/css/ignore-text-zoom.html +/sdcard/android/layout_tests/fast/css/max-height-none.html +/sdcard/android/layout_tests/fast/css/invalidation-errors-3.html +/sdcard/android/layout_tests/fast/css/empty-pseudo-class.html +/sdcard/android/layout_tests/fast/css/begin-end-contain-selector-empty-value.html +/sdcard/android/layout_tests/fast/css/find-next-layer.html +/sdcard/android/layout_tests/fast/css/contentDiv.html +/sdcard/android/layout_tests/fast/css/invalid-pseudo-classes.html +/sdcard/android/layout_tests/fast/css/disabled-author-styles.html +/sdcard/android/layout_tests/fast/css/text-security.html +/sdcard/android/layout_tests/fast/css/font-weight-1.html +/sdcard/android/layout_tests/fast/css/margin-bottom-form-element-quirk.html +/sdcard/android/layout_tests/fast/css/font-shorthand-weight-only.html +/sdcard/android/layout_tests/fast/css/006.html +/sdcard/android/layout_tests/fast/css/fieldset-display-row.html +/sdcard/android/layout_tests/fast/css/border-height.html +/sdcard/android/layout_tests/fast/css/css2-system-fonts.html +/sdcard/android/layout_tests/fast/css/imageTileOpacity.html +/sdcard/android/layout_tests/fast/css/font-face-remote.html +/sdcard/android/layout_tests/fast/css/003.html +/sdcard/android/layout_tests/fast/css/error-in-last-decl.html +/sdcard/android/layout_tests/fast/css/zoom-property-parsing.html +/sdcard/android/layout_tests/fast/css/style-outside-head.html +/sdcard/android/layout_tests/fast/css/first-letter-capitalized.html +/sdcard/android/layout_tests/fast/css/word-space-extra.html +/sdcard/android/layout_tests/fast/css/first-letter-float.html +/sdcard/android/layout_tests/fast/css/simple-selector-chain-parsing.html +/sdcard/android/layout_tests/fast/css/xml-stylesheet-pi-not-in-prolog.xml +/sdcard/android/layout_tests/fast/css/continuationCrash.html +/sdcard/android/layout_tests/fast/css/vertical-align-lengths.html +/sdcard/android/layout_tests/fast/css/first-child-pseudo-class.html +/sdcard/android/layout_tests/fast/css/getFloatValueForUnit.html +/sdcard/android/layout_tests/fast/css/first-letter-detach.html +/sdcard/android/layout_tests/fast/css/line-height-font-order.html +/sdcard/android/layout_tests/fast/css/font-face-unicode-range.html +/sdcard/android/layout_tests/fast/css/layerZOrderCrash.html +/sdcard/android/layout_tests/fast/css/007.html +/sdcard/android/layout_tests/fast/css/import-rule-regression-11590.html +/sdcard/android/layout_tests/fast/css/last-child-style-sharing.html +/sdcard/android/layout_tests/fast/css/css3-modsel-22.html +/sdcard/android/layout_tests/fast/css/ex-after-font-variant.html +/sdcard/android/layout_tests/fast/css/quirk-orphaned-units.html +/sdcard/android/layout_tests/fast/css/outline-auto-location.html +/sdcard/android/layout_tests/fast/css/margin-top-bottom-dynamic.html +/sdcard/android/layout_tests/fast/css/font-face-descriptor-multiple-values.html +/sdcard/android/layout_tests/fast/css/empty-body-test.html +/sdcard/android/layout_tests/fast/css/link-outside-head.html +/sdcard/android/layout_tests/fast/css/font-size-negative.html +/sdcard/android/layout_tests/fast/css/position-negative-top-margin.html +/sdcard/android/layout_tests/fast/css/invalid-percentage-property.html : has expected results +/sdcard/android/layout_tests/fast/css/ZeroOpacityLayers.html +/sdcard/android/layout_tests/fast/css/only-of-type-pseudo-class.html +/sdcard/android/layout_tests/fast/css/004.html +/sdcard/android/layout_tests/fast/css/rtl-ordering.html +/sdcard/android/layout_tests/fast/css/affected-by-hover-after-style-change.html +/sdcard/android/layout_tests/fast/css/resize-corner-tracking.html +/sdcard/android/layout_tests/fast/css/background-shorthand-invalid-url.html +/sdcard/android/layout_tests/fast/css/invalidation-errors.html +/sdcard/android/layout_tests/fast/css/MarqueeLayoutTest.html +/sdcard/android/layout_tests/fast/css/textCapitalizeEdgeCases.html +/sdcard/android/layout_tests/fast/css/001.html +/sdcard/android/layout_tests/fast/css/hsl-color.html +/sdcard/android/layout_tests/fast/css/first-letter-recalculation.html +/sdcard/android/layout_tests/fast/css/inline-properties-important.html +/sdcard/android/layout_tests/fast/css/dynamic-sibling-selector.html +/sdcard/android/layout_tests/fast/css/table-text-align-quirk.html +/sdcard/android/layout_tests/fast/css/outline-auto-empty-rects.html +/sdcard/android/layout_tests/fast/css/font-face-multiple-faces.html +/sdcard/android/layout_tests/fast/css/rgb-float.html +/sdcard/android/layout_tests/fast/css/pendingStylesheetFontSize.html +/sdcard/android/layout_tests/fast/css/contentDivWithChildren.html +/sdcard/android/layout_tests/fast/css/universal-hover-quirk.html +/sdcard/android/layout_tests/fast/css/css3-nth-child.html +/sdcard/android/layout_tests/fast/css/style-parsed-outside-head.html +/sdcard/android/layout_tests/fast/css/percentage-non-integer.html +/sdcard/android/layout_tests/fast/css/negative-nth-child.html +/sdcard/android/layout_tests/fast/box-sizing/panels-one.html +/sdcard/android/layout_tests/fast/box-sizing/percentage-height.html +/sdcard/android/layout_tests/fast/box-sizing/box-sizing.html +/sdcard/android/layout_tests/fast/box-sizing/panels-two.html +/sdcard/android/layout_tests/fast/block/basic/minheight.html +/sdcard/android/layout_tests/fast/block/basic/min-pref-width-nowrap-floats.html +/sdcard/android/layout_tests/fast/block/basic/fieldset-stretch-to-legend.html +/sdcard/android/layout_tests/fast/block/basic/white-space-pre-wraps.html +/sdcard/android/layout_tests/fast/block/basic/adding-near-anonymous-block.html +/sdcard/android/layout_tests/fast/block/basic/quirk-percent-height-grandchild.html +/sdcard/android/layout_tests/fast/block/basic/001.html +/sdcard/android/layout_tests/fast/block/basic/010.html +/sdcard/android/layout_tests/fast/block/basic/quirk-height.html +/sdcard/android/layout_tests/fast/block/basic/020.html +/sdcard/android/layout_tests/fast/block/basic/002.html +/sdcard/android/layout_tests/fast/block/basic/011.html +/sdcard/android/layout_tests/fast/block/basic/text-indent-rtl.html +/sdcard/android/layout_tests/fast/block/basic/021.html +/sdcard/android/layout_tests/fast/block/basic/003.html +/sdcard/android/layout_tests/fast/block/basic/012.html +/sdcard/android/layout_tests/fast/block/basic/013.html +/sdcard/android/layout_tests/fast/block/basic/004.html +/sdcard/android/layout_tests/fast/block/basic/014.html +/sdcard/android/layout_tests/fast/block/basic/005.html +/sdcard/android/layout_tests/fast/block/basic/015.html +/sdcard/android/layout_tests/fast/block/basic/006.html +/sdcard/android/layout_tests/fast/block/basic/016.html +/sdcard/android/layout_tests/fast/block/basic/007.html +/sdcard/android/layout_tests/fast/block/basic/008.html +/sdcard/android/layout_tests/fast/block/basic/009.html +/sdcard/android/layout_tests/fast/block/basic/018.html +/sdcard/android/layout_tests/fast/block/basic/019.html +/sdcard/android/layout_tests/fast/block/positioning/auto/001.html +/sdcard/android/layout_tests/fast/block/positioning/auto/002.html +/sdcard/android/layout_tests/fast/block/positioning/auto/003.html +/sdcard/android/layout_tests/fast/block/positioning/auto/004.html +/sdcard/android/layout_tests/fast/block/positioning/auto/005.html +/sdcard/android/layout_tests/fast/block/positioning/auto/006.html +/sdcard/android/layout_tests/fast/block/positioning/auto/007.html +/sdcard/android/layout_tests/fast/block/positioning/059.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-in-inline-short-rtl.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-in-inline-short-ltr.html +/sdcard/android/layout_tests/fast/block/positioning/relative-overflow-replaced-float.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-positioned-overconstrained.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-in-inline-rtl-2.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-in-inline-ltr-2.html +/sdcard/android/layout_tests/fast/block/positioning/020.html +/sdcard/android/layout_tests/fast/block/positioning/012.html +/sdcard/android/layout_tests/fast/block/positioning/004.html +/sdcard/android/layout_tests/fast/block/positioning/040.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-position-direction-strict.html +/sdcard/android/layout_tests/fast/block/positioning/032.html +/sdcard/android/layout_tests/fast/block/positioning/024.html +/sdcard/android/layout_tests/fast/block/positioning/060.html +/sdcard/android/layout_tests/fast/block/positioning/052.html +/sdcard/android/layout_tests/fast/block/positioning/016.html +/sdcard/android/layout_tests/fast/block/positioning/044.html +/sdcard/android/layout_tests/fast/block/positioning/008.html +/sdcard/android/layout_tests/fast/block/positioning/036.html +/sdcard/android/layout_tests/fast/block/positioning/028.html +/sdcard/android/layout_tests/fast/block/positioning/056.html +/sdcard/android/layout_tests/fast/block/positioning/048.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-position-direction-quirk.html +/sdcard/android/layout_tests/fast/block/positioning/replaced-inside-fixed-top-bottom.html +/sdcard/android/layout_tests/fast/block/positioning/pref-width-change.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-in-inline-ltr-3.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-in-inline-ltr.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-in-inline-rtl-3.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-in-inline-rtl.html +/sdcard/android/layout_tests/fast/block/positioning/001.html +/sdcard/android/layout_tests/fast/block/positioning/021.html +/sdcard/android/layout_tests/fast/block/positioning/013.html +/sdcard/android/layout_tests/fast/block/positioning/relative-overflow-block.html +/sdcard/android/layout_tests/fast/block/positioning/005.html +/sdcard/android/layout_tests/fast/block/positioning/041.html +/sdcard/android/layout_tests/fast/block/positioning/033.html +/sdcard/android/layout_tests/fast/block/positioning/025.html +/sdcard/android/layout_tests/fast/block/positioning/061.html +/sdcard/android/layout_tests/fast/block/positioning/017.html +/sdcard/android/layout_tests/fast/block/positioning/053.html +/sdcard/android/layout_tests/fast/block/positioning/009.html +/sdcard/android/layout_tests/fast/block/positioning/045.html +/sdcard/android/layout_tests/fast/block/positioning/037.html +/sdcard/android/layout_tests/fast/block/positioning/029.html +/sdcard/android/layout_tests/fast/block/positioning/057.html +/sdcard/android/layout_tests/fast/block/positioning/049.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-with-html-border-quirks.html +/sdcard/android/layout_tests/fast/block/positioning/leftmargin-topmargin.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-length-of-neg-666666.html +/sdcard/android/layout_tests/fast/block/positioning/complex-percentage-height.html +/sdcard/android/layout_tests/fast/block/positioning/auto-height-with-top-and-bottom.html +/sdcard/android/layout_tests/fast/block/positioning/010.html +/sdcard/android/layout_tests/fast/block/positioning/002.html +/sdcard/android/layout_tests/fast/block/positioning/030.html +/sdcard/android/layout_tests/fast/block/positioning/relayout-on-position-change.html +/sdcard/android/layout_tests/fast/block/positioning/022.html +/sdcard/android/layout_tests/fast/block/positioning/padding-percent.html +/sdcard/android/layout_tests/fast/block/positioning/014.html +/sdcard/android/layout_tests/fast/block/positioning/050.html +/sdcard/android/layout_tests/fast/block/positioning/006.html +/sdcard/android/layout_tests/fast/block/positioning/042.html +/sdcard/android/layout_tests/fast/block/positioning/034.html +/sdcard/android/layout_tests/fast/block/positioning/offsetLeft-offsetTop-borders.html +/sdcard/android/layout_tests/fast/block/positioning/062.html +/sdcard/android/layout_tests/fast/block/positioning/026.html +/sdcard/android/layout_tests/fast/block/positioning/054.html +/sdcard/android/layout_tests/fast/block/positioning/018.html +/sdcard/android/layout_tests/fast/block/positioning/046.html +/sdcard/android/layout_tests/fast/block/positioning/abs-inside-inline-rel.html +/sdcard/android/layout_tests/fast/block/positioning/038.html +/sdcard/android/layout_tests/fast/block/positioning/absolute-with-html-border-strict.html +/sdcard/android/layout_tests/fast/block/positioning/058.html +/sdcard/android/layout_tests/fast/block/positioning/negative-right-pos.html +/sdcard/android/layout_tests/fast/block/positioning/relative-overconstrained.html +/sdcard/android/layout_tests/fast/block/positioning/child-of-absolute-with-auto-height.html +/sdcard/android/layout_tests/fast/block/positioning/relative-overflow-replaced.html +/sdcard/android/layout_tests/fast/block/positioning/height-change.html +/sdcard/android/layout_tests/fast/block/positioning/window-height-change.html +/sdcard/android/layout_tests/fast/block/positioning/011.html +/sdcard/android/layout_tests/fast/block/positioning/003.html +/sdcard/android/layout_tests/fast/block/positioning/move-with-auto-width.html +/sdcard/android/layout_tests/fast/block/positioning/031.html +/sdcard/android/layout_tests/fast/block/positioning/023.html +/sdcard/android/layout_tests/fast/block/positioning/051.html +/sdcard/android/layout_tests/fast/block/positioning/015.html +/sdcard/android/layout_tests/fast/block/positioning/043.html +/sdcard/android/layout_tests/fast/block/positioning/007.html +/sdcard/android/layout_tests/fast/block/positioning/035.html +/sdcard/android/layout_tests/fast/block/positioning/027.html +/sdcard/android/layout_tests/fast/block/positioning/055.html +/sdcard/android/layout_tests/fast/block/positioning/019.html +/sdcard/android/layout_tests/fast/block/positioning/047.html +/sdcard/android/layout_tests/fast/block/positioning/039.html +/sdcard/android/layout_tests/fast/block/positioning/inline-block-relposition.html +/sdcard/android/layout_tests/fast/block/float/vertical-move-relayout.html +/sdcard/android/layout_tests/fast/block/float/tableshifting.html +/sdcard/android/layout_tests/fast/block/float/table-relayout.html +/sdcard/android/layout_tests/fast/block/float/br-with-clear-2.html +/sdcard/android/layout_tests/fast/block/float/020.html +/sdcard/android/layout_tests/fast/block/float/012.html +/sdcard/android/layout_tests/fast/block/float/004.html +/sdcard/android/layout_tests/fast/block/float/032.html +/sdcard/android/layout_tests/fast/block/float/024.html +/sdcard/android/layout_tests/fast/block/float/016.html +/sdcard/android/layout_tests/fast/block/float/008.html +/sdcard/android/layout_tests/fast/block/float/028.html +/sdcard/android/layout_tests/fast/block/float/shrink-to-fit-width.html +/sdcard/android/layout_tests/fast/block/float/clamped-right-float.html +/sdcard/android/layout_tests/fast/block/float/independent-align-positioning.html +/sdcard/android/layout_tests/fast/block/float/float-on-zero-height-line.html +/sdcard/android/layout_tests/fast/block/float/nowrap-clear-min-width.html +/sdcard/android/layout_tests/fast/block/float/overhanging-after-height-decrease-offsets.html +/sdcard/android/layout_tests/fast/block/float/001.html +/sdcard/android/layout_tests/fast/block/float/021.html +/sdcard/android/layout_tests/fast/block/float/013.html +/sdcard/android/layout_tests/fast/block/float/nopaint-after-layer-destruction2.html +/sdcard/android/layout_tests/fast/block/float/005.html +/sdcard/android/layout_tests/fast/block/float/033.html +/sdcard/android/layout_tests/fast/block/float/025.html +/sdcard/android/layout_tests/fast/block/float/017.html +/sdcard/android/layout_tests/fast/block/float/009.html +/sdcard/android/layout_tests/fast/block/float/float-in-float-hit-testing.html +/sdcard/android/layout_tests/fast/block/float/029.html +/sdcard/android/layout_tests/fast/block/float/4145535Crash.html +/sdcard/android/layout_tests/fast/block/float/editable-text-overlapping-float.html +/sdcard/android/layout_tests/fast/block/float/nestedAnonymousBlocks.html +/sdcard/android/layout_tests/fast/block/float/intruding-painted-twice.html +/sdcard/android/layout_tests/fast/block/float/010.html +/sdcard/android/layout_tests/fast/block/float/002.html +/sdcard/android/layout_tests/fast/block/float/dynamic-unfloat-pref-width.html +/sdcard/android/layout_tests/fast/block/float/marquee-shrink-to-avoid-floats.html +/sdcard/android/layout_tests/fast/block/float/030.html +/sdcard/android/layout_tests/fast/block/float/022.html +/sdcard/android/layout_tests/fast/block/float/014.html +/sdcard/android/layout_tests/fast/block/float/006.html +/sdcard/android/layout_tests/fast/block/float/034.html +/sdcard/android/layout_tests/fast/block/float/relative-painted-twice.html +/sdcard/android/layout_tests/fast/block/float/026.html +/sdcard/android/layout_tests/fast/block/float/018.html +/sdcard/android/layout_tests/fast/block/float/width-update-after-clear.html +/sdcard/android/layout_tests/fast/block/float/nopaint-after-layer-destruction.html +/sdcard/android/layout_tests/fast/block/float/float-in-float-painting.html +/sdcard/android/layout_tests/fast/block/float/overhanging-after-height-decrease.html +/sdcard/android/layout_tests/fast/block/float/float-avoidance.html +/sdcard/android/layout_tests/fast/block/float/narrow-after-wide.html +/sdcard/android/layout_tests/fast/block/float/multiple-float-positioning.html +/sdcard/android/layout_tests/fast/block/float/br-with-clear.html +/sdcard/android/layout_tests/fast/block/float/011.html +/sdcard/android/layout_tests/fast/block/float/negative-margin-clear.html +/sdcard/android/layout_tests/fast/block/float/003.html +/sdcard/android/layout_tests/fast/block/float/031.html +/sdcard/android/layout_tests/fast/block/float/023.html +/sdcard/android/layout_tests/fast/block/float/015.html +/sdcard/android/layout_tests/fast/block/float/007.html +/sdcard/android/layout_tests/fast/block/float/035.html +/sdcard/android/layout_tests/fast/block/float/027.html +/sdcard/android/layout_tests/fast/block/float/019.html +/sdcard/android/layout_tests/fast/block/float/nestedAnonymousBlocks2.html +/sdcard/android/layout_tests/fast/block/margin-collapse/059.html +/sdcard/android/layout_tests/fast/block/margin-collapse/empty-clear-blocks.html +/sdcard/android/layout_tests/fast/block/margin-collapse/010.html +/sdcard/android/layout_tests/fast/block/margin-collapse/negative-margins.html +/sdcard/android/layout_tests/fast/block/margin-collapse/002.html +/sdcard/android/layout_tests/fast/block/margin-collapse/020.html +/sdcard/android/layout_tests/fast/block/margin-collapse/101.html +/sdcard/android/layout_tests/fast/block/margin-collapse/030.html +/sdcard/android/layout_tests/fast/block/margin-collapse/012.html +/sdcard/android/layout_tests/fast/block/margin-collapse/040.html +/sdcard/android/layout_tests/fast/block/margin-collapse/022.html +/sdcard/android/layout_tests/fast/block/margin-collapse/004.html +/sdcard/android/layout_tests/fast/block/margin-collapse/103.html +/sdcard/android/layout_tests/fast/block/margin-collapse/032.html +/sdcard/android/layout_tests/fast/block/margin-collapse/006.html +/sdcard/android/layout_tests/fast/block/margin-collapse/042.html +/sdcard/android/layout_tests/fast/block/margin-collapse/016.html +/sdcard/android/layout_tests/fast/block/margin-collapse/034.html +/sdcard/android/layout_tests/fast/block/margin-collapse/062.html +/sdcard/android/layout_tests/fast/block/margin-collapse/044.html +/sdcard/android/layout_tests/fast/block/margin-collapse/026.html +/sdcard/android/layout_tests/fast/block/margin-collapse/018.html +/sdcard/android/layout_tests/fast/block/margin-collapse/028.html +/sdcard/android/layout_tests/fast/block/margin-collapse/056.html +/sdcard/android/layout_tests/fast/block/margin-collapse/038.html +/sdcard/android/layout_tests/fast/block/margin-collapse/058.html +/sdcard/android/layout_tests/fast/block/margin-collapse/100.html +/sdcard/android/layout_tests/fast/block/margin-collapse/001.html +/sdcard/android/layout_tests/fast/block/margin-collapse/011.html +/sdcard/android/layout_tests/fast/block/margin-collapse/102.html +/sdcard/android/layout_tests/fast/block/margin-collapse/021.html +/sdcard/android/layout_tests/fast/block/margin-collapse/003.html +/sdcard/android/layout_tests/fast/block/margin-collapse/031.html +/sdcard/android/layout_tests/fast/block/margin-collapse/005.html +/sdcard/android/layout_tests/fast/block/margin-collapse/041.html +/sdcard/android/layout_tests/fast/block/margin-collapse/104.html +/sdcard/android/layout_tests/fast/block/margin-collapse/033.html +/sdcard/android/layout_tests/fast/block/margin-collapse/015.html +/sdcard/android/layout_tests/fast/block/margin-collapse/025.html +/sdcard/android/layout_tests/fast/block/margin-collapse/043.html +/sdcard/android/layout_tests/fast/block/margin-collapse/035.html +/sdcard/android/layout_tests/fast/block/margin-collapse/017.html +/sdcard/android/layout_tests/fast/block/margin-collapse/027.html +/sdcard/android/layout_tests/fast/block/margin-collapse/045.html +/sdcard/android/layout_tests/fast/block/margin-collapse/063.html +/sdcard/android/layout_tests/fast/block/margin-collapse/037.html +/sdcard/android/layout_tests/fast/block/margin-collapse/019.html +/sdcard/android/layout_tests/fast/block/margin-collapse/055.html +/sdcard/android/layout_tests/fast/block/margin-collapse/029.html +/sdcard/android/layout_tests/fast/block/margin-collapse/039.html +/sdcard/android/layout_tests/fast/block/margin-collapse/057.html +/sdcard/android/layout_tests/fast/runin/001.html +/sdcard/android/layout_tests/fast/runin/002.html +/sdcard/android/layout_tests/fast/parser/title-error-test.html +/sdcard/android/layout_tests/fast/parser/comments.html +/sdcard/android/layout_tests/fast/parser/fonts.html +/sdcard/android/layout_tests/fast/parser/comment-in-style.html +/sdcard/android/layout_tests/fast/parser/comment-in-script.html +/sdcard/android/layout_tests/fast/parser/broken-comments-vs-parsing-mode.html +/sdcard/android/layout_tests/fast/parser/entity-comment-in-style.html +/sdcard/android/layout_tests/fast/parser/xhtml-alternate-entities.xml +/sdcard/android/layout_tests/fast/parser/nofoo-tags-inside-paragraph.html +/sdcard/android/layout_tests/fast/parser/entity-comment-in-textarea.html +/sdcard/android/layout_tests/fast/parser/bad-xml-slash.html +/sdcard/android/layout_tests/fast/parser/001.html +/sdcard/android/layout_tests/fast/parser/open-comment-in-textarea.html +/sdcard/android/layout_tests/fast/parser/tabs-in-scripts.html +/sdcard/android/layout_tests/fast/parser/external-entities-in-xslt.xml : has expected results +/sdcard/android/layout_tests/fast/parser/parseCommentsInTitles.html +/sdcard/android/layout_tests/fast/parser/remove-block-in-residual-style.html +/sdcard/android/layout_tests/fast/parser/open-comment-in-style.html +/sdcard/android/layout_tests/fast/parser/document-write-option.html +/sdcard/android/layout_tests/fast/parser/style-script-head-test.html +/sdcard/android/layout_tests/fast/parser/comment-in-textarea.html +/sdcard/android/layout_tests/fast/layers/zindex-ridonkulous.html +/sdcard/android/layout_tests/fast/layers/positioned-inside-root-with-margins.html +/sdcard/android/layout_tests/fast/layers/layer-visibility-sublayer.html +/sdcard/android/layout_tests/fast/layers/opacity-outline.html +/sdcard/android/layout_tests/fast/layers/add-layer-with-nested-stacking.html +/sdcard/android/layout_tests/fast/layers/layer-content-visibility-change.html +/sdcard/android/layout_tests/fast/layers/zindex-inherit.html +/sdcard/android/layout_tests/fast/layers/layer-visibility.html +/sdcard/android/layout_tests/fast/layers/remove-layer-with-nested-stacking.html +/sdcard/android/layout_tests/fast/layers/opacity-transforms.html +/sdcard/android/layout_tests/fast/layers/overflow-scroll-auto-switch.html +/sdcard/android/layout_tests/fast/layers/scroll-rect-to-visible.html +/sdcard/android/layout_tests/fast/layers/opacity-stacking.html +/sdcard/android/layout_tests/fast/history/clicked-link-is-visited.html +/sdcard/android/layout_tests/fast/history/history_reload.html : has expected results +/sdcard/android/layout_tests/fast/backgrounds/repeat/mask-negative-offset-repeat.html +/sdcard/android/layout_tests/fast/backgrounds/repeat/negative-offset-repeat.html +/sdcard/android/layout_tests/fast/backgrounds/repeat/negative-offset-repeat-transformed.html +/sdcard/android/layout_tests/fast/backgrounds/repeat/noRepeatCorrectClip.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize02.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize11.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize03.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize12.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize04.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize13.html +/sdcard/android/layout_tests/fast/backgrounds/size/zero.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize05.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize14.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize06.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize15.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize07.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize16.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize17.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize08.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize09.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize18.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize19.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize10.html +/sdcard/android/layout_tests/fast/backgrounds/size/backgroundSize01.html +/sdcard/android/layout_tests/fast/backgrounds/svg-as-background-2.html +/sdcard/android/layout_tests/fast/backgrounds/background-origin-root-element.html +/sdcard/android/layout_tests/fast/backgrounds/svg-as-background-3.html +/sdcard/android/layout_tests/fast/backgrounds/svg-as-background-4.html +/sdcard/android/layout_tests/fast/backgrounds/svg-as-background-5.html +/sdcard/android/layout_tests/fast/backgrounds/background-position-1.html +/sdcard/android/layout_tests/fast/backgrounds/svg-as-background-6.html +/sdcard/android/layout_tests/fast/backgrounds/opacity-on-document-element.html +/sdcard/android/layout_tests/fast/backgrounds/svg-as-mask.html +/sdcard/android/layout_tests/fast/backgrounds/solid-color-context-restore.html +/sdcard/android/layout_tests/fast/backgrounds/mask-composite.html +/sdcard/android/layout_tests/fast/backgrounds/animated-svg-as-background.html +/sdcard/android/layout_tests/fast/backgrounds/001.html +/sdcard/android/layout_tests/fast/backgrounds/animated-gif-as-background.html +/sdcard/android/layout_tests/fast/backgrounds/background-position-rounding.html +/sdcard/android/layout_tests/fast/backgrounds/bgCompositeCopy.html +/sdcard/android/layout_tests/fast/backgrounds/background-inherit-color-bug.html +/sdcard/android/layout_tests/fast/backgrounds/animated-svg-as-mask.html +/sdcard/android/layout_tests/fast/backgrounds/svg-as-background-1.html +/sdcard/android/layout_tests/fast/repaint/reflection-redraw.html +/sdcard/android/layout_tests/fast/repaint/layer-full-repaint.html +/sdcard/android/layout_tests/fast/repaint/subtree-root-clip.html +/sdcard/android/layout_tests/fast/repaint/subtree-root-clip-3.html +/sdcard/android/layout_tests/fast/repaint/layer-outline-horizontal.html +/sdcard/android/layout_tests/fast/repaint/layer-hide-when-needs-layout.html +/sdcard/android/layout_tests/fast/repaint/layer-outline.html +/sdcard/android/layout_tests/fast/repaint/list-marker-2.html +/sdcard/android/layout_tests/fast/repaint/table-section-overflow.html +/sdcard/android/layout_tests/fast/repaint/body-background-image.html +/sdcard/android/layout_tests/fast/repaint/shadow-multiple-strict-vertical.html +/sdcard/android/layout_tests/fast/repaint/inline-outline-repaint.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-4.html +/sdcard/android/layout_tests/fast/repaint/change-transform.html +/sdcard/android/layout_tests/fast/repaint/fixed.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-8.html +/sdcard/android/layout_tests/fast/repaint/erase-overflow.html +/sdcard/android/layout_tests/fast/repaint/outline-child-repaint.html +/sdcard/android/layout_tests/fast/repaint/float-overflow.html +/sdcard/android/layout_tests/fast/repaint/containing-block-position-change.html +/sdcard/android/layout_tests/fast/repaint/text-selection-rect-in-overflow.html +/sdcard/android/layout_tests/fast/repaint/flexible-box-overflow-horizontal.html +/sdcard/android/layout_tests/fast/repaint/table-cell-move.html +/sdcard/android/layout_tests/fast/repaint/transform-absolute-child.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-10.html +/sdcard/android/layout_tests/fast/repaint/float-move-during-layout.html +/sdcard/android/layout_tests/fast/repaint/overflow-clip-subtree-layout.html +/sdcard/android/layout_tests/fast/repaint/invisible-objects.html +/sdcard/android/layout_tests/fast/repaint/shadow-multiple-strict-horizontal.html +/sdcard/android/layout_tests/fast/repaint/focus-layers.html +/sdcard/android/layout_tests/fast/repaint/inline-color-change.html +/sdcard/android/layout_tests/fast/repaint/table-col-background.html +/sdcard/android/layout_tests/fast/repaint/selection-after-remove.html +/sdcard/android/layout_tests/fast/repaint/dynamic-table-vertical-alignment-change.html +/sdcard/android/layout_tests/fast/repaint/flexible-box-overflow.html +/sdcard/android/layout_tests/fast/repaint/table-two-pass-layout-overpaint.html +/sdcard/android/layout_tests/fast/repaint/overflow-into-content.html +/sdcard/android/layout_tests/fast/repaint/shadow-multiple-vertical.html +/sdcard/android/layout_tests/fast/repaint/border-repaint-glitch.html +/sdcard/android/layout_tests/fast/repaint/continuation-after-outline.html +/sdcard/android/layout_tests/fast/repaint/intermediate-layout-position.html +/sdcard/android/layout_tests/fast/repaint/table-section-repaint.html +/sdcard/android/layout_tests/fast/repaint/clipped-relative.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-1.html +/sdcard/android/layout_tests/fast/repaint/backgroundSizeRepaint.html +/sdcard/android/layout_tests/fast/repaint/box-shadow-dynamic.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-5.html +/sdcard/android/layout_tests/fast/repaint/text-shadow-horizontal.html +/sdcard/android/layout_tests/fast/repaint/caret-outside-block.html +/sdcard/android/layout_tests/fast/repaint/renderer-destruction-by-invalidateSelection-crash.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-9.html +/sdcard/android/layout_tests/fast/repaint/transform-repaint-descendants.html +/sdcard/android/layout_tests/fast/repaint/layout-state-relative.html +/sdcard/android/layout_tests/fast/repaint/shadow-multiple-horizontal.html +/sdcard/android/layout_tests/fast/repaint/border-fit-lines.html +/sdcard/android/layout_tests/fast/repaint/repaint-resized-overflow.html +/sdcard/android/layout_tests/fast/repaint/bugzilla-3509.html +/sdcard/android/layout_tests/fast/repaint/inline-block-overflow.html +/sdcard/android/layout_tests/fast/repaint/button-spurious-layout-hint.html +/sdcard/android/layout_tests/fast/repaint/bugzilla-6278.html +/sdcard/android/layout_tests/fast/repaint/box-shadow-v.html +/sdcard/android/layout_tests/fast/repaint/delete-into-nested-block.html +/sdcard/android/layout_tests/fast/repaint/float-overflow-right.html +/sdcard/android/layout_tests/fast/repaint/table-cell-collapsed-border.html +/sdcard/android/layout_tests/fast/repaint/selection-after-delete.html +/sdcard/android/layout_tests/fast/repaint/lines-with-layout-delta.html +/sdcard/android/layout_tests/fast/repaint/layout-state-only-positioned.html +/sdcard/android/layout_tests/fast/repaint/table-extra-bottom-grow.html +/sdcard/android/layout_tests/fast/repaint/transform-relative-position.html +/sdcard/android/layout_tests/fast/repaint/selection-gap-overflow-scroll.html +/sdcard/android/layout_tests/fast/repaint/subtree-root-skipped.html +/sdcard/android/layout_tests/fast/repaint/line-overflow.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-2.html +/sdcard/android/layout_tests/fast/repaint/table-row.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-6.html +/sdcard/android/layout_tests/fast/repaint/table-outer-border.html +/sdcard/android/layout_tests/fast/repaint/overflow-scroll-delete.html +/sdcard/android/layout_tests/fast/repaint/layer-visibility.html +/sdcard/android/layout_tests/fast/repaint/border-radius-repaint.html +/sdcard/android/layout_tests/fast/repaint/table-collapsed-border.html +/sdcard/android/layout_tests/fast/repaint/transform-translate.html +/sdcard/android/layout_tests/fast/repaint/bugzilla-7235.html +/sdcard/android/layout_tests/fast/repaint/4776765.html +/sdcard/android/layout_tests/fast/repaint/bugzilla-6473.html +/sdcard/android/layout_tests/fast/repaint/intermediate-layout-position-clip.html +/sdcard/android/layout_tests/fast/repaint/focus-ring.html +/sdcard/android/layout_tests/fast/repaint/table-cell-vertical-overflow.html +/sdcard/android/layout_tests/fast/repaint/create-layer-repaint.html +/sdcard/android/layout_tests/fast/repaint/subtree-root-clip-2.html +/sdcard/android/layout_tests/fast/repaint/bugzilla-6388.html +/sdcard/android/layout_tests/fast/repaint/overflow-outline-repaint.html +/sdcard/android/layout_tests/fast/repaint/content-into-overflow.html +/sdcard/android/layout_tests/fast/repaint/static-to-positioned.html +/sdcard/android/layout_tests/fast/repaint/bugzilla-5699.html +/sdcard/android/layout_tests/fast/repaint/transform-absolute-in-positioned-container.html +/sdcard/android/layout_tests/fast/repaint/outline-repaint-glitch.html +/sdcard/android/layout_tests/fast/repaint/overflow-delete-line.html +/sdcard/android/layout_tests/fast/repaint/transform-disable-layoutstate.html +/sdcard/android/layout_tests/fast/repaint/list-marker.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-3.html +/sdcard/android/layout_tests/fast/repaint/line-flow-with-floats-7.html +/sdcard/android/layout_tests/fast/repaint/outline-inset.html +/sdcard/android/layout_tests/fast/repaint/box-shadow-h.html +/sdcard/android/layout_tests/fast/repaint/4774354.html +/sdcard/android/layout_tests/fast/repaint/clip-with-layout-delta.html +/sdcard/android/layout_tests/fast/repaint/control-clip.html +/sdcard/android/layout_tests/fast/repaint/selected-replaced.html +/sdcard/android/layout_tests/fast/repaint/text-selection-rect-in-overflow-2.html +/sdcard/android/layout_tests/fast/repaint/make-children-non-inline.html +/sdcard/android/layout_tests/fast/repaint/text-shadow.html +/sdcard/android/layout_tests/fast/repaint/outline-shrinking.html +/sdcard/android/layout_tests/fast/repaint/layer-child-outline.html +/sdcard/android/layout_tests/fast/loader/start-load-in-unload.html +/sdcard/android/layout_tests/fast/loader/text-document-wrapping.html +/sdcard/android/layout_tests/fast/canvas/fillrect-gradient-zero-stops.html +/sdcard/android/layout_tests/fast/canvas/canvas-transforms-during-path.html +/sdcard/android/layout_tests/fast/canvas/drawImage.html +/sdcard/android/layout_tests/fast/canvas/shadow-offset-7.html +/sdcard/android/layout_tests/fast/canvas/canvas-transform-non-invertible.html : has expected results +/sdcard/android/layout_tests/fast/canvas/shadow-offset-4.html +/sdcard/android/layout_tests/fast/canvas/canvas-transform-infinity.html : has expected results +/sdcard/android/layout_tests/fast/canvas/canvas-text-baseline.html +/sdcard/android/layout_tests/fast/canvas/canvas-as-image-incremental-repaint.html +/sdcard/android/layout_tests/fast/canvas/shadow-offset-1.html +/sdcard/android/layout_tests/fast/canvas/canvas-size-change-after-layout.html +/sdcard/android/layout_tests/fast/canvas/canvas-resize-reset.html +/sdcard/android/layout_tests/fast/canvas/canvas-bg.html +/sdcard/android/layout_tests/fast/canvas/canvas-transform-skewed.html : has expected results +/sdcard/android/layout_tests/fast/canvas/zero-size-fill-rect.html +/sdcard/android/layout_tests/fast/canvas/shadow-offset-6.html +/sdcard/android/layout_tests/fast/canvas/patternfill-repeat.html +/sdcard/android/layout_tests/fast/canvas/image-object-in-canvas.html +/sdcard/android/layout_tests/fast/canvas/shadow-offset-3.html +/sdcard/android/layout_tests/fast/canvas/canvas-composite.html +/sdcard/android/layout_tests/fast/canvas/gradient-add-second-start-end-stop.html +/sdcard/android/layout_tests/fast/canvas/quadraticCurveTo.xml +/sdcard/android/layout_tests/fast/canvas/fill-stroke-clip-reset-path.html +/sdcard/android/layout_tests/fast/canvas/canvas-transform-nan.html : has expected results +/sdcard/android/layout_tests/fast/canvas/canvas-text-alignment.html +/sdcard/android/layout_tests/fast/canvas/canvas-incremental-repaint.html +/sdcard/android/layout_tests/fast/canvas/canvasDrawingIntoSelf.html +/sdcard/android/layout_tests/fast/canvas/canvas-as-image.html +/sdcard/android/layout_tests/fast/canvas/canvas-before-css.html +/sdcard/android/layout_tests/fast/canvas/canvas-incremental-repaint-2.html +/sdcard/android/layout_tests/fast/canvas/canvas-transform-identity.html : has expected results +/sdcard/android/layout_tests/fast/canvas/shadow-offset-5.html +/sdcard/android/layout_tests/fast/canvas/fillrect_gradient.html +/sdcard/android/layout_tests/fast/canvas/canvas-transform-multiply.html : has expected results +/sdcard/android/layout_tests/fast/canvas/shadow-offset-2.html +/sdcard/android/layout_tests/fast/frames/contentWindow_Frame.html +/sdcard/android/layout_tests/fast/frames/onlyCommentInIFrame.html +/sdcard/android/layout_tests/fast/frames/frame-src-attribute.html +/sdcard/android/layout_tests/fast/frames/frameElement-frame.html +/sdcard/android/layout_tests/fast/frames/empty-cols-attribute.html +/sdcard/android/layout_tests/fast/frames/iframe-scrolling-attribute.html +/sdcard/android/layout_tests/fast/frames/inline-object-inside-frameset.html +/sdcard/android/layout_tests/fast/frames/valid.html +/sdcard/android/layout_tests/fast/frames/no-frame-borders.html +/sdcard/android/layout_tests/fast/frames/empty-frame-src.html +/sdcard/android/layout_tests/fast/frames/calculate-round.html +/sdcard/android/layout_tests/fast/frames/frame-navigation.html +/sdcard/android/layout_tests/fast/frames/001.html +/sdcard/android/layout_tests/fast/frames/invalid.html +/sdcard/android/layout_tests/fast/frames/frameset-style-recalc.html +/sdcard/android/layout_tests/fast/frames/viewsource-attribute.html +/sdcard/android/layout_tests/fast/frames/002.html +/sdcard/android/layout_tests/fast/frames/calculate-relative.html +/sdcard/android/layout_tests/fast/frames/calculate-order.html +/sdcard/android/layout_tests/fast/frames/calculate-percentage.html +/sdcard/android/layout_tests/fast/frames/iframe-text-contents.html +/sdcard/android/layout_tests/fast/frames/frame-scrolling-attribute.html +/sdcard/android/layout_tests/fast/frames/contentWindow_iFrame.html +/sdcard/android/layout_tests/fast/frames/frame-length-fractional.html : has expected results +/sdcard/android/layout_tests/fast/frames/calculate-fixed.html +/sdcard/android/layout_tests/fast/frames/frame-element-name.html +/sdcard/android/layout_tests/fast/frames/frame-set-whitespace-attributes.html +/sdcard/android/layout_tests/fast/frames/iframe-with-frameborder.html +/sdcard/android/layout_tests/fast/frames/frameElement-iframe.html +/sdcard/android/layout_tests/fast/frames/iframe-name-and-id.html : has expected results +/sdcard/android/layout_tests/fast/reflections/inline-crash.html +/sdcard/android/layout_tests/fast/reflections/reflection-nesting.html +/sdcard/android/layout_tests/fast/reflections/reflection-overflow-hidden.html +/sdcard/android/layout_tests/fast/reflections/table-cell.html +/sdcard/android/layout_tests/fast/reflections/reflection-direction.html diff --git a/tests/DumpRenderTree/results/layout_tests_passed.txt b/tests/DumpRenderTree/results/layout_tests_passed.txt new file mode 100644 index 0000000000000000000000000000000000000000..fbceabd2304814a724bba147258c811975754fd0 --- /dev/null +++ b/tests/DumpRenderTree/results/layout_tests_passed.txt @@ -0,0 +1,1046 @@ +/sdcard/android/layout_tests/fast/replaced/object-param-no-name.html +/sdcard/android/layout_tests/fast/dynamic/subtree-common-root.html +/sdcard/android/layout_tests/fast/dynamic/hovered-detach.html +/sdcard/android/layout_tests/fast/dynamic/insertAdjacentHTML.html +/sdcard/android/layout_tests/fast/dynamic/style-access-late-stylesheet-load.html +/sdcard/android/layout_tests/fast/dynamic/insertAdjacentText.html +/sdcard/android/layout_tests/fast/dynamic/insertAdjacentHTML-allowed-parents.html +/sdcard/android/layout_tests/fast/dynamic/checkbox-selection-crash.html +/sdcard/android/layout_tests/fast/dynamic/outerHTML-no-element.html +/sdcard/android/layout_tests/fast/dynamic/5872671.html +/sdcard/android/layout_tests/fast/dynamic/ancestor-to-absolute.html +/sdcard/android/layout_tests/fast/dynamic/float-remove-above-line.html +/sdcard/android/layout_tests/fast/dynamic/recursive-layout.html +/sdcard/android/layout_tests/fast/dynamic/inline-to-block-crash.html +/sdcard/android/layout_tests/fast/text/find-backwards.html +/sdcard/android/layout_tests/fast/text/large-text-composed-char-dos.html +/sdcard/android/layout_tests/fast/text/find-case-folding.html +/sdcard/android/layout_tests/fast/text/line-breaks-after-ideographic-comma-or-full-stop.html +/sdcard/android/layout_tests/fast/encoding/gbk/chinese.html +/sdcard/android/layout_tests/fast/encoding/gbk/x-euc-cn.html +/sdcard/android/layout_tests/fast/encoding/gbk/gb_2312-80.html +/sdcard/android/layout_tests/fast/encoding/gbk/cn-gb.html +/sdcard/android/layout_tests/fast/encoding/gbk/csgb2312.html +/sdcard/android/layout_tests/fast/encoding/gbk/iso-ir-58.html +/sdcard/android/layout_tests/fast/encoding/gbk/csgb231280.html +/sdcard/android/layout_tests/fast/encoding/gbk/gb2312.html +/sdcard/android/layout_tests/fast/encoding/gbk/gbk.html +/sdcard/android/layout_tests/fast/encoding/gbk/x-gbk.html +/sdcard/android/layout_tests/fast/encoding/gbk/EUC-CN.html +/sdcard/android/layout_tests/fast/encoding/gbk/close-gbk-converter.html +/sdcard/android/layout_tests/fast/encoding/hebrew/hebrew.html +/sdcard/android/layout_tests/fast/encoding/hebrew/csISO88598I.html +/sdcard/android/layout_tests/fast/encoding/hebrew/8859-8.html +/sdcard/android/layout_tests/fast/encoding/hebrew/8859-8-e.html +/sdcard/android/layout_tests/fast/encoding/hebrew/8859-8-i.html +/sdcard/android/layout_tests/fast/encoding/hebrew/logical.html +/sdcard/android/layout_tests/fast/encoding/hebrew/iso-ir-138.html +/sdcard/android/layout_tests/fast/encoding/charset-invalid.html +/sdcard/android/layout_tests/fast/encoding/hanarei-blog32-fc2-com.html +/sdcard/android/layout_tests/fast/encoding/pseudo-tags-in-attributes.html +/sdcard/android/layout_tests/fast/encoding/decoder-allow-null-chars.html +/sdcard/android/layout_tests/fast/encoding/charset-utf16.html +/sdcard/android/layout_tests/fast/encoding/css-charset-dom.html +/sdcard/android/layout_tests/fast/encoding/pseudo-xml-4.html +/sdcard/android/layout_tests/fast/encoding/char-encoding.html +/sdcard/android/layout_tests/fast/encoding/css-link-charset.html +/sdcard/android/layout_tests/fast/encoding/latin1-winlatin.html +/sdcard/android/layout_tests/fast/encoding/no-charset-on-dynamic-script-load.html +/sdcard/android/layout_tests/fast/encoding/high-bit-latin1.html +/sdcard/android/layout_tests/fast/encoding/utf-32-little-endian-bom.html +/sdcard/android/layout_tests/fast/encoding/bandai-co-jp-releases.html +/sdcard/android/layout_tests/fast/encoding/utf-32-big-endian-bom.html +/sdcard/android/layout_tests/fast/encoding/bom-in-content.html +/sdcard/android/layout_tests/fast/encoding/bom-in-content-utf16.html +/sdcard/android/layout_tests/fast/encoding/namespace-tolerance.html +/sdcard/android/layout_tests/fast/encoding/css-charset-evil.html +/sdcard/android/layout_tests/fast/encoding/css-charset.html +/sdcard/android/layout_tests/fast/encoding/misplaced-xml-declaration.html +/sdcard/android/layout_tests/fast/encoding/charset-xuser-defined.html +/sdcard/android/layout_tests/fast/encoding/xml-charset-utf16.html +/sdcard/android/layout_tests/fast/encoding/pseudo-xml-2.html +/sdcard/android/layout_tests/fast/encoding/floraexpress-ru.html +/sdcard/android/layout_tests/fast/encoding/charset-cp1251.html +/sdcard/android/layout_tests/fast/encoding/utf-32-little-endian-nobom.xml +/sdcard/android/layout_tests/fast/encoding/charset-unicode.html +/sdcard/android/layout_tests/fast/encoding/meta-charset.html +/sdcard/android/layout_tests/fast/encoding/utf-32-big-endian-nobom.xml +/sdcard/android/layout_tests/fast/encoding/pseudo-xml-3.html +/sdcard/android/layout_tests/fast/encoding/pseudo-xml.html +/sdcard/android/layout_tests/fast/encoding/tag-in-title.html +/sdcard/android/layout_tests/fast/encoding/yahoo-mail.html +/sdcard/android/layout_tests/fast/encoding/ahram-org-eg.html +/sdcard/android/layout_tests/fast/encoding/noscript-in-head.html +/sdcard/android/layout_tests/fast/encoding/script-in-head.html +/sdcard/android/layout_tests/fast/encoding/css-cached-bom.html +/sdcard/android/layout_tests/fast/encoding/mispositioned-meta.html +/sdcard/android/layout_tests/fast/multicol/gap-non-negative.html +/sdcard/android/layout_tests/fast/multicol/content-height-zero-crash.html +/sdcard/android/layout_tests/fast/doctypes/doctype-at-end.html +/sdcard/android/layout_tests/fast/doctypes/005-case-preserving.html +/sdcard/android/layout_tests/fast/doctypes/doctype-in-element.html +/sdcard/android/layout_tests/fast/doctypes/doctype-after-comment.html +/sdcard/android/layout_tests/fast/doctypes/doctype-parsing.html +/sdcard/android/layout_tests/fast/doctypes/html-doctype.html +/sdcard/android/layout_tests/fast/cookies/local-file-can-set-cookies.html +/sdcard/android/layout_tests/fast/css-generated-content/empty-content-with-float-crash.html +/sdcard/android/layout_tests/fast/css-generated-content/reset-content-to-initial.html +/sdcard/android/layout_tests/fast/transforms/container-transform-crash.html +/sdcard/android/layout_tests/fast/leaks/001.html +/sdcard/android/layout_tests/fast/leaks/002.html +/sdcard/android/layout_tests/fast/innerHTML/innerHTML-custom-tag.html +/sdcard/android/layout_tests/fast/innerHTML/additional-inline-style.html +/sdcard/android/layout_tests/fast/innerHTML/005.html +/sdcard/android/layout_tests/fast/innerHTML/javascript-url.html +/sdcard/android/layout_tests/fast/innerHTML/innerHTML-case.html +/sdcard/android/layout_tests/fast/overflow/onscroll-layer-self-destruct.html +/sdcard/android/layout_tests/fast/overflow/generated-content-crash.html +/sdcard/android/layout_tests/fast/events/dispatch-to-handle-event.html +/sdcard/android/layout_tests/fast/events/onload-after-document-close-with-subresource.html +/sdcard/android/layout_tests/fast/events/dispatchEvent-crash.html +/sdcard/android/layout_tests/fast/events/programmatic-check-no-change-event.html +/sdcard/android/layout_tests/fast/events/onunload-body-property.html +/sdcard/android/layout_tests/fast/events/init-event-after-dispatch.html +/sdcard/android/layout_tests/fast/events/delayed-style-mutation-event-crash.html +/sdcard/android/layout_tests/fast/events/anchor-empty-focus.html +/sdcard/android/layout_tests/fast/events/no-blur-on-page-leave.html +/sdcard/android/layout_tests/fast/events/onload-name-collision.html +/sdcard/android/layout_tests/fast/events/div-focus.html +/sdcard/android/layout_tests/fast/events/overflow-events.html +/sdcard/android/layout_tests/fast/events/create-document-crash-on-attach-event.html +/sdcard/android/layout_tests/fast/events/no-blur-on-enter-button.html +/sdcard/android/layout_tests/fast/events/keypress-removed-node.html +/sdcard/android/layout_tests/fast/events/shadow-boundary-crossing.html +/sdcard/android/layout_tests/fast/events/submit-reset-nested-bubble.html +/sdcard/android/layout_tests/fast/events/nested-event-remove-node-crash.html +/sdcard/android/layout_tests/fast/events/mousedown_in_scrollbar.html +/sdcard/android/layout_tests/fast/events/window-load-capture.html +/sdcard/android/layout_tests/fast/events/event-instanceof.html +/sdcard/android/layout_tests/fast/events/event-creation.html +/sdcard/android/layout_tests/fast/events/caller-access-from-event-listener.html +/sdcard/android/layout_tests/fast/events/stopPropagation-submit.html +/sdcard/android/layout_tests/fast/events/remove-event-listener.html +/sdcard/android/layout_tests/fast/events/mouseup-outside-button.html +/sdcard/android/layout_tests/fast/events/no-window-load.html +/sdcard/android/layout_tests/fast/events/event-listener-html-non-html-confusion.html +/sdcard/android/layout_tests/fast/events/onerror-bubbling.html +/sdcard/android/layout_tests/fast/events/keydown-remove-frame.html +/sdcard/android/layout_tests/fast/events/event-targets.html +/sdcard/android/layout_tests/fast/events/space-scroll-event.html +/sdcard/android/layout_tests/fast/events/onload-after-document-close-no-subresource.html +/sdcard/android/layout_tests/fast/events/stopPropagation-checkbox.html +/sdcard/android/layout_tests/fast/events/tab-crash-with-image-map.html +/sdcard/android/layout_tests/fast/events/simulated-key-state.html +/sdcard/android/layout_tests/fast/events/init-event-null-view.html +/sdcard/android/layout_tests/fast/events/resize-subframe.html +/sdcard/android/layout_tests/fast/events/onunload-window-property.html +/sdcard/android/layout_tests/fast/html/empty-fragment-id-goto-top.html +/sdcard/android/layout_tests/fast/html/script-allowed-types-languages.html +/sdcard/android/layout_tests/fast/html/xhtml-serialize.html +/sdcard/android/layout_tests/fast/html/body-offset-properties.html +/sdcard/android/layout_tests/fast/images/animated-background-image-crash.html +/sdcard/android/layout_tests/fast/images/border.html +/sdcard/android/layout_tests/fast/images/load-img-with-empty-src.html +/sdcard/android/layout_tests/fast/images/image-empty-data.html +/sdcard/android/layout_tests/fast/images/text-content-crash-2.html +/sdcard/android/layout_tests/fast/images/text-content-crash.html +/sdcard/android/layout_tests/fast/inspector/cssURLQuotes.html +/sdcard/android/layout_tests/fast/flexbox/inline-children-crash.html +/sdcard/android/layout_tests/fast/tokenizer/nested-cached-scripts.html +/sdcard/android/layout_tests/fast/tokenizer/image-empty-crash.html +/sdcard/android/layout_tests/fast/tokenizer/lessthan-terminates-tags-and-attrs.html +/sdcard/android/layout_tests/fast/tokenizer/ignore-tags-in-iframe.html +/sdcard/android/layout_tests/fast/tokenizer/write-partial-entity.html +/sdcard/android/layout_tests/fast/tokenizer/external-script-document-open.html +/sdcard/android/layout_tests/fast/tokenizer/004.html +/sdcard/android/layout_tests/fast/tokenizer/write-inline-script-open.html +/sdcard/android/layout_tests/fast/tokenizer/write-external-script-open.html +/sdcard/android/layout_tests/fast/tokenizer/doctype-search-reset.html +/sdcard/android/layout_tests/fast/tokenizer/nested-multiple-scripts.html +/sdcard/android/layout_tests/fast/tokenizer/nested-cached-scripts-and-stylesheet.html +/sdcard/android/layout_tests/fast/tokenizer/ampersand-in-special-tag.html +/sdcard/android/layout_tests/fast/tokenizer/write-unclosed-script.html +/sdcard/android/layout_tests/fast/tokenizer/badscript.html +/sdcard/android/layout_tests/fast/regex/quantified-assertions.html +/sdcard/android/layout_tests/fast/regex/non-pattern-characters.html +/sdcard/android/layout_tests/fast/regex/slow.html +/sdcard/android/layout_tests/fast/regex/malformed-escapes.html +/sdcard/android/layout_tests/fast/regex/early-acid3-86.html +/sdcard/android/layout_tests/fast/regex/test1.html +/sdcard/android/layout_tests/fast/regex/alternative-length-miscalculation.html +/sdcard/android/layout_tests/fast/regex/test4.html +/sdcard/android/layout_tests/fast/regex/non-capturing-backtracking.html +/sdcard/android/layout_tests/fast/js/pic/cached-single-entry-transition.html +/sdcard/android/layout_tests/fast/js/pic/cached-prototype-setter.html +/sdcard/android/layout_tests/fast/js/pic/get-empty-string.html +/sdcard/android/layout_tests/fast/js/pic/get-set-proxy-object.html +/sdcard/android/layout_tests/fast/js/pic/rehash-poisons-structure.html +/sdcard/android/layout_tests/fast/js/pic/cached-array-length-access.html +/sdcard/android/layout_tests/fast/js/pic/cached-prototype-then-immediate.html +/sdcard/android/layout_tests/fast/js/pic/cached-getter-setter.html +/sdcard/android/layout_tests/fast/js/pic/cached-getter-dictionary-and-proto.html +/sdcard/android/layout_tests/fast/js/pic/delete-global-object.html +/sdcard/android/layout_tests/fast/js/pic/cached-deleted-properties.html +/sdcard/android/layout_tests/fast/js/pic/dictionary-prototype.html +/sdcard/android/layout_tests/fast/js/bitwise-and-on-undefined.html +/sdcard/android/layout_tests/fast/js/exception-thrown-from-eval-inside-closure.html +/sdcard/android/layout_tests/fast/js/string_replace.html +/sdcard/android/layout_tests/fast/js/ignored-result-ref-crash.html +/sdcard/android/layout_tests/fast/js/function-toString-object-literals.html +/sdcard/android/layout_tests/fast/js/numeric-conversion.html +/sdcard/android/layout_tests/fast/js/select-options-remove.html +/sdcard/android/layout_tests/fast/js/array-tostring-ignore-separator.html +/sdcard/android/layout_tests/fast/js/number-toExponential.html +/sdcard/android/layout_tests/fast/js/direct-entry-to-function-code.html +/sdcard/android/layout_tests/fast/js/vardecl-preserve-vardecl.html +/sdcard/android/layout_tests/fast/js/unexpected-constant-crash.html +/sdcard/android/layout_tests/fast/js/var-shadows-arg-gc-crash.html +/sdcard/android/layout_tests/fast/js/arguments-bad-index.html +/sdcard/android/layout_tests/fast/js/resize-array-assign.html +/sdcard/android/layout_tests/fast/js/number-toString.html +/sdcard/android/layout_tests/fast/js/this-non-object-proto.html +/sdcard/android/layout_tests/fast/js/exception-thrown-from-new.html +/sdcard/android/layout_tests/fast/js/cyclic-proto.html +/sdcard/android/layout_tests/fast/js/vardecl-preserve-arguments.html +/sdcard/android/layout_tests/fast/js/regexp-compile-crash.html +/sdcard/android/layout_tests/fast/js/var-declarations-shadowing.html +/sdcard/android/layout_tests/fast/js/ignored-result-null-comparison-crash.html +/sdcard/android/layout_tests/fast/js/array-sort-reentrance.html +/sdcard/android/layout_tests/fast/js/toString-for-var-decl.html +/sdcard/android/layout_tests/fast/js/string-slice-abnormal-values.html +/sdcard/android/layout_tests/fast/js/exception-linenums-in-html-1.html +/sdcard/android/layout_tests/fast/js/do-while-without-semicolon.html +/sdcard/android/layout_tests/fast/js/object-prototype-toLocaleString.html +/sdcard/android/layout_tests/fast/js/function-redefinition.html +/sdcard/android/layout_tests/fast/js/function-name.html +/sdcard/android/layout_tests/fast/js/logical-or-jless.html +/sdcard/android/layout_tests/fast/js/regexp-non-character.html +/sdcard/android/layout_tests/fast/js/assign.html +/sdcard/android/layout_tests/fast/js/for-in-avoid-duplicates.html +/sdcard/android/layout_tests/fast/js/sort-stability.html +/sdcard/android/layout_tests/fast/js/duplicate-param-gc-crash.html +/sdcard/android/layout_tests/fast/js/regexp-stack-overflow.html +/sdcard/android/layout_tests/fast/js/function-argument-evaluation-before-exception.html +/sdcard/android/layout_tests/fast/js/number-toprecision.html +/sdcard/android/layout_tests/fast/js/string-property-iteration.html +/sdcard/android/layout_tests/fast/js/do-while-semicolon.html +/sdcard/android/layout_tests/fast/js/regexp-divequal.html +/sdcard/android/layout_tests/fast/js/named-function-expression.html +/sdcard/android/layout_tests/fast/js/array-iterate-backwards.html +/sdcard/android/layout_tests/fast/js/constructor-attributes.html +/sdcard/android/layout_tests/fast/js/array-some.html +/sdcard/android/layout_tests/fast/js/missing-title-end-tag-js.html +/sdcard/android/layout_tests/fast/js/object-extra-comma.html +/sdcard/android/layout_tests/fast/js/number-tofixed.html +/sdcard/android/layout_tests/fast/js/function-declarations-in-switch-statement.html +/sdcard/android/layout_tests/fast/js/regexp-extended-characters-crash.html +/sdcard/android/layout_tests/fast/js/typeof-codegen-crash.html +/sdcard/android/layout_tests/fast/js/array-indexof.html +/sdcard/android/layout_tests/fast/js/mod-crash.html +/sdcard/android/layout_tests/fast/js/eval-keyword-vs-function.html +/sdcard/android/layout_tests/fast/js/debugger.html +/sdcard/android/layout_tests/fast/js/rehash-assign.html +/sdcard/android/layout_tests/fast/js/object-prototype-constructor.html +/sdcard/android/layout_tests/fast/js/string-replace-exception-crash.html +/sdcard/android/layout_tests/fast/js/date-big-setmonth.html +/sdcard/android/layout_tests/fast/js/exception-linenums-in-html-2.html +/sdcard/android/layout_tests/fast/js/select-options-add.html +/sdcard/android/layout_tests/fast/js/toString-dontEnum.html +/sdcard/android/layout_tests/fast/js/toString-elision-trailing-comma.html +/sdcard/android/layout_tests/fast/js/regexp-negative-special-characters.html +/sdcard/android/layout_tests/fast/js/getter-setter-gc.html +/sdcard/android/layout_tests/fast/js/string-substr.html +/sdcard/android/layout_tests/fast/js/for-in-var-scope.html +/sdcard/android/layout_tests/fast/js/exec-state-marking.html +/sdcard/android/layout_tests/fast/js/string-sort.html +/sdcard/android/layout_tests/fast/js/primitive-method-this.html +/sdcard/android/layout_tests/fast/js/delete-getters-setters.html +/sdcard/android/layout_tests/fast/js/const-without-initializer.html +/sdcard/android/layout_tests/fast/js/sparse-array.html +/sdcard/android/layout_tests/fast/js/same-origin-subframe-about-blank.html +/sdcard/android/layout_tests/fast/js/nested-function-scope.html +/sdcard/android/layout_tests/fast/js/reparsing-semicolon-insertion.html +/sdcard/android/layout_tests/fast/js/regexp-non-capturing-groups.html +/sdcard/android/layout_tests/fast/js/has-own-property.html +/sdcard/android/layout_tests/fast/js/window-location-href-file-urls.html +/sdcard/android/layout_tests/fast/js/convert-nan-to-bool.html +/sdcard/android/layout_tests/fast/js/regexp-extended-characters-more.html +/sdcard/android/layout_tests/fast/js/arguments.html +/sdcard/android/layout_tests/fast/js/prefix-syntax.html +/sdcard/android/layout_tests/fast/js/exception-with-handler-inside-eval-with-dynamic-scope.html +/sdcard/android/layout_tests/fast/js/for-in-exeception.html +/sdcard/android/layout_tests/fast/js/array-lastIndexOf.html +/sdcard/android/layout_tests/fast/js/modify-non-references.html +/sdcard/android/layout_tests/fast/js/regexp-find-first-asserted.html +/sdcard/android/layout_tests/fast/js/sort-randomly.html +/sdcard/android/layout_tests/fast/js/array-indexing.html +/sdcard/android/layout_tests/fast/js/regexp-caching.html +/sdcard/android/layout_tests/fast/js/typeof-syntax.html +/sdcard/android/layout_tests/fast/js/regexp-character-match-out-of-order.html +/sdcard/android/layout_tests/fast/js/function-call-register-allocation.html +/sdcard/android/layout_tests/fast/js/constant-folding.html +/sdcard/android/layout_tests/fast/js/activation-object-function-lifetime.html +/sdcard/android/layout_tests/fast/js/array-filter.html +/sdcard/android/layout_tests/fast/js/implicit-global-to-global-reentry.html +/sdcard/android/layout_tests/fast/js/array-foreach.html +/sdcard/android/layout_tests/fast/js/regexp-many-brackets.html +/sdcard/android/layout_tests/fast/js/activation-proto.html +/sdcard/android/layout_tests/fast/js/toString-overrides.html +/sdcard/android/layout_tests/fast/js/regexp-unicode-overflow.html +/sdcard/android/layout_tests/fast/js/postfix-syntax.html +/sdcard/android/layout_tests/fast/js/global-recursion-on-full-stack.html +/sdcard/android/layout_tests/fast/js/number-cell-reuse.html +/sdcard/android/layout_tests/fast/js/closure-inside-extra-arg-call.html +/sdcard/android/layout_tests/fast/js/removing-Cf-characters.html +/sdcard/android/layout_tests/fast/js/pretty-print.html +/sdcard/android/layout_tests/fast/js/const.html +/sdcard/android/layout_tests/fast/js/isPrototypeOf.html +/sdcard/android/layout_tests/fast/js/math.html +/sdcard/android/layout_tests/fast/js/string-from-char-code.html +/sdcard/android/layout_tests/fast/js/eval-overriding.html +/sdcard/android/layout_tests/fast/js/regexp-char-insensitive.html +/sdcard/android/layout_tests/fast/js/array-float-delete.html +/sdcard/android/layout_tests/fast/js/array-index-immediate-types.html +/sdcard/android/layout_tests/fast/js/integer-extremes.html +/sdcard/android/layout_tests/fast/js/regexp-non-bmp.html +/sdcard/android/layout_tests/fast/js/delete-then-put.html +/sdcard/android/layout_tests/fast/js/string-replace-2.html +/sdcard/android/layout_tests/fast/js/cached-eval-gc.html +/sdcard/android/layout_tests/fast/js/property-getters-and-setters.html +/sdcard/android/layout_tests/fast/js/array-reset-large-index.html +/sdcard/android/layout_tests/fast/js/date-proto-generic-invocation.html +/sdcard/android/layout_tests/fast/js/lastModified.html +/sdcard/android/layout_tests/fast/js/encode-URI-test.html +/sdcard/android/layout_tests/fast/js/codegen-loops-logical-nodes.html +/sdcard/android/layout_tests/fast/js/string-capitalization.html +/sdcard/android/layout_tests/fast/js/caller-property.html +/sdcard/android/layout_tests/fast/js/date-DST-time-cusps.html +/sdcard/android/layout_tests/fast/js/regexp-unicode-handling.html +/sdcard/android/layout_tests/fast/js/unmatching-argument-count.html +/sdcard/android/layout_tests/fast/js/delete-multiple-global-blocks.html +/sdcard/android/layout_tests/fast/js/text-field-resize.html +/sdcard/android/layout_tests/fast/js/duplicate-param-crash.html +/sdcard/android/layout_tests/fast/js/switch-behaviour.html +/sdcard/android/layout_tests/fast/js/delete-syntax.html +/sdcard/android/layout_tests/fast/js/date-DST-pre-1970.html +/sdcard/android/layout_tests/fast/js/array-splice.html +/sdcard/android/layout_tests/fast/js/statement-list-register-crash.html +/sdcard/android/layout_tests/fast/js/date-set-to-nan.html +/sdcard/android/layout_tests/fast/js/code-serialize-paren.html +/sdcard/android/layout_tests/fast/js/parse-backslash-before-newline.html +/sdcard/android/layout_tests/fast/js/delete-function-parameter.html +/sdcard/android/layout_tests/fast/js/exception-expression-offset.html +/sdcard/android/layout_tests/fast/js/invalid-syntax-for-function.html +/sdcard/android/layout_tests/fast/js/cyclic-prototypes.html +/sdcard/android/layout_tests/fast/js/equality.html +/sdcard/android/layout_tests/fast/js/order-of-operations.html +/sdcard/android/layout_tests/fast/js/regexp-no-extensions.html +/sdcard/android/layout_tests/fast/js/stack-unwinding.html +/sdcard/android/layout_tests/fast/js/reserved-words.html +/sdcard/android/layout_tests/fast/js/toString-try-else.html +/sdcard/android/layout_tests/fast/js/function-dot-arguments-and-caller.html +/sdcard/android/layout_tests/fast/js/do-while-expression-value.html +/sdcard/android/layout_tests/fast/js/bom-in-file-retains-correct-offset.html +/sdcard/android/layout_tests/fast/js/string-split-ignore-case.html +/sdcard/android/layout_tests/fast/js/date-constructor.html +/sdcard/android/layout_tests/fast/js/date-big-setdate.html +/sdcard/android/layout_tests/fast/js/array-every.html +/sdcard/android/layout_tests/fast/js/function-toString-parentheses.html +/sdcard/android/layout_tests/fast/js/array-functions-non-arrays.html +/sdcard/android/layout_tests/fast/js/while-expression-value.html +/sdcard/android/layout_tests/fast/js/string-replace-3.html +/sdcard/android/layout_tests/fast/js/avl-crash.html +/sdcard/android/layout_tests/fast/js/vardecl-blocks-init.html +/sdcard/android/layout_tests/fast/js/null-char-in-string.html +/sdcard/android/layout_tests/fast/js/codegen-temporaries-multiple-global-blocks.html +/sdcard/android/layout_tests/fast/js/char-at.html +/sdcard/android/layout_tests/fast/js/propertyIsEnumerable.html +/sdcard/android/layout_tests/fast/js/exception-thrown-from-equal.html +/sdcard/android/layout_tests/fast/js/constructor.html +/sdcard/android/layout_tests/fast/js/regexp-overflow.html +/sdcard/android/layout_tests/fast/js/var-declarations.html +/sdcard/android/layout_tests/fast/js/continue-break-multiple-labels.html +/sdcard/android/layout_tests/fast/js/toString-exception.html +/sdcard/android/layout_tests/fast/js/regexp-test-null-string.html +/sdcard/android/layout_tests/fast/js/date-parse-comments-test.html +/sdcard/android/layout_tests/fast/js/select-options-remove-gc.html +/sdcard/android/layout_tests/fast/js/array-tostring-and-join.html +/sdcard/android/layout_tests/fast/js/implicit-call-with-global-reentry.html +/sdcard/android/layout_tests/fast/js/function-names.html +/sdcard/android/layout_tests/fast/js/primitive-property-access-edge-cases.html +/sdcard/android/layout_tests/fast/js/date-preserve-milliseconds.html +/sdcard/android/layout_tests/fast/js/sort-large-array.html +/sdcard/android/layout_tests/fast/js/for-in-to-text.html +/sdcard/android/layout_tests/fast/js/global-var-limit.html +/sdcard/android/layout_tests/fast/js/static-scope-object.html +/sdcard/android/layout_tests/fast/js/var-shadows-arg-crash.html +/sdcard/android/layout_tests/fast/js/function-apply.html +/sdcard/android/layout_tests/fast/js/function-prototype.html +/sdcard/android/layout_tests/fast/js/tostring-exception-in-property-access.html +/sdcard/android/layout_tests/fast/js/function-declaration-statement.html +/sdcard/android/layout_tests/fast/js/date-negative-setmonth.html +/sdcard/android/layout_tests/fast/js/reentrant-call-unwind.html +/sdcard/android/layout_tests/fast/js/regexp-lastindex.html +/sdcard/android/layout_tests/fast/js/finally-codegen-failure.html +/sdcard/android/layout_tests/fast/js/read-modify-eval.html +/sdcard/android/layout_tests/fast/js/exception-thrown-from-function-with-lazy-activation.html +/sdcard/android/layout_tests/fast/js/cyclic-ref-toString.html +/sdcard/android/layout_tests/fast/js/date-big-constructor.html +/sdcard/android/layout_tests/fast/js/gmail-re-re.html +/sdcard/android/layout_tests/fast/js/deep-recursion-test.html +/sdcard/android/layout_tests/fast/js/lexical-lookup-in-function-constructor.html +/sdcard/android/layout_tests/fast/js/regexp-range-out-of-order.html +/sdcard/android/layout_tests/fast/js/throw-from-array-sort.html +/sdcard/android/layout_tests/fast/js/slash-lineterminator-parse.html +/sdcard/android/layout_tests/fast/js/dot-node-base-exception.html +/sdcard/android/layout_tests/fast/js/codegen-peephole-locals.html +/sdcard/android/layout_tests/fast/js/constant-count.html +/sdcard/android/layout_tests/fast/js/regexp-compile.html +/sdcard/android/layout_tests/fast/js/declaration-in-block.html +/sdcard/android/layout_tests/fast/js/eval-var-decl.html +/sdcard/android/layout_tests/fast/js/eval-cross-window.html +/sdcard/android/layout_tests/fast/js/function-decompilation-operators.html +/sdcard/android/layout_tests/fast/js/sort-non-numbers.html +/sdcard/android/layout_tests/fast/js/function-declarations.html +/sdcard/android/layout_tests/fast/js/non-object-proto.html +/sdcard/android/layout_tests/fast/js/regexp-extended-characters-match.html +/sdcard/android/layout_tests/fast/js/toString-number-dot-expr.html +/sdcard/android/layout_tests/fast/js/date-parse-test.html +/sdcard/android/layout_tests/fast/js/exception-try-finally-scope-error.html +/sdcard/android/layout_tests/fast/js/function-dot-arguments.html +/sdcard/android/layout_tests/fast/js/toString-prefix-postfix-preserve-parens.html +/sdcard/android/layout_tests/fast/js/regexp-ranges-and-escaped-hyphens.html +/sdcard/android/layout_tests/fast/js/exception-linenums.html +/sdcard/android/layout_tests/fast/js/array-holes.html +/sdcard/android/layout_tests/fast/js/construct-global-object.html +/sdcard/android/layout_tests/fast/js/codegen-temporaries.html +/sdcard/android/layout_tests/fast/js/array-join-bug-11524.html +/sdcard/android/layout_tests/fast/js/with-scope-gc.html +/sdcard/android/layout_tests/fast/js/array-map.html +/sdcard/android/layout_tests/fast/js/string-index-overflow.html +/sdcard/android/layout_tests/fast/js/eval-cache-crash.html +/sdcard/android/layout_tests/fast/js/typeof-constant-string.html +/sdcard/android/layout_tests/fast/js/comparefn-sort-stability.html +/sdcard/android/layout_tests/fast/js/navigator-plugins-crash.html +/sdcard/android/layout_tests/fast/js/vardecl-preserve-parameters.html +/sdcard/android/layout_tests/fast/inline/clean-after-removing-temp-boxes.html +/sdcard/android/layout_tests/fast/dom/HTMLTableElement/early-acid3-65-excerpt.html +/sdcard/android/layout_tests/fast/dom/HTMLTableElement/early-acid3-66-excerpt.html +/sdcard/android/layout_tests/fast/dom/HTMLTableElement/cellpadding-attribute.html +/sdcard/android/layout_tests/fast/dom/HTMLTableElement/insert-row.html +/sdcard/android/layout_tests/fast/dom/HTMLTableElement/tBodies.html +/sdcard/android/layout_tests/fast/dom/HTMLTableElement/rows.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/write-multiple-calls.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/document-special-properties.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/url-getset.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/writeln-call.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/document-plugins.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/title-get.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/object-by-name-unknown-child-element.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/write-call.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/object-by-name-or-id.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/document-open-return-value.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/writeln-multiple-calls.html +/sdcard/android/layout_tests/fast/dom/HTMLDocument/title-set.html +/sdcard/android/layout_tests/fast/dom/HTMLLabelElement/form/test1.html +/sdcard/android/layout_tests/fast/dom/HTMLSelectElement/options-collection-set-string-length.html +/sdcard/android/layout_tests/fast/dom/HTMLSelectElement/options-collection-detached.html +/sdcard/android/layout_tests/fast/dom/Document/replace-child.html +/sdcard/android/layout_tests/fast/dom/Document/title-property-creates-title-element.html +/sdcard/android/layout_tests/fast/dom/Document/createElementNS-namespace-err.html +/sdcard/android/layout_tests/fast/dom/Document/title-property-set-multiple-times.html +/sdcard/android/layout_tests/fast/dom/Document/document-reopen.html +/sdcard/android/layout_tests/fast/dom/Document/document-charset.html +/sdcard/android/layout_tests/fast/dom/Document/replaceChild-null-oldChild.html +/sdcard/android/layout_tests/fast/dom/Document/createAttributeNS-namespace-err.html +/sdcard/android/layout_tests/fast/dom/Document/open-with-pending-load.html +/sdcard/android/layout_tests/fast/dom/Document/doc-open-while-parsing.html +/sdcard/android/layout_tests/fast/dom/HTMLMetaElement/meta-attributes.html +/sdcard/android/layout_tests/fast/dom/Element/getAttribute-check-case-sensitivity.html +/sdcard/android/layout_tests/fast/dom/Element/attr-param-typechecking.html +/sdcard/android/layout_tests/fast/dom/Element/attribute-uppercase.html +/sdcard/android/layout_tests/fast/dom/Element/element-traversal.html +/sdcard/android/layout_tests/fast/dom/Element/onclick-case.html +/sdcard/android/layout_tests/fast/dom/Element/contains-method.html +/sdcard/android/layout_tests/fast/dom/Element/setAttribute-with-colon.html +/sdcard/android/layout_tests/fast/dom/Element/setAttribute-case-insensitivity.html +/sdcard/android/layout_tests/fast/dom/Element/dimension-properties-unrendered.html +/sdcard/android/layout_tests/fast/dom/Element/offsetTop-table-cell.html +/sdcard/android/layout_tests/fast/dom/DOMException/EventException.html +/sdcard/android/layout_tests/fast/dom/DOMException/prototype-object.html +/sdcard/android/layout_tests/fast/dom/DOMException/RangeException.html +/sdcard/android/layout_tests/fast/dom/HTMLButtonElement/value/getset.html +/sdcard/android/layout_tests/fast/dom/HTMLScriptElement/script-reexecution.html +/sdcard/android/layout_tests/fast/dom/HTMLScriptElement/script-set-src.html +/sdcard/android/layout_tests/fast/dom/HTMLScriptElement/script-load-events.html +/sdcard/android/layout_tests/fast/dom/HTMLScriptElement/script-decoding-error-after-setting-src.html +/sdcard/android/layout_tests/fast/dom/HTMLOptionElement/collection-setter-getter.html +/sdcard/android/layout_tests/fast/dom/HTMLOptionElement/set-option-index-text.html +/sdcard/android/layout_tests/fast/dom/HTMLOptionElement/option-text.html +/sdcard/android/layout_tests/fast/dom/HTMLOptionElement/option-prototype.html +/sdcard/android/layout_tests/fast/dom/NodeList/5725058-crash-scenario-1.html +/sdcard/android/layout_tests/fast/dom/NodeList/5725058-crash-scenario-2.html +/sdcard/android/layout_tests/fast/dom/NodeList/childNodes-reset-cache.html +/sdcard/android/layout_tests/fast/dom/NodeList/5725058-crash-scenario-3.html +/sdcard/android/layout_tests/fast/dom/NodeList/invalidate-node-lists-when-parsing.html +/sdcard/android/layout_tests/fast/dom/NodeList/item-by-id-with-no-document.html +/sdcard/android/layout_tests/fast/dom/NodeList/nodelist-item-with-name.html +/sdcard/android/layout_tests/fast/dom/DOMImplementation/createDocumentType-err.html +/sdcard/android/layout_tests/fast/dom/CSSStyleDeclaration/transition-property-names.html +/sdcard/android/layout_tests/fast/dom/CSSStyleDeclaration/css-properties-case-sensitive.html +/sdcard/android/layout_tests/fast/dom/CSSStyleDeclaration/empty-string-property.html +/sdcard/android/layout_tests/fast/dom/Node/initial-values.html +/sdcard/android/layout_tests/fast/dom/Node/DOMNodeRemovedEvent.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/viewless-document.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/caseID-almost-strict.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/elementRoot.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/caseID-strict.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/not-supported-namespace-in-selector.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/id-fastpath.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/dumpNodeList.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/caseTag.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/detached-element.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/caseID.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/bug-17313.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/id-fastpath-almost-strict.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/id-fastpath-strict.html +/sdcard/android/layout_tests/fast/dom/SelectorAPI/dumpNodeList-almost-strict.html +/sdcard/android/layout_tests/fast/dom/HTMLTableSectionElement/rows.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/array/001.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/array/002.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/array/003.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/array/004.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/002.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/012.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/004.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/014.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/006.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/008.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/dumpNodeList.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/001.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/003.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/013.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/005.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/015.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/007.html +/sdcard/android/layout_tests/fast/dom/getElementsByClassName/009.html +/sdcard/android/layout_tests/fast/dom/HTMLInputElement/checked-pseudo-selector.html +/sdcard/android/layout_tests/fast/dom/HTMLInputElement/input-text-reset.html +/sdcard/android/layout_tests/fast/dom/HTMLInputElement/size-as-number.html +/sdcard/android/layout_tests/fast/dom/HTMLInputElement/duplicate-element-names.html +/sdcard/android/layout_tests/fast/dom/HTMLInputElement/input-hidden-value.html +/sdcard/android/layout_tests/fast/dom/HTMLInputElement/input-checked-reset.html +/sdcard/android/layout_tests/fast/dom/HTMLInputElement/size-attribute.html +/sdcard/android/layout_tests/fast/dom/TreeWalker/TreeWalker-currentNode.html +/sdcard/android/layout_tests/fast/dom/HTMLDivElement/align/getset.html +/sdcard/android/layout_tests/fast/dom/Text/replaceWholeText.html +/sdcard/android/layout_tests/fast/dom/HTMLFormElement/htmlformelement-indexed-getter.html +/sdcard/android/layout_tests/fast/dom/HTMLFormElement/elements-not-in-document.html +/sdcard/android/layout_tests/fast/dom/Window/window-closed-crash.html +/sdcard/android/layout_tests/fast/dom/Window/setTimeout-no-arguments.html +/sdcard/android/layout_tests/fast/dom/Window/window-open-self.html +/sdcard/android/layout_tests/fast/dom/Window/getMatchedCSSRules-null-crash.html +/sdcard/android/layout_tests/fast/dom/Window/window-open-self-from-other-frame.html +/sdcard/android/layout_tests/fast/dom/Window/window-custom-prototype-crash.html +/sdcard/android/layout_tests/fast/dom/Window/window-object-cross-frame-calls.html +/sdcard/android/layout_tests/fast/dom/Window/window-location-replace-functions.html +/sdcard/android/layout_tests/fast/dom/Window/attr-constructor.html +/sdcard/android/layout_tests/fast/dom/Window/window-remove-event-listener.html +/sdcard/android/layout_tests/fast/dom/Window/window-function-frame-getter-precedence.html +/sdcard/android/layout_tests/fast/dom/Window/atob-btoa.html +/sdcard/android/layout_tests/fast/dom/Window/clear-timeout.html +/sdcard/android/layout_tests/fast/dom/Window/window-property-clearing.html +/sdcard/android/layout_tests/fast/dom/Window/element-constructors-on-window.html +/sdcard/android/layout_tests/fast/dom/Window/orphaned-frame-access.html +/sdcard/android/layout_tests/fast/dom/Window/redirect-with-timer.html +/sdcard/android/layout_tests/fast/dom/Window/window-resize-and-move-sub-frame.html +/sdcard/android/layout_tests/fast/dom/Window/window-open-parent.html +/sdcard/android/layout_tests/fast/dom/Window/console-trace.html +/sdcard/android/layout_tests/fast/dom/Window/alert-undefined.html +/sdcard/android/layout_tests/fast/dom/Window/window-open-top.html +/sdcard/android/layout_tests/fast/dom/Window/window-appendages-cleared.html +/sdcard/android/layout_tests/fast/dom/Window/window-open-parent-no-parent.html +/sdcard/android/layout_tests/fast/dom/Window/closure-access-after-navigation-iframe.html +/sdcard/android/layout_tests/fast/dom/HTMLTableRowElement/cells.html +/sdcard/android/layout_tests/fast/dom/HTMLTableRowElement/insertCell.html +/sdcard/android/layout_tests/fast/dom/HTMLFontElement/size-attribute.html +/sdcard/android/layout_tests/fast/dom/HTMLObjectElement/form/test1.html +/sdcard/android/layout_tests/fast/dom/HTMLObjectElement/object-as-frame.html +/sdcard/android/layout_tests/fast/dom/HTMLElement/set-inner-outer-optimization.html +/sdcard/android/layout_tests/fast/dom/Range/compareBoundaryPoints-1.html +/sdcard/android/layout_tests/fast/dom/Range/range-compareNode.html +/sdcard/android/layout_tests/fast/dom/Range/range-comparePoint.html +/sdcard/android/layout_tests/fast/dom/Range/acid3-surround-contents.html +/sdcard/android/layout_tests/fast/dom/Range/mutation.html +/sdcard/android/layout_tests/fast/dom/Range/13000.html +/sdcard/android/layout_tests/fast/dom/Range/range-processing-instructions.html +/sdcard/android/layout_tests/fast/dom/Range/range-insertNode-separate-endContainer.html +/sdcard/android/layout_tests/fast/dom/Range/range-intersectsNode.html +/sdcard/android/layout_tests/fast/dom/Range/range-isPointInRange.html +/sdcard/android/layout_tests/fast/dom/Range/range-clone-empty.html +/sdcard/android/layout_tests/fast/dom/Range/compareBoundaryPoints-2.html +/sdcard/android/layout_tests/fast/dom/Range/range-modifycontents.html +/sdcard/android/layout_tests/fast/dom/Range/range-insertNode-splittext.html +/sdcard/android/layout_tests/fast/dom/Range/surroundContents-check-boundary-points.html +/sdcard/android/layout_tests/fast/dom/Range/range-exceptions.html +/sdcard/android/layout_tests/fast/dom/HTMLHeadElement/head-check.html +/sdcard/android/layout_tests/fast/dom/HTMLHtmlElement/set-version.html +/sdcard/android/layout_tests/fast/dom/HTMLHtmlElement/duplicate-html-element-crash.html +/sdcard/android/layout_tests/fast/dom/HTMLImageElement/image-lowsrc-getset.html +/sdcard/android/layout_tests/fast/dom/HTMLImageElement/image-src-absolute-url.html +/sdcard/android/layout_tests/fast/dom/HTMLImageElement/image-loading-gc.html +/sdcard/android/layout_tests/fast/dom/HTMLImageElement/image-longdesc-absolute-url.html +/sdcard/android/layout_tests/fast/dom/HTMLImageElement/constructor-mutation-event-dispatch.html +/sdcard/android/layout_tests/fast/dom/HTMLImageElement/image-without-renderer-width.html +/sdcard/android/layout_tests/fast/dom/HTMLImageElement/image-natural-width-height.html +/sdcard/android/layout_tests/fast/dom/StyleSheet/ownerNode-lifetime.html +/sdcard/android/layout_tests/fast/dom/EntityReference/readonly-exceptions.html +/sdcard/android/layout_tests/fast/dom/script-element-remove-self.html +/sdcard/android/layout_tests/fast/dom/remove-named-attribute-crash.html +/sdcard/android/layout_tests/fast/dom/node-item.html +/sdcard/android/layout_tests/fast/dom/clone-node-style.html +/sdcard/android/layout_tests/fast/dom/script-element-without-frame-crash.html +/sdcard/android/layout_tests/fast/dom/script-element-gc.html +/sdcard/android/layout_tests/fast/dom/duplicate-ids.html +/sdcard/android/layout_tests/fast/dom/prototypes.html +/sdcard/android/layout_tests/fast/dom/clone-node-form-elements.html +/sdcard/android/layout_tests/fast/dom/import-attribute-node.html +/sdcard/android/layout_tests/fast/dom/getter-on-window-object2.html +/sdcard/android/layout_tests/fast/dom/objc-big-method-name.html +/sdcard/android/layout_tests/fast/dom/importNode-prefix.html +/sdcard/android/layout_tests/fast/dom/css-dom-read.html +/sdcard/android/layout_tests/fast/dom/image-object.html +/sdcard/android/layout_tests/fast/dom/gc-5.html +/sdcard/android/layout_tests/fast/dom/node-filter-gc.html +/sdcard/android/layout_tests/fast/dom/noscript-canvas-in-created-html-document.html +/sdcard/android/layout_tests/fast/dom/DOMParser-assign-variable.html +/sdcard/android/layout_tests/fast/dom/timer-clear-interval-in-handler.html +/sdcard/android/layout_tests/fast/dom/implementation-createHTMLDocument.html +/sdcard/android/layout_tests/fast/dom/iframe-document.html +/sdcard/android/layout_tests/fast/dom/document-all-input.html +/sdcard/android/layout_tests/fast/dom/null-document-location-href-put-crash.html +/sdcard/android/layout_tests/fast/dom/getelementsbytagnamens-mixed-namespaces.html +/sdcard/android/layout_tests/fast/dom/object-plugin-hides-properties.html +/sdcard/android/layout_tests/fast/dom/gc-2.html +/sdcard/android/layout_tests/fast/dom/computed-style-set-property.html +/sdcard/android/layout_tests/fast/dom/inner-text-001.html +/sdcard/android/layout_tests/fast/dom/css-selectorText.html +/sdcard/android/layout_tests/fast/dom/replace-first-child.html +/sdcard/android/layout_tests/fast/dom/importNode-null.html +/sdcard/android/layout_tests/fast/dom/select-selectedIndex-multiple.html +/sdcard/android/layout_tests/fast/dom/xmlhttprequest-invalid-values.html +/sdcard/android/layout_tests/fast/dom/space-to-text.html +/sdcard/android/layout_tests/fast/dom/css-set-property-exception.html +/sdcard/android/layout_tests/fast/dom/java-applet-calls.html +/sdcard/android/layout_tests/fast/dom/plugin-attributes-enumeration.html +/sdcard/android/layout_tests/fast/dom/html-attribute-types.html +/sdcard/android/layout_tests/fast/dom/resource-locations-in-created-html-document.html +/sdcard/android/layout_tests/fast/dom/comment-document-fragment.html +/sdcard/android/layout_tests/fast/dom/createAttribute-exception.html +/sdcard/android/layout_tests/fast/dom/noscript-style.html +/sdcard/android/layout_tests/fast/dom/serialize-cdata.html +/sdcard/android/layout_tests/fast/dom/createDocument.html +/sdcard/android/layout_tests/fast/dom/getelementbyname-invalidation.html +/sdcard/android/layout_tests/fast/dom/capturing-event-listeners.html +/sdcard/android/layout_tests/fast/dom/title-text-property.html +/sdcard/android/layout_tests/fast/dom/incompatible-operations.html +/sdcard/android/layout_tests/fast/dom/xmlhttprequest-html-response-encoding.html +/sdcard/android/layout_tests/fast/dom/inner-text-rtl.html +/sdcard/android/layout_tests/fast/dom/createDocument-empty.html +/sdcard/android/layout_tests/fast/dom/documenturi-assigned-junk-implies-baseuri-null.html +/sdcard/android/layout_tests/fast/dom/option-properties.html +/sdcard/android/layout_tests/fast/dom/background-shorthand-csstext.html +/sdcard/android/layout_tests/fast/dom/Range-insertNode-crash.html +/sdcard/android/layout_tests/fast/dom/early-frame-url.html +/sdcard/android/layout_tests/fast/dom/everything-to-string.html +/sdcard/android/layout_tests/fast/dom/attribute-empty-value-no-children.html +/sdcard/android/layout_tests/fast/dom/length-attribute-mapping.html +/sdcard/android/layout_tests/fast/dom/documenturi-loses-to-base-tag.html +/sdcard/android/layout_tests/fast/dom/createDocumentType2.html +/sdcard/android/layout_tests/fast/dom/gc-6.html +/sdcard/android/layout_tests/fast/dom/attribute-case-sensitivity.html +/sdcard/android/layout_tests/fast/dom/compatMode-Compat.html +/sdcard/android/layout_tests/fast/dom/namespaces-1.html +/sdcard/android/layout_tests/fast/dom/getter-on-window-object.html +/sdcard/android/layout_tests/fast/dom/constructors-overriding.html +/sdcard/android/layout_tests/fast/dom/defaultView.html +/sdcard/android/layout_tests/fast/dom/collection-null-like-arguments.html +/sdcard/android/layout_tests/fast/dom/gc-3.html +/sdcard/android/layout_tests/fast/dom/compatMode-Strict.html +/sdcard/android/layout_tests/fast/dom/attribute-downcast-right.html +/sdcard/android/layout_tests/fast/dom/document-all-select.html +/sdcard/android/layout_tests/fast/dom/anchor-backslash.html +/sdcard/android/layout_tests/fast/dom/css-mediarule-functions.html +/sdcard/android/layout_tests/fast/dom/gc-acid3.html +/sdcard/android/layout_tests/fast/dom/duplicate-ids-document-order.html +/sdcard/android/layout_tests/fast/dom/exception-no-frame-inline-script-crash.html +/sdcard/android/layout_tests/fast/dom/XMLSerializer-doctype2.html +/sdcard/android/layout_tests/fast/dom/dir-no-body.html +/sdcard/android/layout_tests/fast/dom/null-document-window-open-crash.html +/sdcard/android/layout_tests/fast/dom/css-RGBValue.html +/sdcard/android/layout_tests/fast/dom/innerHTML-nbsp.html +/sdcard/android/layout_tests/fast/dom/documentElement-null.html +/sdcard/android/layout_tests/fast/dom/class-all-whitespace.html +/sdcard/android/layout_tests/fast/dom/wrapper-identity.html +/sdcard/android/layout_tests/fast/dom/null-document-location-assign-crash.html +/sdcard/android/layout_tests/fast/dom/createElement.html +/sdcard/android/layout_tests/fast/dom/createElement-with-column.xml +/sdcard/android/layout_tests/fast/dom/simultaneouslyRegsiteredTimerFireOrder.html +/sdcard/android/layout_tests/fast/dom/generic-form-element-assert.html +/sdcard/android/layout_tests/fast/dom/css-shortHands.html +/sdcard/android/layout_tests/fast/dom/dom-instanceof.html +/sdcard/android/layout_tests/fast/dom/array-special-accessors-should-ignore-items.html +/sdcard/android/layout_tests/fast/dom/element-attribute-js-null.html +/sdcard/android/layout_tests/fast/dom/css-dom-read-2.html +/sdcard/android/layout_tests/fast/dom/navigator-cookieEnabled-no-crash.html +/sdcard/android/layout_tests/fast/dom/import-document-fragment.html +/sdcard/android/layout_tests/fast/dom/setter-type-enforcement.html +/sdcard/android/layout_tests/fast/dom/XMLSerializer.html +/sdcard/android/layout_tests/fast/dom/navigator-vendorSub.html +/sdcard/android/layout_tests/fast/dom/gc-7.html +/sdcard/android/layout_tests/fast/dom/outerText-no-element.html +/sdcard/android/layout_tests/fast/dom/replace-child-siblings.html +/sdcard/android/layout_tests/fast/dom/constants.html +/sdcard/android/layout_tests/fast/dom/inner-text-with-no-renderer.html +/sdcard/android/layout_tests/fast/dom/onerror-img.html +/sdcard/android/layout_tests/fast/dom/document-attribute-js-null.html +/sdcard/android/layout_tests/fast/dom/css-element-attribute-js-null.html +/sdcard/android/layout_tests/fast/dom/gc-11.html +/sdcard/android/layout_tests/fast/dom/mutation-event-remove-inserted-node.html +/sdcard/android/layout_tests/fast/dom/null-chardata-crash.html +/sdcard/android/layout_tests/fast/dom/compatMode-AlmostStrict.html +/sdcard/android/layout_tests/fast/dom/createElement-with-column.html +/sdcard/android/layout_tests/fast/dom/exception-no-frame-timeout-crash.html +/sdcard/android/layout_tests/fast/dom/title-text-property-2.html +/sdcard/android/layout_tests/fast/dom/no-elements.html +/sdcard/android/layout_tests/fast/dom/non-numeric-values-numeric-parameters.html +/sdcard/android/layout_tests/fast/dom/gc-4.html +/sdcard/android/layout_tests/fast/dom/inner-width-height.html +/sdcard/android/layout_tests/fast/dom/XMLSerializer-doctype.html +/sdcard/android/layout_tests/fast/dom/createElementNS.html +/sdcard/android/layout_tests/fast/dom/undetectable-document-all.html +/sdcard/android/layout_tests/fast/dom/prototype-chain.html +/sdcard/android/layout_tests/fast/dom/gc-1.html +/sdcard/android/layout_tests/fast/dom/select-selectedIndex-bug-12942.html +/sdcard/android/layout_tests/fast/dom/frame-contentWindow-crash.html +/sdcard/android/layout_tests/fast/dom/namednodemap-namelookup.html +/sdcard/android/layout_tests/fast/dom/null-document-location-replace-crash.html +/sdcard/android/layout_tests/fast/dom/htmlcollection-detectability.html +/sdcard/android/layout_tests/fast/dom/documenturi-assigned-junk-implies-relative-urls-do-not-resolve.html +/sdcard/android/layout_tests/fast/dom/collection-namedItem-via-item.html +/sdcard/android/layout_tests/fast/dom/set-inner-text-newlines.html +/sdcard/android/layout_tests/fast/dom/document-dir-property.html +/sdcard/android/layout_tests/fast/dom/undetectable-style-filter.html +/sdcard/android/layout_tests/fast/dom/domListEnumeration.html +/sdcard/android/layout_tests/fast/dom/destroy-selected-radio-button-crash.html +/sdcard/android/layout_tests/fast/dom/script-add.html +/sdcard/android/layout_tests/fast/dom/iframe-contentWindow-crash.html +/sdcard/android/layout_tests/fast/dom/comment-dom-node.html +/sdcard/android/layout_tests/fast/dom/features.html +/sdcard/android/layout_tests/fast/dom/canvasContext2d-element-attribute-js-null.html +/sdcard/android/layout_tests/fast/dom/remove-style-element.html +/sdcard/android/layout_tests/fast/dom/attribute-namespaces-get-set.html +/sdcard/android/layout_tests/fast/dom/innerHTML-escaping-attribute.html +/sdcard/android/layout_tests/fast/dom/null-document-xmlhttprequest-open.html +/sdcard/android/layout_tests/fast/invalid/nestedh3s-rapidweaver.html +/sdcard/android/layout_tests/fast/forms/element-by-name.html +/sdcard/android/layout_tests/fast/forms/HTMLOptionElement_selected.html +/sdcard/android/layout_tests/fast/forms/willvalidate-003.html +/sdcard/android/layout_tests/fast/forms/radio-button-no-change-event.html +/sdcard/android/layout_tests/fast/forms/menulist-selection-reset.html +/sdcard/android/layout_tests/fast/forms/textfield-focus-out.html +/sdcard/android/layout_tests/fast/forms/willvalidate-000.html +/sdcard/android/layout_tests/fast/forms/form-data-encoding-normalization-overrun.html +/sdcard/android/layout_tests/fast/forms/select-reset.html +/sdcard/android/layout_tests/fast/forms/input-named-action-overrides-action-attribute.html +/sdcard/android/layout_tests/fast/forms/empty-get.html +/sdcard/android/layout_tests/fast/forms/display-none-in-onchange-keyboard.html +/sdcard/android/layout_tests/fast/forms/range-default-value.html +/sdcard/android/layout_tests/fast/forms/paste-into-textarea.html +/sdcard/android/layout_tests/fast/forms/4628409.html +/sdcard/android/layout_tests/fast/forms/radio-no-theme-padding.html +/sdcard/android/layout_tests/fast/forms/autofocus-opera-006.html +/sdcard/android/layout_tests/fast/forms/activate-and-disabled-elements.html +/sdcard/android/layout_tests/fast/forms/form-get-multipart2.html +/sdcard/android/layout_tests/fast/forms/select-replace-option.html +/sdcard/android/layout_tests/fast/forms/textarea-setvalue-submit.html +/sdcard/android/layout_tests/fast/forms/cursor-position.html +/sdcard/android/layout_tests/fast/forms/willvalidate-007.html +/sdcard/android/layout_tests/fast/forms/input-changing-value.html +/sdcard/android/layout_tests/fast/forms/double-focus.html +/sdcard/android/layout_tests/fast/forms/form-data-encoding-2.html +/sdcard/android/layout_tests/fast/forms/focus.html +/sdcard/android/layout_tests/fast/forms/button-in-forms-collection.html +/sdcard/android/layout_tests/fast/forms/input-delete.html +/sdcard/android/layout_tests/fast/forms/placeholder-non-textfield.html +/sdcard/android/layout_tests/fast/forms/element-order.html +/sdcard/android/layout_tests/fast/forms/willvalidate-001.html +/sdcard/android/layout_tests/fast/forms/option-constructor-selected.html +/sdcard/android/layout_tests/fast/forms/8250.html +/sdcard/android/layout_tests/fast/forms/input-zero-height-focus.html +/sdcard/android/layout_tests/fast/forms/var-name-conflict-in-form-event-handler.html +/sdcard/android/layout_tests/fast/forms/range-reset.html +/sdcard/android/layout_tests/fast/forms/textarea-linewrap-dynamic.html +/sdcard/android/layout_tests/fast/forms/select-remove-option.html +/sdcard/android/layout_tests/fast/forms/onselect-selectall.html +/sdcard/android/layout_tests/fast/forms/select-width-font-change.html +/sdcard/android/layout_tests/fast/forms/text-field-setvalue-crash.html +/sdcard/android/layout_tests/fast/forms/paste-multiline-text-input.html +/sdcard/android/layout_tests/fast/forms/form-get-multipart.html +/sdcard/android/layout_tests/fast/forms/tab-in-input.html +/sdcard/android/layout_tests/fast/forms/button-click-DOM.html +/sdcard/android/layout_tests/fast/forms/domstring-replace-crash.html +/sdcard/android/layout_tests/fast/forms/submit-nil-value-field-assert.html +/sdcard/android/layout_tests/fast/forms/autofocus-opera-007.html +/sdcard/android/layout_tests/fast/forms/form-get-multipart3.html +/sdcard/android/layout_tests/fast/forms/select-out-of-bounds-index.html +/sdcard/android/layout_tests/fast/forms/select-type-ahead-list-box-no-selection.html +/sdcard/android/layout_tests/fast/forms/selected-index-assert.html +/sdcard/android/layout_tests/fast/forms/remove-radio-button-assert.html +/sdcard/android/layout_tests/fast/forms/textarea-crlf.html +/sdcard/android/layout_tests/fast/forms/form-collection-lookup.html +/sdcard/android/layout_tests/fast/forms/autofocus-opera-004.html +/sdcard/android/layout_tests/fast/forms/select-list-box-mouse-focus.html +/sdcard/android/layout_tests/fast/forms/text-set-value-crash.html +/sdcard/android/layout_tests/fast/forms/willvalidate-008.html +/sdcard/android/layout_tests/fast/forms/autofocus-opera-001.html +/sdcard/android/layout_tests/fast/forms/select-namedItem.html +/sdcard/android/layout_tests/fast/forms/willvalidate-005.html +/sdcard/android/layout_tests/fast/forms/select-index-setter.html +/sdcard/android/layout_tests/fast/forms/option-change-single-selected.html +/sdcard/android/layout_tests/fast/forms/listbox-scroll-after-options-removed.html +/sdcard/android/layout_tests/fast/forms/willvalidate-002.html +/sdcard/android/layout_tests/fast/forms/form-data-encoding.html +/sdcard/android/layout_tests/fast/forms/input-appearance-elementFromPoint.html +/sdcard/android/layout_tests/fast/forms/select-set-inner.html +/sdcard/android/layout_tests/fast/forms/missing-action.html +/sdcard/android/layout_tests/fast/forms/textarea-scrollbar-height.html +/sdcard/android/layout_tests/fast/forms/textarea-default-value-leading-newline.html +/sdcard/android/layout_tests/fast/forms/autofocus-opera-008.html +/sdcard/android/layout_tests/fast/forms/listbox-typeahead-empty.html +/sdcard/android/layout_tests/fast/forms/submit-to-url-fragment.html +/sdcard/android/layout_tests/fast/forms/textarea-setvalue-without-renderer.html +/sdcard/android/layout_tests/fast/forms/hidden-input-not-enabled.html +/sdcard/android/layout_tests/fast/forms/autofocus-opera-005.html +/sdcard/android/layout_tests/fast/forms/input-appearance-maxlength.html +/sdcard/android/layout_tests/fast/forms/submit-with-base.html +/sdcard/android/layout_tests/fast/forms/willvalidate-009.html +/sdcard/android/layout_tests/fast/forms/input-setvalue-selection.html +/sdcard/android/layout_tests/fast/forms/autofocus-opera-002.html +/sdcard/android/layout_tests/fast/forms/old-names.html +/sdcard/android/layout_tests/fast/forms/willvalidate-006.html +/sdcard/android/layout_tests/fast/forms/focus-style-pending.html +/sdcard/android/layout_tests/fast/forms/textarea-hard-linewrap-empty.html +/sdcard/android/layout_tests/fast/forms/document-write.html +/sdcard/android/layout_tests/fast/forms/slow-click.html +/sdcard/android/layout_tests/fast/forms/autofocus-attribute.html +/sdcard/android/layout_tests/fast/table/incomplete-table-in-fragment-hang.html +/sdcard/android/layout_tests/fast/table/section-in-table-before-misnested-text-crash-css.html +/sdcard/android/layout_tests/fast/table/large-rowspan-crash.html +/sdcard/android/layout_tests/fast/table/colgroup-relative.html +/sdcard/android/layout_tests/fast/table/border-changes.html +/sdcard/android/layout_tests/fast/table/cell-in-row-before-misnested-text-crash-css.html +/sdcard/android/layout_tests/fast/table/incomplete-table-in-fragment-2.html +/sdcard/android/layout_tests/fast/table/rowindex-comment-nodes.html +/sdcard/android/layout_tests/fast/table/td-display-nowrap.html +/sdcard/android/layout_tests/fast/table/row-in-tbody-before-misnested-text-crash-css.html +/sdcard/android/layout_tests/fast/table/empty-auto-column-zero-divide.html +/sdcard/android/layout_tests/fast/table/form-in-tbody-before-misnested-text-crash-css.html +/sdcard/android/layout_tests/fast/table/form-in-table-before-misnested-text-crash-css.html +/sdcard/android/layout_tests/fast/table/destroy-cell-with-selection-crash.html +/sdcard/android/layout_tests/fast/table/form-in-row-before-misnested-text-crash-css.html +/sdcard/android/layout_tests/fast/css/counters/counter-function-input-2.html +/sdcard/android/layout_tests/fast/css/counters/counter-function-input.html +/sdcard/android/layout_tests/fast/css/counters/counter-number-input.html +/sdcard/android/layout_tests/fast/css/variables/invalid-identifier.html +/sdcard/android/layout_tests/fast/css/media-rule-dyn.html +/sdcard/android/layout_tests/fast/css/transform-function-lowercase-assert.html +/sdcard/android/layout_tests/fast/css/word-break-user-modify-allowed-values.html +/sdcard/android/layout_tests/fast/css/import-style-update.html +/sdcard/android/layout_tests/fast/css/outline-invert-assertion.html +/sdcard/android/layout_tests/fast/css/insertRule-font-face.html +/sdcard/android/layout_tests/fast/css/readonly-pseudoclass-opera-004.html +/sdcard/android/layout_tests/fast/css/transform-inline-style-remove.html +/sdcard/android/layout_tests/fast/css/padding-no-renderer.html +/sdcard/android/layout_tests/fast/css/transition_shorthand_parsing.html +/sdcard/android/layout_tests/fast/css/css-selector-text.html +/sdcard/android/layout_tests/fast/css/dashboard-regions-attr-crash.html +/sdcard/android/layout_tests/fast/css/readonly-pseudoclass-opera-001.html +/sdcard/android/layout_tests/fast/css/font-property-priority.html +/sdcard/android/layout_tests/fast/css/computed-style-negative-top.html +/sdcard/android/layout_tests/fast/css/device-aspect-ratio.html +/sdcard/android/layout_tests/fast/css/pseudostyle-anonymous-text.html +/sdcard/android/layout_tests/fast/css/css-properties-case-insensitive.html +/sdcard/android/layout_tests/fast/css/getComputedStyle-border-image.html +/sdcard/android/layout_tests/fast/css/getComputedStyle-border-spacing.html +/sdcard/android/layout_tests/fast/css/font-face-descriptor-multiple-values-parsing.html +/sdcard/android/layout_tests/fast/css/hexColor-isDigit-assert.html +/sdcard/android/layout_tests/fast/css/transform-inline-style.html +/sdcard/android/layout_tests/fast/css/child-selector-implicit-tbody.html +/sdcard/android/layout_tests/fast/css/outline-hidden-illegal-value.html +/sdcard/android/layout_tests/fast/css/emptyStyleTag.html +/sdcard/android/layout_tests/fast/css/stale-style-selector-crash-1.html +/sdcard/android/layout_tests/fast/css/getComputedStyle-background-size.html +/sdcard/android/layout_tests/fast/css/display-none-inline-style-change-crash.html +/sdcard/android/layout_tests/fast/css/getPropertyValue-clip.html +/sdcard/android/layout_tests/fast/css/border-image-crash.html +/sdcard/android/layout_tests/fast/css/getComputedStyle-border-box.html +/sdcard/android/layout_tests/fast/css/readonly-pseudoclass-opera-005.html +/sdcard/android/layout_tests/fast/css/insertRule-media.html +/sdcard/android/layout_tests/fast/css/font-face-multiple-families.html +/sdcard/android/layout_tests/fast/css/getPropertyValue-border.html +/sdcard/android/layout_tests/fast/css/readonly-pseudoclass-opera-002.html +/sdcard/android/layout_tests/fast/css/invalid-rule-value.html +/sdcard/android/layout_tests/fast/css/max-device-aspect-ratio.html +/sdcard/android/layout_tests/fast/css/background-currentcolor.html +/sdcard/android/layout_tests/fast/css/orphaned_units_crash.html +/sdcard/android/layout_tests/fast/css/getComputedStyle-relayout.html +/sdcard/android/layout_tests/fast/css/invalid-cursor-property-crash.html +/sdcard/android/layout_tests/fast/css/getComputedStyle-borderRadius.html +/sdcard/android/layout_tests/fast/css/sheet-title.html +/sdcard/android/layout_tests/fast/css/background-position-serialize.html +/sdcard/android/layout_tests/fast/css/getComputedStyle-background-position.html +/sdcard/android/layout_tests/fast/css/stale-style-selector-crash-2.html +/sdcard/android/layout_tests/fast/css/webkit-marquee-speed-unit-in-quirksmode.html +/sdcard/android/layout_tests/fast/css/CSSPrimitiveValue-exceptions.html +/sdcard/android/layout_tests/fast/css/empty-script.html +/sdcard/android/layout_tests/fast/css/mask-missing-image-crash.html +/sdcard/android/layout_tests/fast/css/parse-timing-function-crash.html +/sdcard/android/layout_tests/fast/css/background-position-inherit.html +/sdcard/android/layout_tests/fast/css/readonly-pseudoclass-opera-003.html +/sdcard/android/layout_tests/fast/css/overflow-property.html +/sdcard/android/layout_tests/fast/css/remove-shorthand.html +/sdcard/android/layout_tests/fast/css/getComputedStyle-zIndex-auto.html +/sdcard/android/layout_tests/fast/css/min-device-aspect-ratio.html +/sdcard/android/layout_tests/fast/css/case-transform.html +/sdcard/android/layout_tests/fast/css/nested-rule-parent-sheet.html +/sdcard/android/layout_tests/fast/css/font-family-initial.html +/sdcard/android/layout_tests/fast/css/computed-style-display-none.html +/sdcard/android/layout_tests/fast/css/small-caps-crash.html +/sdcard/android/layout_tests/fast/css/max-height-and-max-width.html +/sdcard/android/layout_tests/fast/css/legacy-opacity-styles.html +/sdcard/android/layout_tests/fast/css/transition-timing-function.html +/sdcard/android/layout_tests/fast/parser/remove-node-stack.html +/sdcard/android/layout_tests/fast/parser/remove-current-node-parent.html +/sdcard/android/layout_tests/fast/parser/entity-end-iframe-tag.html +/sdcard/android/layout_tests/fast/parser/nsup-entity.html +/sdcard/android/layout_tests/fast/parser/parse-wbr.html +/sdcard/android/layout_tests/fast/parser/residual-style-close-across-n-blocks.html +/sdcard/android/layout_tests/fast/parser/open-comment-in-script-tricky.html +/sdcard/android/layout_tests/fast/parser/tag-with-exclamation-point.html +/sdcard/android/layout_tests/fast/parser/p-in-scope-strict.html +/sdcard/android/layout_tests/fast/parser/hex-entities-length.html +/sdcard/android/layout_tests/fast/parser/entity-end-style-tag.html +/sdcard/android/layout_tests/fast/parser/entity-end-xmp-tag.html +/sdcard/android/layout_tests/fast/parser/html-whitespace.html +/sdcard/android/layout_tests/fast/parser/head-comment.html +/sdcard/android/layout_tests/fast/parser/test-unicode-characters-in-attribute-name.html +/sdcard/android/layout_tests/fast/parser/entity-end-textarea-tag.html +/sdcard/android/layout_tests/fast/parser/script-after-frameset-assert.html +/sdcard/android/layout_tests/fast/parser/duplicate-html-body-element-IDs.html +/sdcard/android/layout_tests/fast/parser/comment-in-title.html +/sdcard/android/layout_tests/fast/parser/residual-style-close-across-removed-block.html +/sdcard/android/layout_tests/fast/parser/entity-comment-in-title.html +/sdcard/android/layout_tests/fast/parser/assertion-empty-attribute.html +/sdcard/android/layout_tests/fast/parser/entity-end-title-tag.html +/sdcard/android/layout_tests/fast/parser/comment-in-script-tricky.html +/sdcard/android/layout_tests/fast/parser/pre-first-line-break.html +/sdcard/android/layout_tests/fast/parser/rewrite-form.html +/sdcard/android/layout_tests/fast/parser/number-sign-in-map-name.html +/sdcard/android/layout_tests/fast/parser/entity-comment-in-script-tricky.html +/sdcard/android/layout_tests/fast/parser/input-textarea-inside-select-element.html +/sdcard/android/layout_tests/fast/parser/entities-in-html.html +/sdcard/android/layout_tests/fast/parser/remove-parser-current-node.html +/sdcard/android/layout_tests/fast/parser/area-in-div.html +/sdcard/android/layout_tests/fast/parser/rewrite-map.html +/sdcard/android/layout_tests/fast/parser/entity-surrogate-pairs.html +/sdcard/android/layout_tests/fast/parser/strict-img-in-map.html +/sdcard/android/layout_tests/fast/parser/p-in-scope.html +/sdcard/android/layout_tests/fast/layers/removed-by-scroll-handler.html +/sdcard/android/layout_tests/fast/layers/generated-layer-scrollbar-crash.html +/sdcard/android/layout_tests/fast/layers/resize-layer-deletion-crash.html +/sdcard/android/layout_tests/fast/loader/early-load-cancel.html +/sdcard/android/layout_tests/fast/loader/iframe-recursive-synchronous-load.html +/sdcard/android/layout_tests/fast/loader/xmlhttprequest-bad-mimetype.html +/sdcard/android/layout_tests/fast/loader/local-css-allowed-in-strict-mode.html +/sdcard/android/layout_tests/fast/loader/user-style-sheet-resource-load-callbacks.html +/sdcard/android/layout_tests/fast/loader/url-strip-cr-lf-tab.html +/sdcard/android/layout_tests/fast/loader/unloadable-script.html +/sdcard/android/layout_tests/fast/loader/url-parse-1.html +/sdcard/android/layout_tests/fast/loader/redirect-with-open-subframe-2.html +/sdcard/android/layout_tests/fast/loader/simultaneous-reloads-assert.html +/sdcard/android/layout_tests/fast/loader/invalid-charset-on-script-crashes-loader.html +/sdcard/android/layout_tests/fast/loader/javascript-url-encoding.html +/sdcard/android/layout_tests/fast/loader/charset-parse.html +/sdcard/android/layout_tests/fast/loader/meta-refresh-vs-open.html +/sdcard/android/layout_tests/fast/loader/url-data-replace-backslash.html +/sdcard/android/layout_tests/fast/loader/redirect-with-open-subframe.html +/sdcard/android/layout_tests/fast/loader/empty-ref-versus-no-ref.html +/sdcard/android/layout_tests/fast/loader/window-clearing.html +/sdcard/android/layout_tests/fast/loader/javascript-url-encoding-2.html +/sdcard/android/layout_tests/fast/loader/external-script-URL-location.html +/sdcard/android/layout_tests/fast/loader/loadInProgress.html +/sdcard/android/layout_tests/fast/loader/inherit-charset-to-empty-frame.html +/sdcard/android/layout_tests/fast/loader/font-face-empty.html +/sdcard/android/layout_tests/fast/loader/data-url-encoding-html.html +/sdcard/android/layout_tests/fast/loader/file-URL-with-port-number.html +/sdcard/android/layout_tests/fast/loader/link-no-URL.html +/sdcard/android/layout_tests/fast/canvas/pattern-with-transform.html +/sdcard/android/layout_tests/fast/canvas/gradient-addColorStop-with-invalid-color.html +/sdcard/android/layout_tests/fast/canvas/canvas-gradient-without-path.html +/sdcard/android/layout_tests/fast/canvas/canvas-pattern-behaviour.html +/sdcard/android/layout_tests/fast/canvas/radialGradient-infinite-values.html +/sdcard/android/layout_tests/fast/canvas/drawImage-with-negative-source-destination.html +/sdcard/android/layout_tests/fast/canvas/drawImage-with-invalid-args.html +/sdcard/android/layout_tests/fast/canvas/canvas-stroke-empty-fill.html +/sdcard/android/layout_tests/fast/canvas/access-zero-sized-canvas.html +/sdcard/android/layout_tests/fast/canvas/script-inside-canvas-fallback.html +/sdcard/android/layout_tests/fast/canvas/unclosed-canvas-2.html +/sdcard/android/layout_tests/fast/canvas/create-pattern-does-not-crash.html +/sdcard/android/layout_tests/fast/canvas/gradient-with-clip.html +/sdcard/android/layout_tests/fast/canvas/canvas-hides-fallback.html +/sdcard/android/layout_tests/fast/canvas/arc-crash.html +/sdcard/android/layout_tests/fast/canvas/canvas-ImageData-behaviour.html +/sdcard/android/layout_tests/fast/canvas/canvas-putImageData.html +/sdcard/android/layout_tests/fast/canvas/unclosed-canvas-4.html +/sdcard/android/layout_tests/fast/canvas/canvas-invalid-fillstyle.html +/sdcard/android/layout_tests/fast/canvas/unclosed-canvas-1.html +/sdcard/android/layout_tests/fast/canvas/toDataURL-noData.html +/sdcard/android/layout_tests/fast/canvas/canvas-with-incorrect-args.html +/sdcard/android/layout_tests/fast/canvas/canvas-path-with-inf-nan-dimensions.html +/sdcard/android/layout_tests/fast/canvas/canvas-radial-gradient-spreadMethod.html +/sdcard/android/layout_tests/fast/canvas/canvas-set-properties-with-non-invertible-ctm.html +/sdcard/android/layout_tests/fast/canvas/canvas-invalid-strokestyle.html +/sdcard/android/layout_tests/fast/canvas/canvas-strokeRect.html +/sdcard/android/layout_tests/fast/canvas/canvas-pattern-transform.html +/sdcard/android/layout_tests/fast/canvas/canvas-transparency-and-composite.html +/sdcard/android/layout_tests/fast/canvas/unclosed-canvas-3.html +/sdcard/android/layout_tests/fast/canvas/linearGradient-infinite-values.html +/sdcard/android/layout_tests/fast/canvas/canvas-setTransform.html +/sdcard/android/layout_tests/fast/frames/frame-set-same-location.html +/sdcard/android/layout_tests/fast/frames/set-unloaded-frame-location.html +/sdcard/android/layout_tests/fast/frames/negative-remaining-length-crash.html +/sdcard/android/layout_tests/fast/frames/frame-name-reset.html +/sdcard/android/layout_tests/fast/frames/frame-set-same-src.html +/sdcard/android/layout_tests/fast/frames/crash-removed-iframe.html +/sdcard/android/layout_tests/fast/frames/empty-frame-document.html +/sdcard/android/layout_tests/fast/frames/viewsource-plain-text-tags.html +/sdcard/android/layout_tests/fast/frames/location-put-after-removal.html +/sdcard/android/layout_tests/fast/frames/repaint-display-none-crash.html +/sdcard/android/layout_tests/fast/frames/remove-frame-with-scrollbars-crash.html +/sdcard/android/layout_tests/fast/frames/cross-site-this.html +/sdcard/android/layout_tests/fast/frames/onload-remove-iframe-crash.html +/sdcard/android/layout_tests/fast/frames/iframe-set-inner-html.html +/sdcard/android/layout_tests/fast/frames/iframe-remove-after-id-change.html +/sdcard/android/layout_tests/fast/frames/iframe-target.html +/sdcard/android/layout_tests/fast/frames/hover-timer-crash.html +/sdcard/android/layout_tests/fast/frames/iframe-set-same-src.html +/sdcard/android/layout_tests/fast/frames/iframe-double-attach.html +/sdcard/android/layout_tests/fast/frames/iframe-set-same-location.html +/sdcard/android/layout_tests/fast/frames/iframe-js-url-clientWidth.html +/sdcard/android/layout_tests/fast/frames/location-change.html +/sdcard/android/layout_tests/fast/frames/frame-base-url.html +/sdcard/android/layout_tests/fast/frames/iframe-display-none.html +/sdcard/android/layout_tests/fast/frames/frame-display-none-focus.html +/sdcard/android/layout_tests/fast/reflections/teardown-crash.html +/sdcard/android/layout_tests/fast/reflections/reflection-computed-style.html diff --git a/tests/DumpRenderTree/run_layout_tests.py b/tests/DumpRenderTree/run_layout_tests.py new file mode 100755 index 0000000000000000000000000000000000000000..5409a0cdb0e3da4c71b6cb5008604c65670bed48 --- /dev/null +++ b/tests/DumpRenderTree/run_layout_tests.py @@ -0,0 +1,286 @@ +#!/usr/bin/python + +"""Run layout tests using Android emulator and instrumentation. + + First, you need to get an SD card or sdcard image that has layout tests on it. + Layout tests are in following directory: + /sdcard/android/layout_tests + For example, /sdcard/android/layout_tests/fast + + Usage: + Run all tests under fast/ directory: + run_layout_tests.py, or + run_layout_tests.py fast + + Run all tests under a sub directory: + run_layout_tests.py fast/dom + + Run a single test: + run_layout_tests.py fast/dom/ + + After a merge, if there are changes of layout tests in SD card, you need to + use --refresh-test-list option *once* to re-generate test list on the card. + + Some other options are: + --rebaseline generates expected layout tests results under /sdcard/android/expected_result/ + --time-out-ms (default is 8000 millis) for each test + --adb-options="-e" passes option string to adb + --results-directory=..., (default is ./layout-test-results) directory name under which results are stored. +""" + +import logging +import optparse +import os +import subprocess +import sys +import time + +def CountLineNumber(filename): + """Compute the number of lines in a given file. + + Args: + filename: a file name related to the current directory. + """ + + fp = open(os.path.abspath(filename), "r"); + lines = 0 + for line in fp.readlines(): + lines = lines + 1 + fp.close() + return lines + +def DumpRenderTreeFinished(adb_cmd): + """ Check if DumpRenderTree finished running tests + + Args: + output: adb_cmd string + """ + + # pull /sdcard/android/running_test.txt, if the content is "#DONE", it's done + shell_cmd_str = adb_cmd + " shell cat /sdcard/android/running_test.txt" + adb_output = subprocess.Popen(shell_cmd_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] + return adb_output.strip() == "#DONE" + +def DiffResults(marker, new_results, old_results, diff_results, strip_reason): + """ Given two result files, generate diff and + write to diff_results file. All arguments are absolute paths + to files. + """ + old_file = open(old_results, "r") + new_file = open(new_results, "r") + diff_file = open(diff_results, "a") + + # Read lines from each file + ndict = new_file.readlines() + cdict = old_file.readlines() + + # Write marker to diff file + diff_file.writelines(marker + "\n") + diff_file.writelines("###############\n") + + # Strip reason from result lines + if strip_reason is True: + for i in range(0, len(ndict)): + ndict[i] = ndict[i].split(' ')[0] + "\n" + for i in range(0, len(cdict)): + cdict[i] = cdict[i].split(' ')[0] + "\n" + + # Find results in new_results missing in old_results + new_count=0 + for line in ndict: + if line not in cdict: + diff_file.writelines("+ " + line) + new_count += 1 + + # Find results in old_results missing in new_results + missing_count=0 + for line in cdict: + if line not in ndict: + diff_file.writelines("- " + line) + missing_count += 1 + + logging.info(marker + " >>> " + str(new_count) + " new, " + str(missing_count) + " misses") + + diff_file.writelines("\n\n") + + old_file.close() + new_file.close() + diff_file.close() + return + +def CompareResults(ref_dir, results_dir): + """Compare results in two directories + + Args: + ref_dir: the reference directory having layout results as references + results_dir: the results directory + """ + logging.info("Comparing results to " + ref_dir) + + diff_result = os.path.join(results_dir, "layout_tests_diff.txt") + if os.path.exists(diff_result): + os.remove(diff_result) + + files=["passed", "failed", "nontext", "crashed"] + for f in files: + result_file_name = "layout_tests_" + f + ".txt" + DiffResults(f, os.path.join(results_dir, result_file_name), + os.path.join(ref_dir, result_file_name), diff_result, + f == "failed") + logging.info("Detailed diffs are in " + diff_result) + +def main(options, args): + """Run the tests. Will call sys.exit when complete. + + Args: + options: a dictionary of command line options + args: a list of sub directories or files to test + """ + + # Set up logging format. + log_level = logging.INFO + if options.verbose: + log_level = logging.DEBUG + logging.basicConfig(level=log_level, + format='%(message)s') + + # Include all tests if none are specified. + if not args: + path = '/'; + else: + path = ' '.join(args); + + adb_cmd = "adb "; + if options.adb_options: + adb_cmd += options.adb_options + + # Re-generate the test list if --refresh-test-list is on + if options.refresh_test_list: + logging.info("Generating test list."); + generate_test_list_cmd_str = adb_cmd + " shell am instrument -e class com.android.dumprendertree.LayoutTestsAutoTest#generateTestList -e path \"" + path + "\" -w com.android.dumprendertree/.LayoutTestsAutoRunner" + adb_output = subprocess.Popen(generate_test_list_cmd_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] + + if adb_output.find('Process crashed') != -1: + logging.info("Aborting because cannot generate test list.\n" + adb_output) + sys.exit(1) + + + logging.info("Running tests") + + # Count crashed tests. + crashed_tests = [] + + timeout_ms = '5000' + if options.time_out_ms: + timeout_ms = options.time_out_ms + + # Run test until it's done + + run_layout_test_cmd_prefix = adb_cmd + " shell am instrument" + + run_layout_test_cmd_postfix = " -e path \"" + path + "\" -e timeout " + timeout_ms + if options.rebaseline: + run_layout_test_cmd_postfix += " -e rebaseline true" + run_layout_test_cmd_postfix += " -w com.android.dumprendertree/.LayoutTestsAutoRunner" + + # Call LayoutTestsAutoTest::startLayoutTests. + run_layout_test_cmd = run_layout_test_cmd_prefix + " -e class com.android.dumprendertree.LayoutTestsAutoTest#startLayoutTests" + run_layout_test_cmd_postfix + + adb_output = subprocess.Popen(run_layout_test_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] + while not DumpRenderTreeFinished(adb_cmd): + # Get the running_test.txt + logging.error("DumpRenderTree crashed, output:\n" + adb_output) + + shell_cmd_str = adb_cmd + " shell cat /sdcard/android/running_test.txt" + crashed_test = subprocess.Popen(shell_cmd_str, shell=True, stdout=subprocess.PIPE).communicate()[0] + + logging.info(crashed_test + " CRASHED"); + crashed_tests.append(crashed_test); + + logging.info("Resuming layout test runner..."); + # Call LayoutTestsAutoTest::resumeLayoutTests + run_layout_test_cmd = run_layout_test_cmd_prefix + " -e class com.android.dumprendertree.LayoutTestsAutoTest#resumeLayoutTests" + run_layout_test_cmd_postfix + + adb_output = subprocess.Popen(run_layout_test_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] + + if adb_output.find('INSTRUMENTATION_FAILED') != -1: + logging.error("Error happened : " + adb_output) + sys.exit(1) + + logging.debug(adb_output); + logging.info("Done\n"); + + # Pull results from /sdcard + results_dir = options.results_directory + if not os.path.exists(results_dir): + os.makedirs(results_dir) + if not os.path.isdir(results_dir): + logging.error("Cannot create results dir: " + results_dir); + sys.exit(1); + + result_files = ["/sdcard/layout_tests_passed.txt", + "/sdcard/layout_tests_failed.txt", + "/sdcard/layout_tests_nontext.txt"] + for file in result_files: + shell_cmd_str = adb_cmd + " pull " + file + " " + results_dir + adb_output = subprocess.Popen(shell_cmd_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] + logging.debug(adb_output) + + # Create the crash list. + fp = open(results_dir + "/layout_tests_crashed.txt", "w"); + fp.writelines('\n'.join(crashed_tests)) + fp.close() + + # Count the number of tests in each category. + passed_tests = CountLineNumber(results_dir + "/layout_tests_passed.txt") + logging.info(str(passed_tests) + " passed") + failed_tests = CountLineNumber(results_dir + "/layout_tests_failed.txt") + logging.info(str(failed_tests) + " failed") + crashed_tests = CountLineNumber(results_dir + "/layout_tests_crashed.txt") + logging.info(str(crashed_tests) + " crashed") + nontext_tests = CountLineNumber(results_dir + "/layout_tests_nontext.txt") + logging.info(str(nontext_tests) + " no dumpAsText") + + logging.info("Results are stored under: " + results_dir + "\n") + + # Comparing results to references to find new fixes and regressions. + results_dir = os.path.abspath(options.results_directory) + ref_dir = options.ref_directory + + # if ref_dir is null, cannonify ref_dir to the script dir. + if not ref_dir: + script_self = sys.argv[0] + script_dir = os.path.dirname(script_self) + ref_dir = os.path.join(script_dir, "results") + + ref_dir = os.path.abspath(ref_dir) + + CompareResults(ref_dir, results_dir) + +if '__main__' == __name__: + option_parser = optparse.OptionParser() + option_parser.add_option("", "--rebaseline", action="store_true", + default=False, + help="generate expected results for those tests not having one") + option_parser.add_option("", "--time-out-ms", + default=None, + help="set the timeout for each test") + option_parser.add_option("", "--verbose", action="store_true", + default=False, + help="include debug-level logging") + option_parser.add_option("", "--refresh-test-list", action="store_true", + default=False, + help="re-generate test list, it may take some time.") + option_parser.add_option("", "--adb-options", + default=None, + help="pass options to adb, such as -d -e, etc"); + option_parser.add_option("", "--results-directory", + default="layout-test-results", + help="directory which results are stored.") + option_parser.add_option("", "--ref-directory", + default=None, + dest="ref_directory", + help="directory where reference results are stored.") + + options, args = option_parser.parse_args(); + main(options, args) diff --git a/tests/DumpRenderTree/run_page_cycler.py b/tests/DumpRenderTree/run_page_cycler.py new file mode 100755 index 0000000000000000000000000000000000000000..9a099b52694b4a2f640b8c39cb6211511992bc83 --- /dev/null +++ b/tests/DumpRenderTree/run_page_cycler.py @@ -0,0 +1,101 @@ +#!/usr/bin/python + +"""Run page cycler tests using Android instrumentation. + + First, you need to get an SD card or sdcard image that has page cycler tests. + + Usage: + Run a single page cycler test: + run_page_cycler.py "file:///sdcard/android/page_cycler/moz/start.html?auto=1\&iterations=10" +""" + +import logging +import optparse +import os +import subprocess +import sys +import time + + + +def main(options, args): + """Run the tests. Will call sys.exit when complete. + + """ + + # Set up logging format. + log_level = logging.INFO + if options.verbose: + log_level = logging.DEBUG + logging.basicConfig(level=log_level, + format='%(message)s') + + # Include all tests if none are specified. + if not args: + print "need a URL, e.g. file:///sdcard/android/page_cycler/moz/start.html" + sys.exit(1) + else: + path = ' '.join(args); + + adb_cmd = "adb "; + if options.adb_options: + adb_cmd += options.adb_options + + logging.info("Running the test ...") + + # Count crashed tests. + crashed_tests = [] + + timeout_ms = '0' + if options.time_out_ms: + timeout_ms = options.time_out_ms + + # Run test until it's done + + run_load_test_cmd_prefix = adb_cmd + " shell am instrument" + run_load_test_cmd_postfix = " -w com.android.dumprendertree/.LayoutTestsAutoRunner" + + # Call LoadTestsAutoTest::runTest. + run_load_test_cmd = run_load_test_cmd_prefix + " -e class com.android.dumprendertree.LoadTestsAutoTest#runTest -e path \"" + path + "\" -e timeout " + timeout_ms + run_load_test_cmd_postfix + + (adb_output, adb_error) = subprocess.Popen(run_load_test_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() + if adb_output.find('INSTRUMENTATION_FAILED') != -1: + logging.error("Error happened : " + adb_output) + sys.exit(1) + + logging.info(adb_output); + logging.info(adb_error); + logging.info("Done\n"); + + # Pull results from /sdcard/load_test_result.txt + results_dir = options.results_directory + if not os.path.exists(results_dir): + os.makedirs(results_dir) + if not os.path.isdir(results_dir): + logging.error("Cannot create results dir: " + results_dir) + sys.exit(1) + + result_file = "/sdcard/load_test_result.txt" + shell_cmd_str = adb_cmd + " pull " + result_file + " " + results_dir + adb_output = subprocess.Popen(shell_cmd_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] + logging.info(adb_output) + + logging.info("Results are stored under: " + results_dir + "/load_test_result.txt\n") + +if '__main__' == __name__: + option_parser = optparse.OptionParser() + option_parser.add_option("", "--time-out-ms", + default=None, + help="set the timeout for each test") + option_parser.add_option("", "--verbose", action="store_true", + default=False, + help="include debug-level logging") + option_parser.add_option("", "--adb-options", + default=None, + help="pass options to adb, such as -d -e, etc"); + option_parser.add_option("", "--results-directory", + default="layout-test-results", + help="directory which results are stored.") + + options, args = option_parser.parse_args(); + main(options, args) diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java index 91597d5227896592298cfc928b4cd5c36896cbc2..4f162b3a1660f259e9e4c54dec45c93329cf8a77 100644 --- a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java +++ b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java @@ -24,13 +24,19 @@ public class FileFilter { public static boolean ignoreTest(String file) { // treat files like directories for the time being. - int size = ignoreTestList.length; - for (int i = 0; i < size; i ++) { - if (file.startsWith(ignoreTestList[i])) { + for (int i = 0; i < ignoreTestList.length; i ++) { + if (file.endsWith(ignoreTestList[i])) { Log.e("FileFilter", "File path in IgnoreTest: " + file); return true; } } + for (int i = 0; i < ignoreTestDirs.length; i++) { + if (file.endsWith(ignoreTestDirs[i])) { + Log.e("FileFilter", "File path in ignore list: " + file); + return true; + } + } + return false; } @@ -64,33 +70,19 @@ public class FileFilter { fillIgnoreResultSet(); fillBugTable(); } - - static final String [] ignoreTestList = { + + static final String[] ignoreTestDirs = { ".", // ignore hidden directories and files "resources", // ignore resource directories "AppleScript", // AppleScript not supported - "xpath", // xpath requires libxml2, not supported - "xsl", //xsl requires libxml2 & libxslt, not sup. - "kde", // don't run kde tests. ".svn", // don't run anything under .svn folder - "gradients", //known crash - "toString-stack-overflow.html", // Crashes #606688 - "frame-limit.html", // generates too many GREFs - "css-insert-import-rule.html", // Crashes, #717414 - "input-text-enter.html", // Crashes. #735088 - "text-shadow-extreme-value.html", // Crashes #571671 - "001.html", - "reflection-masks.html", - "frame-creation-removal.html", - "large-expressions.html", - "null-page-show-modal-dialog-crash.html", - "font-face-implicit-local-font.html", - "font-face-locally-installed.html", - "beforeSelectorOnCodeElement.html", - "cssTarget-crash.html", - "searchfield-heights.html", // Bug 1570692 - "tabindex-focus-blur-all.html", - "search-rtl.html" // fast/forms/search-rtl.html + "profiler", // profiler is not supported + "svg", // svg is not supported + "platform", // platform specific + "http" // requires local http(s) server + }; + + static final String [] ignoreTestList = { }; static void fillIgnoreResultSet() { @@ -203,6 +195,8 @@ public class FileFilter { ignoreResultList.add("fast/loader/local-iFrame-source-from-local.html"); // extra spacing because iFrames rendered next to each other on Apple ignoreResultList.add("fast/loader/opaque-base-url.html"); + // RegExp is too large, causing OOM + ignoreResultList.add("fast/js/regexp-charclass-crash.html"); ignoreResultList.add("fast/text/plain-text-line-breaks.html"); diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/FileList.java b/tests/DumpRenderTree/src/com/android/dumprendertree/FileList.java index 8b33d16a7806bd3823b626feafa62b92d442a028..0218317dbcc6a44091cf65341b9704b612f84ad8 100644 --- a/tests/DumpRenderTree/src/com/android/dumprendertree/FileList.java +++ b/tests/DumpRenderTree/src/com/android/dumprendertree/FileList.java @@ -17,6 +17,7 @@ package com.android.dumprendertree; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -84,7 +85,8 @@ public abstract class FileList extends ListActivity return myData; } String[] files = f.list(); - + Arrays.sort(files); + for (int i = 0; i < files.length; i++) { StringBuilder sb = new StringBuilder(mPath); sb.append(File.separatorChar); @@ -117,9 +119,14 @@ public abstract class FileList extends ListActivity { Map map = (Map) l.getItemAtPosition(position); String path = (String)map.get("path"); - if (path.length() > 0) - processFile(path, true); + if ((new File(path)).isDirectory()) { + mPath = path; + mFocusFile = null; + updateList(); + } else { + processFile(path, false); + } } /* @@ -148,7 +155,7 @@ public abstract class FileList extends ListActivity protected void setupPath() { - mPath = "/sdcard"; + mPath = "/sdcard/android/layout_tests"; mBaseLength = mPath.length(); } diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/HTMLHostActivity.java b/tests/DumpRenderTree/src/com/android/dumprendertree/HTMLHostActivity.java deleted file mode 100644 index 9521f8038656ff58fa4976408d39a74ef079f5ec..0000000000000000000000000000000000000000 --- a/tests/DumpRenderTree/src/com/android/dumprendertree/HTMLHostActivity.java +++ /dev/null @@ -1,607 +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. - */ - -package com.android.dumprendertree; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.BufferedOutputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Vector; -import java.util.Stack; - -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; -import android.util.Log; -import android.view.KeyEvent; -import android.view.ViewGroup; -import android.webkit.JsPromptResult; -import android.webkit.JsResult; -import android.webkit.WebChromeClient; -import android.webkit.WebSettings; -import android.webkit.WebView; -import android.widget.LinearLayout; -import android.os.*; -import android.test.TestRecorder; - -// SQLite3 in android has a bunch of bugs which -// is causing TestRecorder to not record the results -// properly. This class is a wrapper around it and records -// results in a file as well. -class TestRecorderV2 extends TestRecorder { - @Override - public void passed(String layout_file) { - try { - mBufferedOutputPassedStream.write(layout_file.getBytes()); - mBufferedOutputPassedStream.write('\n'); - mBufferedOutputPassedStream.flush(); - } catch(Exception e) { - e.printStackTrace(); - } - super.passed(layout_file); - } - - @Override - public void failed(String layout_file, String reason) { - try { - mBufferedOutputFailedStream.write(layout_file.getBytes()); - mBufferedOutputFailedStream.write('\n'); - mBufferedOutputFailedStream.flush(); - } catch(Exception e) { - e.printStackTrace(); - } - super.failed(layout_file, reason); - } - - public TestRecorderV2() { - super(); - try { - File resultsPassedFile = new File("/sdcard/layout_test_presults.txt"); - File resultsFailedFile = new File("/sdcard/layout_test_fresults.txt"); - - mBufferedOutputPassedStream = - new BufferedOutputStream(new FileOutputStream(resultsPassedFile, true)); - mBufferedOutputFailedStream = - new BufferedOutputStream(new FileOutputStream(resultsFailedFile, true)); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - protected void finalize() throws Throwable { - mBufferedOutputPassedStream.flush(); - mBufferedOutputFailedStream.flush(); - mBufferedOutputPassedStream.close(); - mBufferedOutputFailedStream.close(); - } - - private static BufferedOutputStream mBufferedOutputPassedStream; - private static BufferedOutputStream mBufferedOutputFailedStream; -} - -public class HTMLHostActivity extends Activity - implements LayoutTestController { - - private TestRecorderV2 mResultRecorder = new TestRecorderV2(); - private HTMLHostCallbackInterface mCallback = null; - private CallbackProxy mCallbackProxy; - - public class FileEntry { - public FileEntry(String path, int index) { - mPath = path; mIndex=index; - } - String mPath; - int mIndex; - } - - public class AsyncHandler extends Handler { - @Override - public void handleMessage(Message msg) { - if (msg.what == MSG_DUMP) { - this.removeMessages(MSG_TIMEOUT); - mTimedOut = false; - requestWebKitData(); - return; - } else if (msg.what == MSG_TIMEOUT) { - mTimedOut = true; - requestWebKitData(); - return; - } else if (msg.what == MSG_WEBKIT_DATA) { - HTMLHostActivity.this.dump(mTimedOut, (String)msg.obj); - return; - } - - super.handleMessage(msg); - } - - void requestWebKitData() { - Message callback = obtainMessage(MSG_WEBKIT_DATA); - if (dumpAsText) { - mWebView.documentAsText(callback); - } else { - mWebView.externalRepresentation(callback); - } - } - - } - - // Activity methods - public void onCreate(Bundle icicle) { - super.onCreate(icicle); - - LinearLayout contentView = new LinearLayout(this); - contentView.setOrientation(LinearLayout.VERTICAL); - setContentView(contentView); - - mWebView = new WebView(this); - mWebView.getSettings().setJavaScriptEnabled(true); - mWebView.setWebChromeClient(mChromeClient); - eventSender = new WebViewEventSender(mWebView); - mCallbackProxy = new CallbackProxy(eventSender, this); - - mWebView.addJavascriptInterface(mCallbackProxy, "layoutTestController"); - mWebView.addJavascriptInterface(mCallbackProxy, "eventSender"); - contentView.addView(mWebView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0f)); - - mHandler = new AsyncHandler(); - } - - @Override - protected void onRestoreInstanceState(Bundle savedInstanceState) { - super.onRestoreInstanceState(savedInstanceState); - } - - protected void onResume() { - super.onResume(); - if (mProcessStack == null || mProcessStack.isEmpty() ) { - mOutstandingLoads = 0; - dumpAsText = false; - pageComplete = false; - - mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); - - mFinishedStack = new Stack(); - - Intent intent = getIntent(); - if (intent.getData() != null) { - File f = new File(intent.getData().toString()); - - if (f.isDirectory()) { - mProcessStack = new Vector(); - mProcessStack.add(new FileEntry(intent.getData().toString(), 0)); - Log.v(LOGTAG, "Initial dir: "+intent.getData().toString()); - loadNextPage(); - } else { - mCurrentFile = intent.getData().toString(); - mWebView.loadUrl("file://"+intent.getData().toString()); - } - - } - else - mWebView.loadUrl("about:"); - } - } - - protected void onStop() { - super.onStop(); - mWebView.stopLoading(); - } - - protected void onDestroy() { - super.onDestroy(); - mWebView.destroy(); - mWebView = null; - } - - public boolean dispatchKeyEvent(KeyEvent event) { - // Log key strokes as they don't seem to be matched - //Log.e(LOGTAG, "Event: "+event); - return super.dispatchKeyEvent(event); - } - - // Functions - - protected void loadNextPage() { - dumpAsText = false; - pageComplete = false; - dumpTitleChanges = false; - eventSender.resetMouse(); - while (!mProcessStack.isEmpty()) { - FileEntry fe = (FileEntry)mProcessStack.remove(0); - if (fe.mIndex == 0) { - System.out.println(); - System.out.print(fe.mPath); - } - Log.v(LOGTAG, "Processing dir: "+fe.mPath+" size: "+mProcessStack.size()); - File f = new File(fe.mPath); - String [] files = f.list(); - for (int i = fe.mIndex; i < files.length; i++) { - if (FileFilter.ignoreTest(files[i])) { - continue; - } - File c = new File(f.getPath(), files[i]); - if (c.isDirectory()) { - Log.v(LOGTAG, "Adding dir: "+fe.mPath+"/"+files[i]); - mProcessStack.add(new FileEntry(fe.mPath+"/"+files[i], 0)); - } else if (files[i].toLowerCase().endsWith("ml")) { - mProcessStack.add(0, new FileEntry(fe.mPath, i+1)); - mCurrentFile = fe.mPath+"/"+files[i]; - Log.e(LOGTAG, "Processing: "+mCurrentFile); - mWebView.loadUrl("file://"+mCurrentFile); - - // Create a timeout timer - Message m = mHandler.obtainMessage(MSG_TIMEOUT); - // Some tests can take up to 5secs to run. - mHandler.sendMessageDelayed(m, 6000); - return; - } - } - Log.v(LOGTAG, "Finished dir: "+fe.mPath+" size: "+mProcessStack.size()); - } - // If we got to here, then we must have finished completely - finished(); - } - - public void scheduleDump() { - // Only schedule if we really are ready - if (waitToDump || mOutstandingLoads > 0 || mDumpRequested) { - return; - } - mDumpRequested = true; - mHandler.obtainMessage(MSG_DUMP).sendToTarget(); - } - - // Dump the page - public void dump(boolean timeout, String webkitData) { - mDumpRequested = false; - System.out.print('.'); - - // remove the extension - String resultFile = mCurrentFile.substring(0, mCurrentFile.lastIndexOf('.')); - - // store the finished file on the stack so that we can do a diff at the end. - mFinishedStack.push(resultFile); - - // dumpAsText version can be directly compared to expected results - if (dumpAsText) { - resultFile += "-results.txt"; - } else { - resultFile += "-android-results.txt"; - } - try { - FileOutputStream os = new FileOutputStream(resultFile); - if (timeout) { - Log.i("Layout test: Timeout", resultFile); - os.write("**Test timeout\n".getBytes()); - } - if (dumpTitleChanges) - os.write(mTitleChanges.toString().getBytes()); - if (mDialogStrings != null) - os.write(mDialogStrings.toString().getBytes()); - mDialogStrings = null; - os.write(webkitData.getBytes()); - os.flush(); - os.close(); - } catch (FileNotFoundException ex) { - ex.printStackTrace(); - } catch (IOException ex) { - ex.printStackTrace(); - } - - if (mProcessStack != null) - loadNextPage(); - else - finished(); - } - - // Wrap up - public void failedCase(String file, String reason) { - Log.i("Layout test:", file + " failed" + reason); - mResultRecorder.failed(file, reason); - - file = file + ".html"; - String bugNumber = FileFilter.isKnownBug(file); - if (bugNumber != null) { - System.out.println("FAIL known:"+bugNumber+ " "+file+reason); - return; - } - if (FileFilter.ignoreResults(file)) { - return; - } - System.out.println("FAIL: "+file+reason); - } - - public void passedCase(String file) { - // Add the result to the sqlite database - Log.i("Layout test:", file + " passed"); - mResultRecorder.passed(file); - - file = file + ".html"; - String bugNumber = FileFilter.isKnownBug(file); - if (bugNumber != null) { - System.out.println("Bug Fixed: "+bugNumber+ " "+file); - return; - } - - if (FileFilter.ignoreResults(file)) { - System.out.println("Ignored test passed: "+file); - return; - } - } - - public void setCallback(HTMLHostCallbackInterface callback) { - mCallback = callback; - } - - public void finished() { - int passed = 0; - while (!mFinishedStack.empty()) { - Log.v(LOGTAG, "Comparing dump and reference"); - String file = (String)mFinishedStack.pop(); - - // Only check results that we can check, ie dumpAsText results - String dumpFile = file + "-results.txt"; - File f = new File(dumpFile); - if (f.exists()) { - try { - FileInputStream fr = new FileInputStream(file+"-results.txt"); - FileInputStream fe = new FileInputStream(file+"-expected.txt"); - - mResultRecorder.started(file); - - // If the length is different then they are different - int diff = fe.available() - fr.available(); - if (diff > 1 || diff < 0) { - failedCase(file, " different length"); - fr.close(); - fe.close(); - - mResultRecorder.finished(file); - continue; - } - byte[] br = new byte[fr.available()]; - byte[] be = new byte[fe.available()]; - fr.read(br); - fe.read(be); - boolean fail = false; - for (int i = 0; i < br.length; i++) { - if (br[i] != be[i]) { - failedCase(file, " @offset: "+i); - fail = true; - break; - } - } - if (br.length != be.length && be[be.length-1] == '\n') { - Log.d(LOGTAG, "Extra new line being ignore:" + file); - } - fr.close(); - fe.close(); - if (!fail) { - passed++; - passedCase(file); - } - } catch (FileNotFoundException ex) { - // TODO do something here - } catch (IOException ex) { - // Failed on available() or read() - } - mResultRecorder.finished(file); - } - } - - if (mCallback != null) { - mCallback.waitForFinish(); - } - - finish(); - } - - // LayoutTestController Functions - public void dumpAsText() { - dumpAsText = true; - String url = mWebView.getUrl(); - Log.v(LOGTAG, "dumpAsText called:"+url); - if (url.length() > 60) - url = url.substring(60); - } - - public void waitUntilDone() { - waitToDump = true; - } - public void notifyDone() { - waitToDump = false; - mChromeClient.onProgressChanged(mWebView, 100); - } - public void display() { - mWebView.invalidate(); - } - - public void clearBackForwardList() { - mWebView.clearHistory(); - - } - - public void dumpBackForwardList() { - //printf("\n============== Back Forward List ==============\n"); - // mWebHistory - //printf("===============================================\n"); - - } - - public void dumpChildFrameScrollPositions() { - // TODO Auto-generated method stub - - } - - public void dumpEditingCallbacks() { - // TODO Auto-generated method stub - - } - - public void dumpSelectionRect() { - // TODO Auto-generated method stub - - } - - public void dumpTitleChanges() { - if (!dumpTitleChanges) { - mTitleChanges = new StringBuffer(); - } - dumpTitleChanges = true; - } - - public void keepWebHistory() { - if (!keepWebHistory) { - mWebHistory = new Vector(); - } - keepWebHistory = true; - - } - - public void queueBackNavigation(int howfar) { - // TODO Auto-generated method stub - - } - - public void queueForwardNavigation(int howfar) { - // TODO Auto-generated method stub - - } - - public void queueLoad(String Url, String frameTarget) { - // TODO Auto-generated method stub - - } - - public void queueReload() { - mWebView.reload(); - } - - public void queueScript(String scriptToRunInCurrentContext) { - mWebView.loadUrl("javascript:"+scriptToRunInCurrentContext); - } - - public void repaintSweepHorizontally() { - // TODO Auto-generated method stub - - } - - public void setAcceptsEditing(boolean b) { - // TODO Auto-generated method stub - - } - - public void setMainFrameIsFirstResponder(boolean b) { - // TODO Auto-generated method stub - - } - - public void setWindowIsKey(boolean b) { - // This is meant to show/hide the window. The best I can find - // is setEnabled() - mWebView.setEnabled(b); - } - - public void testRepaint() { - mWebView.invalidate(); - } - - // Instrumentation calls this to find - // if the activity has finished running the layout tests - public boolean hasFinishedRunning() { - if( mProcessStack == null || mFinishedStack == null) - return false; - - if (mProcessStack.isEmpty() && mFinishedStack.empty()) { - return true; - } - - return false; - } - - private final WebChromeClient mChromeClient = new WebChromeClient() { - @Override - public void onProgressChanged(WebView view, int newProgress) { - if (newProgress == 100) { - pageComplete = true; - String url = mWebView.getUrl(); - if (url != null) { - Log.v(LOGTAG, "Finished: "+ url); - if (url.length() > 60) - url = url.substring(60); - scheduleDump(); - } - } - } - - @Override - public void onReceivedTitle(WebView view, String title) { - if (title.length() > 30) - title = "..."+title.substring(title.length()-30); - setTitle(title); - if (dumpTitleChanges) { - mTitleChanges.append("TITLE CHANGED: "); - mTitleChanges.append(title); - mTitleChanges.append("\n"); - } - } - - @Override - public boolean onJsAlert(WebView view, String url, String message, - JsResult result) { - if (mDialogStrings == null) { - mDialogStrings = new StringBuffer(); - } - mDialogStrings.append("ALERT: "); - mDialogStrings.append(message); - mDialogStrings.append('\n'); - return false; - } - }; - - private WebView mWebView; - private WebViewEventSender eventSender; - private Vector mProcessStack; - private Stack mFinishedStack; - static final String LOGTAG="DumpRenderTree"; - private String mCurrentFile; - private int mOutstandingLoads; - private AsyncHandler mHandler; - private boolean mDumpRequested; - - private boolean dumpAsText; - private boolean waitToDump; - private boolean pageComplete; - - private boolean dumpTitleChanges; - private StringBuffer mTitleChanges; - - private StringBuffer mDialogStrings; - - private boolean keepWebHistory; - private Vector mWebHistory; - - private boolean mTimedOut; - - static final int MSG_DUMP = 0; - static final int MSG_TIMEOUT = 1; - static final int MSG_WEBKIT_DATA = 2; - -} diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoRunner.java b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoRunner.java index e0e535e356b1d29477ab829f0e20ea6a90c2e9e5..8f968b43972a04ae25b1349f1906dc2a95f61a18 100755 --- a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoRunner.java +++ b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoRunner.java @@ -21,10 +21,13 @@ import com.android.dumprendertree.LayoutTestsAutoTest; import android.test.InstrumentationTestRunner; import android.test.InstrumentationTestSuite; +import android.util.Log; +import android.content.Intent; +import android.os.Bundle; /** - * Instrumentation Test Runner for all MediaPlayer tests. + * Instrumentation Test Runner for all DumpRenderTree tests. * * Running all tests: * @@ -37,6 +40,7 @@ public class LayoutTestsAutoRunner extends InstrumentationTestRunner { public TestSuite getAllTests() { TestSuite suite = new InstrumentationTestSuite(this); suite.addTestSuite(LayoutTestsAutoTest.class); + suite.addTestSuite(LoadTestsAutoTest.class); return suite; } @@ -44,5 +48,26 @@ public class LayoutTestsAutoRunner extends InstrumentationTestRunner { public ClassLoader getLoader() { return LayoutTestsAutoRunner.class.getClassLoader(); } + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + this.mTestPath = (String) icicle.get("path"); + String timeout_str = (String) icicle.get("timeout"); + if (timeout_str != null) { + try { + this.mTimeoutInMillis = Integer.parseInt(timeout_str); + } catch (Exception e) { + e.printStackTrace(); + } + } + + String r = (String)icicle.get("rebaseline"); + this.mRebaseline = (r != null && r.toLowerCase().equals("true")); + } + + public String mTestPath = null; + public int mTimeoutInMillis = 0; + public boolean mRebaseline = false; } diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java index f46b263bfc7ce92318652b20060ea606c21b45e6..a857e681aa5c280ffbc6a2cf20dd89c4791e1847 100644 --- a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java +++ b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java @@ -16,142 +16,440 @@ package com.android.dumprendertree; +import android.app.Activity; import android.app.Instrumentation; import android.app.Instrumentation.ActivityMonitor; import android.content.ContentResolver; import android.content.ContentValues; +import android.content.Intent; + import android.util.Log; import android.view.KeyEvent; +import android.webkit.WebSettings; -import android.test.ActivityInstrumentationTestCase; +import android.os.Bundle; +import android.os.Message; +import android.test.ActivityInstrumentationTestCase2; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.LargeTest; -import com.android.dumprendertree.HTMLHostActivity; +import com.android.dumprendertree.TestShellActivity; + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.Vector; + +//TestRecorder creates two files, one for passing tests +//and another for failing tests and writes the paths to +//layout tests one line at a time. TestRecorder does not +//have ability to clear the results. +class MyTestRecorder { + private BufferedOutputStream mBufferedOutputPassedStream; + private BufferedOutputStream mBufferedOutputFailedStream; + private BufferedOutputStream mBufferedOutputNoresultStream; + + public void passed(String layout_file) { + try { + mBufferedOutputPassedStream.write(layout_file.getBytes()); + mBufferedOutputPassedStream.write('\n'); + mBufferedOutputPassedStream.flush(); + } catch(Exception e) { + e.printStackTrace(); + } + } + + public void failed(String layout_file) { + try { + mBufferedOutputFailedStream.write(layout_file.getBytes()); + mBufferedOutputFailedStream.write('\n'); + mBufferedOutputFailedStream.flush(); + } catch(Exception e) { + e.printStackTrace(); + } + } + + public void noresult(String layout_file) { + try { + mBufferedOutputNoresultStream.write(layout_file.getBytes()); + mBufferedOutputNoresultStream.write('\n'); + mBufferedOutputNoresultStream.flush(); + } catch(Exception e) { + e.printStackTrace(); + } + } + + public MyTestRecorder(boolean resume) { + try { + File resultsPassedFile = new File("/sdcard/layout_tests_passed.txt"); + File resultsFailedFile = new File("/sdcard/layout_tests_failed.txt"); + File noExpectedResultFile = new File("/sdcard/layout_tests_nontext.txt"); + + mBufferedOutputPassedStream = + new BufferedOutputStream(new FileOutputStream(resultsPassedFile, resume)); + mBufferedOutputFailedStream = + new BufferedOutputStream(new FileOutputStream(resultsFailedFile, resume)); + mBufferedOutputNoresultStream = + new BufferedOutputStream(new FileOutputStream(noExpectedResultFile, resume)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void close() { + try { + mBufferedOutputPassedStream.close(); + mBufferedOutputFailedStream.close(); + mBufferedOutputNoresultStream.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} + -public class LayoutTestsAutoTest extends ActivityInstrumentationTestCase

            { +public class LayoutTestsAutoTest extends ActivityInstrumentationTestCase2 { - private final static String LOGTAG = "LayoutTests"; - private final static String LAYOUT_TESTS_ROOT = "/sdcard/android/layout_tests/"; + private static final String LOGTAG = "LayoutTests"; + static final int DEFAULT_TIMEOUT_IN_MILLIS = 5000; + + static final String LAYOUT_TESTS_ROOT = "/sdcard/android/layout_tests/"; + static final String LAYOUT_TESTS_RESULT_DIR = "/sdcard/android/layout_tests_results/"; + static final String ANDROID_EXPECTED_RESULT_DIR = "/sdcard/android/expected_results/"; + static final String LAYOUT_TESTS_LIST_FILE = "/sdcard/android/layout_tests_list.txt"; + static final String TEST_STATUS_FILE = "/sdcard/android/running_test.txt"; + private MyTestRecorder mResultRecorder; + private Vector mTestList; + private boolean mRebaselineResults; + private String mTestPathPrefix; + public LayoutTestsAutoTest() { - super("com.android.dumprendertree", Menu.class); + super("com.android.dumprendertree", TestShellActivity.class); } - // Invokes running of layout tests - // and waits till it has finished running. - public void executeLayoutTests(String folder) { + // This function writes the result of the layout test to + // Am status so that it can be picked up from a script. + private void passOrFailCallback(String file, boolean result) { Instrumentation inst = getInstrumentation(); - getActivity().processFile(folder, true); + Bundle bundle = new Bundle(); + bundle.putBoolean(file, result); + inst.sendStatus(0, bundle); + } + + private void getTestList() { + // Read test list. + try { + BufferedReader inReader = new BufferedReader(new FileReader(LAYOUT_TESTS_LIST_FILE)); + String line = inReader.readLine(); + while (line != null) { + if (line.startsWith(mTestPathPrefix)) + mTestList.add(line); + line = inReader.readLine(); + } + inReader.close(); + Log.v(LOGTAG, "Test list has " + mTestList.size() + " test(s)."); + } catch (Exception e) { + Log.e(LOGTAG, "Error while reading test list : " + e.getMessage()); + } + } + + private void resumeTestList() { + // read out the test name it stoped last time. + try { + BufferedReader inReader = new BufferedReader(new FileReader(TEST_STATUS_FILE)); + String line = inReader.readLine(); + for (int i = 0; i < mTestList.size(); i++) { + if (mTestList.elementAt(i).equals(line)) { + mTestList = new Vector(mTestList.subList(i+1, mTestList.size())); + break; + } + } + inReader.close(); + } catch (Exception e) { + Log.e(LOGTAG, "Error reading " + TEST_STATUS_FILE); + } + } + + private void clearTestStatus() { + // Delete TEST_STATUS_FILE + try { + File f = new File(TEST_STATUS_FILE); + if (f.delete()) + Log.v(LOGTAG, "Deleted " + TEST_STATUS_FILE); + else + Log.e(LOGTAG, "Fail to delete " + TEST_STATUS_FILE); + } catch (Exception e) { + Log.e(LOGTAG, "Fail to delete " + TEST_STATUS_FILE + " : " + e.getMessage()); + } + } + + private void updateTestStatus(String s) { + // Write TEST_STATUS_FILE + try { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(TEST_STATUS_FILE)); + bos.write(s.getBytes()); + bos.close(); + } catch (Exception e) { + Log.e(LOGTAG, "Cannot update file " + TEST_STATUS_FILE); + } + } + + private String getResultFile(String test) { + String shortName = test.substring(0, test.lastIndexOf('.')); + // Write actual results to result directory. + return shortName.replaceFirst(LAYOUT_TESTS_ROOT, LAYOUT_TESTS_RESULT_DIR) + "-result.txt"; + } + + private String getExpectedResultFile(String test) { + String shortName = test.substring(0, test.lastIndexOf('.')); + return shortName + "-expected.txt"; + } - ActivityMonitor htmlHostActivityMonitor = - inst.addMonitor("com.android.dumprendertree.HTMLHostActivity", null, false); - HTMLHostActivity activity = - (HTMLHostActivity) htmlHostActivityMonitor.waitForActivityWithTimeout(6000); + private String getAndroidExpectedResultFile(String expectedResultFile) { + return expectedResultFile.replaceFirst(LAYOUT_TESTS_ROOT, ANDROID_EXPECTED_RESULT_DIR); + } + + // Wrap up + private void failedCase(String file) { + Log.w("Layout test: ", file + " failed"); + mResultRecorder.failed(file); + } + + private void passedCase(String file) { + Log.v("Layout test:", file + " passed"); + mResultRecorder.passed(file); + } + + private void noresultCase(String file) { + Log.v("Layout test:", file + " no expected result"); + mResultRecorder.noresult(file); + } + + private void processResult(String testFile, String actualResultFile, String expectedResultFile) { + Log.v(LOGTAG, " Processing result: " + testFile); + + File actual = new File(actualResultFile); + File expected = new File(expectedResultFile); + if (actual.exists() && expected.exists()) { + try { + boolean passing = true; + BufferedReader fr = new BufferedReader(new FileReader(actual)); + BufferedReader fe = new BufferedReader(new FileReader(expected)); + while (true) { + String s1 = fr.readLine(); + String s2 = fe.readLine(); + if (s1 == null && s2 == null) + break; // both files are the same + if (s1 == null || s2 == null || !s1.equals(s2)) { + passing = false; + break; + } + } + + if (passing) { + passedCase(testFile); + } else { + failedCase(testFile); + } + + fe.close(); + fr.close(); + } catch (FileNotFoundException ex) { + Log.e(LOGTAG, "File not found : " + ex.getMessage()); + } catch (IOException ex) { + Log.e(LOGTAG, "IO Error : " + ex.getMessage()); + } + return; + } + + if (!expected.exists()) { + noresultCase(testFile); + } + } + + private void runTestAndWaitUntilDone(TestShellActivity activity, String test, int timeout) { + activity.setCallback(new TestShellCallback() { + public void finished() { + synchronized (LayoutTestsAutoTest.this) { + LayoutTestsAutoTest.this.notifyAll(); + } + } + }); + + String resultFile = getResultFile(test); + if (mRebaselineResults) { + String expectedResultFile = getExpectedResultFile(test); + File f = new File(expectedResultFile); + if (f.exists()) { + return; // don't run test and don't overwrite default tests. + } + + resultFile = getAndroidExpectedResultFile(expectedResultFile); + } + + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setClass(activity, TestShellActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + intent.putExtra(TestShellActivity.TEST_URL, "file://" + test); + intent.putExtra(TestShellActivity.RESULT_FILE, resultFile); + intent.putExtra(TestShellActivity.TIMEOUT_IN_MILLIS, timeout); + activity.startActivity(intent); - while (!activity.hasFinishedRunning()) { - // Poll every 5 seconds to determine if the layout - // tests have finished running - try {Thread.sleep(5000); } catch(Exception e){} - } + // Wait until done. + synchronized (this) { + try { + this.wait(); + } catch (InterruptedException e) { } + } + + if (!mRebaselineResults) { + String expectedResultFile = getExpectedResultFile(test); + File f = new File(expectedResultFile); + if (!f.exists()) { + expectedResultFile = getAndroidExpectedResultFile(expectedResultFile); + } + + processResult(test, resultFile, expectedResultFile); + } + } + + // Invokes running of layout tests + // and waits till it has finished running. + public void executeLayoutTests(boolean resume) { + LayoutTestsAutoRunner runner = (LayoutTestsAutoRunner) getInstrumentation(); + // A convenient method to be called by another activity. + + if (runner.mTestPath == null) { + Log.e(LOGTAG, "No test specified"); + return; + } + + this.mTestList = new Vector(); - // Wait few more seconds so that results are - // flushed to the /sdcard - try {Thread.sleep(5000); } catch(Exception e){} + // Read settings + try { + this.mTestPathPrefix = + (new File(LAYOUT_TESTS_ROOT + runner.mTestPath)).getCanonicalPath(); + } catch (IOException e) { + Log.e(LOGTAG, "Cannot find test path prefix: " + e.getMessage()); + return; + } + + this.mRebaselineResults = runner.mRebaseline; + + int timeout = runner.mTimeoutInMillis; + if (timeout <= 0) { + timeout = DEFAULT_TIMEOUT_IN_MILLIS; + } + + this.mResultRecorder = new MyTestRecorder(resume); + + if (!resume) + clearTestStatus(); + + getTestList(); + if (resume) + resumeTestList(); + + TestShellActivity activity = (TestShellActivity) getActivity(); + + // Run tests. + for (int i = 0; i < mTestList.size(); i++) { + String s = mTestList.elementAt(i); + updateTestStatus(s); + // Run tests + runTestAndWaitUntilDone(activity, s, runner.mTimeoutInMillis); + } + + updateTestStatus("#DONE"); + + activity.finish(); + } + - return ; + private String getTestPath() { + LayoutTestsAutoRunner runner = (LayoutTestsAutoRunner) getInstrumentation(); + + String test_path = LAYOUT_TESTS_ROOT; + if (runner.mTestPath != null) { + test_path += runner.mTestPath; + } + try { + test_path = new File(test_path).getCanonicalPath(); + } catch (IOException e) { + Log.e("LayoutTestsAutoTest", "Cannot get cannonical path " + e.getMessage()); + } + Log.v("LayoutTestsAutoTest", " Test path : " + test_path); + + return test_path; + } + + public void generateTestList() { + try { + File tests_list = new File(LAYOUT_TESTS_LIST_FILE); + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tests_list, false)); + findTestsRecursively(bos, getTestPath()); + bos.flush(); + bos.close(); + } catch (Exception e) { + Log.e(LOGTAG, "Error when creating test list: " + e.getMessage()); + } + } + + private void findTestsRecursively(BufferedOutputStream bos, String dir) throws IOException { + Log.v(LOGTAG, "Searching tests under " + dir); + + File d = new File(dir); + if (!d.isDirectory()) { + throw new AssertionError("A directory expected, but got " + dir); + } + + String[] files = d.list(); + for (int i = 0; i < files.length; i++) { + String s = dir + "/" + files[i]; + if (FileFilter.ignoreTest(s)) { + Log.v(LOGTAG, " Ignoring: " + s); + continue; + } + if (s.toLowerCase().endsWith(".html") + || s.toLowerCase().endsWith(".xml")) { + bos.write(s.getBytes()); + bos.write('\n'); + continue; + } + + File f = new File(s); + if (f.isDirectory()) { + findTestsRecursively(bos, s); + continue; + } + + Log.v(LOGTAG, "Skipping " + s); + } } // Running all the layout tests at once sometimes // causes the dumprendertree to run out of memory. // So, additional tests are added to run the tests // in chunks. - @LargeTest - public void testAllLayoutTests() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast"); - } - - @LargeTest - public void testLayoutSubset1() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/backgrounds"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/borders"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/box-shadow"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/box-sizing"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/canvas"); - } - - @LargeTest - public void testLayoutSubset2() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/clip"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/compact"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/cookies"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/css"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/css-generated-content"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/doctypes"); - } - - @LargeTest - public void testLayoutSubset3() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/dom"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/dynamic"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/encoding"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/events"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/flexbox"); - } - - @LargeTest - public void testLayoutSubset4() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/forms"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/frames"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/gradients"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/history"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/html"); - } - - @LargeTest - public void testLayoutSubset5() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/images"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/inline"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/inline-block"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/innerHTML"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/invalid"); - } - - @LargeTest - public void testLayoutSubset6() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/js"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/layers"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/leaks"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/lists"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/loader"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/media"); - } - - @LargeTest - public void testLayoutSubset7() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/multicol"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/overflow"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/parser"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/profiler"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/reflections"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/regex"); - } - - @LargeTest - public void testLayoutSubset8() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/repaint"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/replaced"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/runin"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/selectors"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/table"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/text"); - } - - @LargeTest - public void testLayoutSubset9() { - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/tokenizer"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/transforms"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/xpath"); - executeLayoutTests(LAYOUT_TESTS_ROOT + "fast/xsl"); + public void startLayoutTests() { + try { + File tests_list = new File(LAYOUT_TESTS_LIST_FILE); + if (!tests_list.exists()) + generateTestList(); + } catch (Exception e) { + e.printStackTrace(); + } + + executeLayoutTests(false); + } + + public void resumeLayoutTests() { + executeLayoutTests(true); } } diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/LoadTestsAutoTest.java b/tests/DumpRenderTree/src/com/android/dumprendertree/LoadTestsAutoTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b064dbb404290bca217ccccb57057dc5feef041f --- /dev/null +++ b/tests/DumpRenderTree/src/com/android/dumprendertree/LoadTestsAutoTest.java @@ -0,0 +1,152 @@ +/* + * 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. + */ + +package com.android.dumprendertree; + +import android.app.Activity; +import android.app.Instrumentation; +import android.app.Instrumentation.ActivityMonitor; +import android.content.Intent; + +import android.util.Log; + +import android.os.Bundle; +import android.test.ActivityInstrumentationTestCase2; + +import com.android.dumprendertree.TestShellActivity; +import com.android.dumprendertree.TestShellCallback; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +class StreamPipe extends Thread { + InputStream in; + OutputStream out; + + StreamPipe(InputStream in, OutputStream out) { + this.in = in; + this.out = out; + } + + public void run() { + try { + byte[] buf = new byte[1024]; + int nofb = this.in.read(buf); + while (nofb != -1) { + this.out.write(buf, 0, nofb); + nofb = this.in.read(buf); + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} + +public class LoadTestsAutoTest extends ActivityInstrumentationTestCase2 { + + private final static String LOGTAG = "LoadTest"; + private final static String LOAD_TEST_RESULT = "/sdcard/load_test_result.txt"; + + public LoadTestsAutoTest() { + super("com.android.dumprendertree", TestShellActivity.class); + } + + // This function writes the result of the layout test to + // Am status so that it can be picked up from a script. + public void passOrFailCallback(String file, boolean result) { + Instrumentation inst = getInstrumentation(); + Bundle bundle = new Bundle(); + bundle.putBoolean(file, result); + inst.sendStatus(0, bundle); + } + + // Invokes running of layout tests + // and waits till it has finished running. + public void runTest() { + LayoutTestsAutoRunner runner = (LayoutTestsAutoRunner) getInstrumentation(); + + if (runner.mTestPath == null) { + Log.e(LOGTAG, "No test specified"); + return; + } + + TestShellActivity activity = (TestShellActivity) getActivity(); + + // Run tests + runTestAndWaitUntilDone(activity, runner.mTestPath, runner.mTimeoutInMillis); + + // TODO(fqian): let am instrumentation pass in the command line, currently + // am instrument does not allow spaces in the command. + runPostShellCommand("/system/bin/dumpsys meminfo"); + + // Kill activity + activity.finish(); + } + + private void runPostShellCommand(String cmd) { + if (cmd == null || cmd.length() == 0) + return; + + try { + // Call dumpsys meminfo + Process proc = Runtime.getRuntime().exec(cmd); + // Append output to LOAD_TEST_RESULT + InputStream input = proc.getInputStream(); + InputStream error = proc.getErrorStream(); + FileOutputStream out = new FileOutputStream(LOAD_TEST_RESULT, true); + + StreamPipe p_in = new StreamPipe(input, out); + StreamPipe p_err = new StreamPipe(error, System.err); + + p_in.start(); + p_err.start(); + + proc.waitFor(); + } catch (IOException e) { + Log.e(LOGTAG, e.getMessage()); + } catch (InterruptedException e) { + Log.e(LOGTAG, e.getMessage()); + } + } + + // A convenient method to be called by another activity. + private void runTestAndWaitUntilDone(TestShellActivity activity, String url, int timeout) { + activity.setCallback(new TestShellCallback() { + public void finished() { + synchronized (LoadTestsAutoTest.this) { + LoadTestsAutoTest.this.notifyAll(); + } + } + }); + + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setClass(activity, TestShellActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + intent.putExtra(TestShellActivity.TEST_URL, url); + intent.putExtra(TestShellActivity.TIMEOUT_IN_MILLIS, timeout); + intent.putExtra(TestShellActivity.RESULT_FILE, LOAD_TEST_RESULT); + activity.startActivity(intent); + + // Wait until done. + synchronized (this) { + try { + this.wait(); + } catch (InterruptedException e) { } + } + } +} diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/Menu.java b/tests/DumpRenderTree/src/com/android/dumprendertree/Menu.java index 2def8f353e3e9454cf5370535f1a7a60feb363ea..00e0f895375794fb94a03d7366b3d8d0faac5335 100644 --- a/tests/DumpRenderTree/src/com/android/dumprendertree/Menu.java +++ b/tests/DumpRenderTree/src/com/android/dumprendertree/Menu.java @@ -19,6 +19,7 @@ package com.android.dumprendertree; import android.content.Intent; import android.net.Uri; import android.os.Bundle; +import android.util.Log; import java.io.File; @@ -42,12 +43,12 @@ public class Menu extends FileList { } void processFile(String filename, boolean selection) - { - Intent result = new Intent(null, Uri.parse(filename)); - result.setClass(this, HTMLHostActivity.class); - result.putExtra("ReturnWhenFinished", selection); - startActivity(result); + { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setClass(this, TestShellActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + intent.putExtra(TestShellActivity.TEST_URL, "file://" + filename); + startActivity(intent); } - } diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java b/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..bf8a3b35a443f3f9f54c3f0d65e28165f87159e4 --- /dev/null +++ b/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java @@ -0,0 +1,426 @@ +/* + * 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. + */ + +package com.android.dumprendertree; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Vector; + +import android.app.Activity; +import android.content.Intent; +import android.util.Log; +import android.webkit.JsPromptResult; +import android.webkit.JsResult; +import android.view.ViewGroup; +import android.webkit.WebChromeClient; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.widget.LinearLayout; +import android.os.*; + +public class TestShellActivity extends Activity implements LayoutTestController { + public class AsyncHandler extends Handler { + @Override + public void handleMessage(Message msg) { + if (msg.what == MSG_TIMEOUT) { + mTimedOut = true; + requestWebKitData(); + return; + } else if (msg.what == MSG_WEBKIT_DATA) { + TestShellActivity.this.dump(mTimedOut, (String)msg.obj); + return; + } + + super.handleMessage(msg); + } + } + + public void requestWebKitData() { + Message callback = mHandler.obtainMessage(MSG_WEBKIT_DATA); + + if (mRequestedWebKitData) + throw new AssertionError("Requested webkit data twice: " + mWebView.getUrl()); + + mRequestedWebKitData = true; + if (mDumpAsText) { + mWebView.documentAsText(callback); + } else { + mWebView.externalRepresentation(callback); + } + } + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + LinearLayout contentView = new LinearLayout(this); + contentView.setOrientation(LinearLayout.VERTICAL); + setContentView(contentView); + + mWebView = new WebView(this); + mWebView.getSettings().setJavaScriptEnabled(true); + mWebView.setWebChromeClient(mChromeClient); + mEventSender = new WebViewEventSender(mWebView); + mCallbackProxy = new CallbackProxy(mEventSender, this); + + mWebView.addJavascriptInterface(mCallbackProxy, "layoutTestController"); + mWebView.addJavascriptInterface(mCallbackProxy, "eventSender"); + contentView.addView(mWebView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0f)); + + mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); + + mHandler = new AsyncHandler(); + + Intent intent = getIntent(); + if (intent != null) { + executeIntent(intent); + } + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + executeIntent(intent); + } + + private void executeIntent(Intent intent) { + resetTestStatus(); + if (!Intent.ACTION_VIEW.equals(intent.getAction())) { + return; + } + + mTestUrl = intent.getStringExtra(TEST_URL); + if (mTestUrl == null) + return; + + mResultFile = intent.getStringExtra(RESULT_FILE); + mTimeoutInMillis = intent.getIntExtra(TIMEOUT_IN_MILLIS, 0); + + Log.v(LOGTAG, " Loading " + mTestUrl); + mWebView.loadUrl(mTestUrl); + + if (mTimeoutInMillis > 0) { + // Create a timeout timer + Message m = mHandler.obtainMessage(MSG_TIMEOUT); + mHandler.sendMessageDelayed(m, mTimeoutInMillis); + } + } + + @Override + protected void onStop() { + super.onStop(); + mWebView.stopLoading(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + mWebView.destroy(); + mWebView = null; + } + + @Override + public void onLowMemory() { + super.onLowMemory(); + Log.e(LOGTAG, "Low memory, kill self"); + System.exit(1); + } + + // Dump the page + public void dump(boolean timeout, String webkitData) { + if (mResultFile == null || mResultFile.length() == 0) { + finished(); + return; + } + + try { + File parentDir = new File(mResultFile).getParentFile(); + if (!parentDir.exists()) { + parentDir.mkdirs(); + } + + FileOutputStream os = new FileOutputStream(mResultFile); + if (timeout) { + Log.w("Layout test: Timeout", mResultFile); + os.write(TIMEOUT_STR.getBytes()); + os.write('\n'); + } + if (mDumpTitleChanges) + os.write(mTitleChanges.toString().getBytes()); + if (mDialogStrings != null) + os.write(mDialogStrings.toString().getBytes()); + mDialogStrings = null; + os.write(webkitData.getBytes()); + os.flush(); + os.close(); + } catch (IOException ex) { + Log.e(LOGTAG, "Cannot write to " + mResultFile + ", " + ex.getMessage()); + } + + finished(); + } + + public void setCallback(TestShellCallback callback) { + mCallback = callback; + } + + public void finished() { + if (mCallback != null) { + mCallback.finished(); + } + } + + // ....................................... + // LayoutTestController Functions + public void dumpAsText() { + mDumpAsText = true; + if (mWebView != null) { + String url = mWebView.getUrl(); + Log.v(LOGTAG, "dumpAsText called: "+url); + } + } + + public void waitUntilDone() { + mWaitUntilDone = true; + String url = mWebView.getUrl(); + Log.v(LOGTAG, "waitUntilDone called: " + url); + } + + public void notifyDone() { + String url = mWebView.getUrl(); + Log.v(LOGTAG, "notifyDone called: " + url); + if (mWaitUntilDone) { + mWaitUntilDone = false; + mChromeClient.onProgressChanged(mWebView, 100); + } + } + + public void display() { + mWebView.invalidate(); + } + + public void clearBackForwardList() { + mWebView.clearHistory(); + + } + + public void dumpBackForwardList() { + //printf("\n============== Back Forward List ==============\n"); + // mWebHistory + //printf("===============================================\n"); + + } + + public void dumpChildFrameScrollPositions() { + // TODO Auto-generated method stub + + } + + public void dumpEditingCallbacks() { + // TODO Auto-generated method stub + + } + + public void dumpSelectionRect() { + // TODO Auto-generated method stub + + } + + public void dumpTitleChanges() { + if (!mDumpTitleChanges) { + mTitleChanges = new StringBuffer(); + } + mDumpTitleChanges = true; + } + + public void keepWebHistory() { + if (!mKeepWebHistory) { + mWebHistory = new Vector(); + } + mKeepWebHistory = true; + } + + public void queueBackNavigation(int howfar) { + // TODO Auto-generated method stub + + } + + public void queueForwardNavigation(int howfar) { + // TODO Auto-generated method stub + + } + + public void queueLoad(String Url, String frameTarget) { + // TODO Auto-generated method stub + + } + + public void queueReload() { + mWebView.reload(); + } + + public void queueScript(String scriptToRunInCurrentContext) { + mWebView.loadUrl("javascript:"+scriptToRunInCurrentContext); + } + + public void repaintSweepHorizontally() { + // TODO Auto-generated method stub + + } + + public void setAcceptsEditing(boolean b) { + // TODO Auto-generated method stub + + } + + public void setMainFrameIsFirstResponder(boolean b) { + // TODO Auto-generated method stub + + } + + public void setWindowIsKey(boolean b) { + // This is meant to show/hide the window. The best I can find + // is setEnabled() + mWebView.setEnabled(b); + } + + public void testRepaint() { + mWebView.invalidate(); + } + + private final WebChromeClient mChromeClient = new WebChromeClient() { + @Override + public void onProgressChanged(WebView view, int newProgress) { + if (newProgress == 100) { + if (!mTimedOut && !mWaitUntilDone && !mRequestedWebKitData) { + String url = mWebView.getUrl(); + Log.v(LOGTAG, "Finished: "+ url); + mHandler.removeMessages(MSG_TIMEOUT); + requestWebKitData(); + } else { + String url = mWebView.getUrl(); + if (mTimedOut) { + Log.v(LOGTAG, "Timed out before finishing: " + url); + } else if (mWaitUntilDone) { + Log.v(LOGTAG, "Waiting for notifyDone: " + url); + } else if (mRequestedWebKitData) { + Log.v(LOGTAG, "Requested webkit data ready: " + url); + } + } + } + } + + @Override + public void onReceivedTitle(WebView view, String title) { + if (title.length() > 30) + title = "..."+title.substring(title.length()-30); + setTitle(title); + if (mDumpTitleChanges) { + mTitleChanges.append("TITLE CHANGED: "); + mTitleChanges.append(title); + mTitleChanges.append("\n"); + } + } + + @Override + public boolean onJsAlert(WebView view, String url, String message, + JsResult result) { + if (mDialogStrings == null) { + mDialogStrings = new StringBuffer(); + } + mDialogStrings.append("ALERT: "); + mDialogStrings.append(message); + mDialogStrings.append('\n'); + result.confirm(); + return true; + } + + @Override + public boolean onJsConfirm(WebView view, String url, String message, + JsResult result) { + if (mDialogStrings == null) { + mDialogStrings = new StringBuffer(); + } + mDialogStrings.append("CONFIRM: "); + mDialogStrings.append(message); + mDialogStrings.append('\n'); + result.confirm(); + return true; + } + + @Override + public boolean onJsPrompt(WebView view, String url, String message, + String defaultValue, JsPromptResult result) { + if (mDialogStrings == null) { + mDialogStrings = new StringBuffer(); + } + mDialogStrings.append("PROMPT: "); + mDialogStrings.append(message); + mDialogStrings.append(", default text: "); + mDialogStrings.append(defaultValue); + mDialogStrings.append('\n'); + result.confirm(); + return true; + } + }; + + private void resetTestStatus() { + mWaitUntilDone = false; + mDumpAsText = false; + mTimedOut = false; + mDumpTitleChanges = false; + mRequestedWebKitData = false; + mEventSender.resetMouse(); + } + + private WebView mWebView; + private WebViewEventSender mEventSender; + private AsyncHandler mHandler; + private TestShellCallback mCallback; + + private CallbackProxy mCallbackProxy; + + private String mTestUrl; + private String mResultFile; + private int mTimeoutInMillis; + + // States + private boolean mTimedOut; + private boolean mRequestedWebKitData; + private boolean mFinishedRunning; + + // Layout test controller variables. + private boolean mDumpAsText; + private boolean mWaitUntilDone; + private boolean mDumpTitleChanges; + private StringBuffer mTitleChanges; + private StringBuffer mDialogStrings; + private boolean mKeepWebHistory; + private Vector mWebHistory; + + static final String TIMEOUT_STR = "**Test timeout"; + + static final int MSG_TIMEOUT = 0; + static final int MSG_WEBKIT_DATA = 1; + + static final String LOGTAG="TestShell"; + + static final String TEST_URL = "TestUrl"; + static final String RESULT_FILE = "ResultFile"; + static final String TIMEOUT_IN_MILLIS = "TimeoutInMillis"; +} diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/HTMLHostCallbackInterface.java b/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellCallback.java similarity index 89% rename from tests/DumpRenderTree/src/com/android/dumprendertree/HTMLHostCallbackInterface.java rename to tests/DumpRenderTree/src/com/android/dumprendertree/TestShellCallback.java index 60a2915fbc55b1de09f3bdd68ca294731e2a7d64..759c443392eb45db929a4ec7d487eb6863e0700a 100644 --- a/tests/DumpRenderTree/src/com/android/dumprendertree/HTMLHostCallbackInterface.java +++ b/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellCallback.java @@ -16,6 +16,6 @@ package com.android.dumprendertree; -public interface HTMLHostCallbackInterface { - public void waitForFinish(); +public interface TestShellCallback { + public void finished(); } diff --git a/tests/FrameworkTest/AndroidManifest.xml b/tests/FrameworkTest/AndroidManifest.xml index 8106a50e2eca5c3c3f0dd1717b03792a44de28b8..c70302be798fb73ec692a91665d0be59489b8fc4 100644 --- a/tests/FrameworkTest/AndroidManifest.xml +++ b/tests/FrameworkTest/AndroidManifest.xml @@ -571,6 +571,14 @@ + + + + + + + + @@ -845,6 +853,13 @@ + + + + + + + diff --git a/tests/FrameworkTest/src/com/android/frameworktest/drawable/MutateDrawable.java b/tests/FrameworkTest/src/com/android/frameworktest/drawable/MutateDrawable.java new file mode 100644 index 0000000000000000000000000000000000000000..2fcaea3f8db7dee2699a5527f3270ab2c69382cc --- /dev/null +++ b/tests/FrameworkTest/src/com/android/frameworktest/drawable/MutateDrawable.java @@ -0,0 +1,49 @@ +/* + * 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. + */ + +package com.android.frameworktest.drawable; + +import android.app.Activity; +import android.os.Bundle; +import android.widget.LinearLayout; +import android.widget.Button; +import com.android.frameworktest.R; + +public class MutateDrawable extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + LinearLayout layout = new LinearLayout(this); + + Button ok = new Button(this); + ok.setId(R.id.a); + ok.setBackgroundDrawable(getResources().getDrawable( + R.drawable.sym_now_playing_skip_forward_1)); + + Button cancel = new Button(this); + cancel.setId(R.id.b); + cancel.setBackgroundDrawable(getResources().getDrawable( + R.drawable.sym_now_playing_skip_forward_1)); + + layout.addView(ok); + layout.addView(cancel); + + ok.getBackground().mutate().setAlpha(127); + + setContentView(layout); + } +} diff --git a/core/java/com/android/internal/os/HandlerHelper.java b/tests/FrameworkTest/src/com/android/frameworktest/listview/ListWithFirstScreenUnSelectable.java similarity index 56% rename from core/java/com/android/internal/os/HandlerHelper.java rename to tests/FrameworkTest/src/com/android/frameworktest/listview/ListWithFirstScreenUnSelectable.java index d810e6b044a0a9f867c06ce079824ca7b2a7a0ae..4ad72fd8f52c578fa53119ca5a131c03dc0c9df8 100644 --- a/core/java/com/android/internal/os/HandlerHelper.java +++ b/tests/FrameworkTest/src/com/android/frameworktest/listview/ListWithFirstScreenUnSelectable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 The Android Open Source Project + * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,25 +14,20 @@ * limitations under the License. */ -package com.android.internal.os; +package com.android.frameworktest.listview; -import android.os.Handler; -import android.os.HandlerInterface; -import android.os.Message; +import com.android.frameworktest.util.ListScenario; -/** @hide */ -public class HandlerHelper extends Handler -{ - public HandlerHelper(HandlerInterface target) - { - mTarget = target; - } +/** + * The first item is unselectable, and takes up the whole screen. + */ +public class ListWithFirstScreenUnSelectable extends ListScenario { - public void handleMessage(Message msg) - { - mTarget.handleMessage(msg); - } + @Override + protected void init(Params params) { + params.setItemScreenSizeFactor(1.2) + .setNumItems(2) + .setPositionsUnselectable(0); - private HandlerInterface mTarget; + } } - diff --git a/tests/FrameworkTest/tests/src/com/android/frameworktest/drawable/MutateDrawableTest.java b/tests/FrameworkTest/tests/src/com/android/frameworktest/drawable/MutateDrawableTest.java new file mode 100644 index 0000000000000000000000000000000000000000..53085ca9b681b2671a8f155aa28f7b88229712b0 --- /dev/null +++ b/tests/FrameworkTest/tests/src/com/android/frameworktest/drawable/MutateDrawableTest.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package com.android.frameworktest.drawable; + +import android.test.ActivityInstrumentationTestCase2; +import android.test.suitebuilder.annotation.MediumTest; +import android.view.View; + +public class MutateDrawableTest extends ActivityInstrumentationTestCase2 { + private View mFirstButton; + private View mSecondButton; + + public MutateDrawableTest() { + super("com.android.frameworktest", MutateDrawable.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + mFirstButton = getActivity().findViewById(com.android.frameworktest.R.id.a); + mSecondButton = getActivity().findViewById(com.android.frameworktest.R.id.b); + } + + @MediumTest + public void testSetUpConditions() throws Exception { + assertNotNull(mFirstButton); + assertNotNull(mSecondButton); + assertNotSame(mFirstButton.getBackground(), mSecondButton.getBackground()); + } + + @MediumTest + public void testDrawableCanMutate() throws Exception { + assertNotSame(mFirstButton.getBackground().getConstantState(), + mSecondButton.getBackground().getConstantState()); + } +} diff --git a/tests/FrameworkTest/tests/src/com/android/frameworktest/focus/ScrollingThroughListOfFocusablesTest.java b/tests/FrameworkTest/tests/src/com/android/frameworktest/focus/ScrollingThroughListOfFocusablesTest.java index 2134e040c77e89e42c4b83805b2ed02fcd15e795..07916ee83d3c6368b385f55e1785d501a4ecaa2e 100644 --- a/tests/FrameworkTest/tests/src/com/android/frameworktest/focus/ScrollingThroughListOfFocusablesTest.java +++ b/tests/FrameworkTest/tests/src/com/android/frameworktest/focus/ScrollingThroughListOfFocusablesTest.java @@ -87,9 +87,12 @@ public class ScrollingThroughListOfFocusablesTest extends InstrumentationTestCas assertEquals(0, mListView.getSelectedItemPosition()); InternalSelectionView view = (InternalSelectionView) mListView.getSelectedView(); - assertEquals("bottom of view should be just above fading edge", - mListView.getBottom() - mListView.getVerticalFadingEdgeLength(), - view.getBottom()); + + // 1 pixel tolerance in case height / 4 is not an even number + final int fadingEdge = mListView.getBottom() - mListView.getVerticalFadingEdgeLength(); + assertTrue("bottom of view should be just above fading edge", + view.getBottom() >= fadingEdge - 1 && + view.getBottom() <= fadingEdge); } @@ -138,9 +141,9 @@ public class ScrollingThroughListOfFocusablesTest extends InstrumentationTestCas view.getRectForRow(mTempRect, mNumRowsPerItem - 1); mListView.offsetDescendantRectToMyCoords(view, mTempRect); - assertEquals("bottom of last row of last item should be at " + + assertTrue("bottom of last row of last item should be at " + "the bottom of the list view (no fading edge)", - mListView.getBottom(), mTempRect.bottom); + mListView.getBottom() - mListView.getVerticalFadingEdgeLength() < mTempRect.bottom); } @LargeTest diff --git a/tests/FrameworkTest/tests/src/com/android/frameworktest/layout/table/VerticalGravityTest.java b/tests/FrameworkTest/tests/src/com/android/frameworktest/layout/table/VerticalGravityTest.java index de3e68be9c8dc81ada9bd8810f83a4ffdb923896..d731243226394fd282078c405eef558b51fceb17 100644 --- a/tests/FrameworkTest/tests/src/com/android/frameworktest/layout/table/VerticalGravityTest.java +++ b/tests/FrameworkTest/tests/src/com/android/frameworktest/layout/table/VerticalGravityTest.java @@ -21,6 +21,7 @@ import com.android.frameworktest.R; import android.test.ActivityInstrumentationTestCase; import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.Suppress; import android.test.ViewAsserts; import android.view.View; @@ -73,6 +74,7 @@ public class VerticalGravityTest extends ActivityInstrumentationTestCase implements @@ -88,8 +87,6 @@ public class ListScrollListenerTest extends ActivityInstrumentationTestCase { + private ListView mListView; + + public ListWithFirstScreenUnSelectableTest() { + super("com.android.frameworktest", ListWithFirstScreenUnSelectable.class); + } + + protected void setUp() throws Exception { + super.setUp(); + + setActivityInitialTouchMode(true); + + mListView = getActivity().getListView(); + } + + public void testPreconditions() { + assertTrue(mListView.isInTouchMode()); + assertEquals(1, mListView.getChildCount()); + assertFalse(mListView.getAdapter().isEnabled(0)); + assertEquals(AdapterView.INVALID_POSITION, mListView.getSelectedItemPosition()); + } + + public void testRessurectSelection() { + sendKeys(KeyEvent.KEYCODE_SPACE); + assertEquals(AdapterView.INVALID_POSITION, mListView.getSelectedItemPosition()); + } + + public void testScrollUpDoesNothing() { + sendKeys(KeyEvent.KEYCODE_DPAD_UP); + assertEquals(AdapterView.INVALID_POSITION, mListView.getSelectedItemPosition()); + assertEquals(1, mListView.getChildCount()); + assertEquals(0, mListView.getFirstVisiblePosition()); + } + + public void testScrollDownPansNextItemOn() { + sendKeys(KeyEvent.KEYCODE_DPAD_DOWN); + assertEquals(2, mListView.getChildCount()); + } +} diff --git a/tests/FrameworkTest/tests/src/com/android/frameworktest/widget/ListViewTest.java b/tests/FrameworkTest/tests/src/com/android/frameworktest/widget/ListViewTest.java index dff1610c3790bc071ffd4fb47edaaf6183812298..ecb7d3ad5ea9c899c28eacdfbccc08e3fb8b37f6 100644 --- a/tests/FrameworkTest/tests/src/com/android/frameworktest/widget/ListViewTest.java +++ b/tests/FrameworkTest/tests/src/com/android/frameworktest/widget/ListViewTest.java @@ -92,7 +92,7 @@ public class ListViewTest extends InstrumentationTestCase { @Override public Resources getResources() { - return null; + return getInstrumentation().getTargetContext().getResources(); } @Override diff --git a/tests/GadgetHost/AndroidManifest.xml b/tests/GadgetHost/AndroidManifest.xml deleted file mode 100644 index eeb8979fa14920585fc454c0ab4ecfe5ef2b1159..0000000000000000000000000000000000000000 --- a/tests/GadgetHost/AndroidManifest.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/GadgetHost/res/xml/gadget_info.xml b/tests/GadgetHost/res/xml/gadget_info.xml deleted file mode 100644 index 84d0603cdbcb437379425cf7a168c013da986885..0000000000000000000000000000000000000000 --- a/tests/GadgetHost/res/xml/gadget_info.xml +++ /dev/null @@ -1,7 +0,0 @@ - - diff --git a/tests/GadgetHost/src/com/android/gadgethost/GadgetHostActivity.java b/tests/GadgetHost/src/com/android/gadgethost/GadgetHostActivity.java deleted file mode 100644 index 38073fa8d936df4cbb5ac8109946df32ddebfc3d..0000000000000000000000000000000000000000 --- a/tests/GadgetHost/src/com/android/gadgethost/GadgetHostActivity.java +++ /dev/null @@ -1,130 +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. - */ - -package com.android.gadgethost; - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.gadget.GadgetHost; -import android.gadget.GadgetHostView; -import android.gadget.GadgetInfo; -import android.gadget.GadgetManager; -import android.os.Bundle; -import android.util.Log; -import android.view.ContextMenu; -import android.view.View; -import android.widget.LinearLayout; - -public class GadgetHostActivity extends Activity -{ - static final String TAG = "GadgetHostActivity"; - - static final int DISCOVER_GADGET_REQUEST = 1; - - GadgetManager mGadgetManager; - GadgetContainerView mGadgetContainer; - - public GadgetHostActivity() { - mGadgetManager = GadgetManager.getInstance(this); - } - - @Override - public void onCreate(Bundle icicle) { - super.onCreate(icicle); - setContentView(R.layout.gadget_host); - - findViewById(R.id.add_gadget).setOnClickListener(mOnClickListener); - mGadgetContainer = (GadgetContainerView)findViewById(R.id.gadget_container); - } - - View.OnClickListener mOnClickListener = new View.OnClickListener() { - public void onClick(View v) { - discoverGadget(DISCOVER_GADGET_REQUEST); - } - }; - - void discoverGadget(int requestCode) { - Intent intent = new Intent(GadgetManager.GADGET_PICK_ACTION); - startActivityForResult(intent, requestCode); - } - - void handleGadgetPickResult(int resultCode, Intent data) { - if (resultCode == RESULT_OK) { - Bundle extras = data.getExtras(); - int gadgetId = extras.getInt(GadgetManager.EXTRA_GADGET_ID); - GadgetInfo gadget = mGadgetManager.getGadgetInfo(gadgetId); - - if (gadget.configure != null) { - // configure the gadget if we should - - // TODO: start the activity. Watch for a cancel result. If it returns - // RESULT_CANCELED, then remove the gadget. - } else { - // just add it as is - addGadgetView(gadgetId, gadget); - } - } - } - - void addGadgetView(int gadgetId, GadgetInfo gadget) { - // Inflate the gadget's RemoteViews - GadgetHostView view = mHost.createView(this, gadgetId, gadget); - - // Add it to the list - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( - 65, // LinearLayout.LayoutParams.WRAP_CONTENT, - LinearLayout.LayoutParams.WRAP_CONTENT); - mGadgetContainer.addView(view, layoutParams); - } - - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - switch (requestCode) { - case DISCOVER_GADGET_REQUEST: - handleGadgetPickResult(resultCode, data); - break; - } - } - - protected void onStart() { - super.onStart(); - mHost.startListening(); - } - - protected void onStop() { - super.onStop(); - mHost.stopListening(); - } - - class MyGadgetView extends GadgetHostView { - MyGadgetView() { - super(GadgetHostActivity.this); - } - - public void createContextMenu(ContextMenu menu) { - menu.add("Delete"); - } - } - - GadgetHost mHost = new GadgetHost(this, 0) { - protected GadgetHostView onCreateView(Context context, int gadgetId, GadgetInfo gadget) { - return new MyGadgetView(); - } - }; - -} - - diff --git a/tests/GadgetHost/src/com/android/gadgethost/GadgetPickActivity.java b/tests/GadgetHost/src/com/android/gadgethost/GadgetPickActivity.java deleted file mode 100644 index a9955440ba34d47ef12f61a496cd657df4a18290..0000000000000000000000000000000000000000 --- a/tests/GadgetHost/src/com/android/gadgethost/GadgetPickActivity.java +++ /dev/null @@ -1,73 +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. - */ - -package com.android.gadgethost; - -import android.app.ListActivity; -import android.content.ComponentName; -import android.content.Intent; -import android.gadget.GadgetInfo; -import android.gadget.GadgetManager; -import android.os.Bundle; -import android.view.View; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import android.util.Log; - -import java.util.List; - -public class GadgetPickActivity extends ListActivity -{ - private static final String TAG = "GadgetPickActivity"; - - GadgetManager mGadgetManager; - List mInstalled; - - public GadgetPickActivity() { - mGadgetManager = GadgetManager.getInstance(this); - } - - @Override - public void onCreate(Bundle icicle) { - super.onCreate(icicle); - - Bundle extras = getIntent().getExtras(); - - List installed = mGadgetManager.getInstalledProviders(); - mInstalled = installed; - final int N = installed.size(); - String[] labels = new String[N]; - for (int i=0; i(this, android.R.layout.simple_list_item_1, labels)); - } - - @Override - public void onListItemClick(ListView l, View v, int position, long id) - { - int gadgetId = mGadgetManager.allocateGadgetId(getCallingPackage()); - mGadgetManager.bindGadgetId(gadgetId, mInstalled.get(position).provider); - - Intent result = new Intent(); - result.putExtra(GadgetManager.EXTRA_GADGET_ID, gadgetId); - - setResult(RESULT_OK, result); - finish(); - } -} - diff --git a/tests/ImfTest/AndroidManifest.xml b/tests/ImfTest/AndroidManifest.xml index 85d6b0ce862c4ee1b71e586914ce236519b71b08..55e5d386a235a3f415060b2bcc9ed7a2649ac116 100755 --- a/tests/ImfTest/AndroidManifest.xml +++ b/tests/ImfTest/AndroidManifest.xml @@ -19,6 +19,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/ImfTest/res/layout/dialog_edit_text_no_scroll.xml b/tests/ImfTest/res/layout/dialog_edit_text_no_scroll.xml new file mode 100644 index 0000000000000000000000000000000000000000..e8ffa1ce8fc86a127fbf402501d2c611f0655804 --- /dev/null +++ b/tests/ImfTest/res/layout/dialog_edit_text_no_scroll.xml @@ -0,0 +1,36 @@ + + + + + + + + + + diff --git a/core/res/res/layout/time_picker_text.xml b/tests/ImfTest/res/layout/full_screen_edit_text.xml old mode 100644 new mode 100755 similarity index 73% rename from core/res/res/layout/time_picker_text.xml rename to tests/ImfTest/res/layout/full_screen_edit_text.xml index bad980b64324d5f00e48ffdba8a960ac69ccc9ab..f22aa2f724cb75723755c999311101a0182a426c --- a/core/res/res/layout/time_picker_text.xml +++ b/tests/ImfTest/res/layout/full_screen_edit_text.xml @@ -1,7 +1,8 @@ - - - + android:minLines="15" + android:gravity="top"/> + diff --git a/tests/ImfTest/res/layout/one_edit_text_activity.xml b/tests/ImfTest/res/layout/one_edit_text_activity.xml new file mode 100755 index 0000000000000000000000000000000000000000..09925e1e76cbc15dce009fc88186f633c84b278f --- /dev/null +++ b/tests/ImfTest/res/layout/one_edit_text_activity.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + diff --git a/location/java/com/android/internal/location/protocol/GLatLng.java b/tests/ImfTest/res/values/config.xml similarity index 56% rename from location/java/com/android/internal/location/protocol/GLatLng.java rename to tests/ImfTest/res/values/config.xml index 90e23df54db836f0c5dffa4368d22b32aff5af67..5ae40a381523f3e8eb97e83fdf5ec0f6715c18b5 100644 --- a/location/java/com/android/internal/location/protocol/GLatLng.java +++ b/tests/ImfTest/res/values/config.xml @@ -1,23 +1,21 @@ -/* - * Copyright (C) 2007 The Android Open Source Project + + + + false + diff --git a/tests/ImfTest/res/values/strings.xml b/tests/ImfTest/res/values/strings.xml index a56c36375f1c53cce6e1e3c0a5fb4c33f7791f58..fc87480788d6319a8dab9bfcf95b2ec3a7c8b2cf 100755 --- a/tests/ImfTest/res/values/strings.xml +++ b/tests/ImfTest/res/values/strings.xml @@ -35,5 +35,16 @@ Datetime Date Time + Cap Chars + Cap Words + Multiline + Search (flag) + Cap Sentences + Auto Complete + Auto Correct + Test Dialog + open scrollable dialog + open nonscrollable dialog + diff --git a/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityLandscape.java b/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityLandscape.java new file mode 100644 index 0000000000000000000000000000000000000000..9638d34ab567cef5b695b56f5b7f1da65f1e6b03 --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityLandscape.java @@ -0,0 +1,85 @@ +package com.android.imftest.samples; + +import android.app.Activity; +import android.app.ActivityManagerNative; +import android.os.Bundle; +import android.os.RemoteException; +import android.provider.MediaStore; +import android.view.KeyEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.AutoCompleteTextView; +import android.widget.ArrayAdapter; +import android.content.Intent; +import android.content.pm.ActivityInfo; + +import com.android.internal.R; + +/* + * Activity with AutoCompleteTextView forced to landscape mode + */ +public class AutoCompleteTextViewActivityLandscape extends Activity +{ + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + setContentView(R.layout.auto_complete_list); + + ArrayAdapter adapter = new ArrayAdapter(this, + android.R.layout.simple_dropdown_item_1line, COUNTRIES); + AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit); + textView.setAdapter(adapter); + } + + static final String[] COUNTRIES = new String[] { + "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", + "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", + "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", + "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", + "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", + "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", + "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", + "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde", + "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", + "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", + "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic", + "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic", + "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", + "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland", + "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia", + "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", + "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", + "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary", + "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", + "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos", + "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", + "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", + "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", + "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", + "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", + "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas", + "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", + "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar", + "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena", + "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon", + "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal", + "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", + "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea", + "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", + "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas", + "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", + "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda", + "Ukraine", "United Arab Emirates", "United Kingdom", + "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", + "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara", + "Yemen", "Yugoslavia", "Zambia", "Zimbabwe" + }; +} diff --git a/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityPortrait.java b/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityPortrait.java new file mode 100644 index 0000000000000000000000000000000000000000..58651e1bfb86e7220b23724852cbfc38a9a773cf --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityPortrait.java @@ -0,0 +1,79 @@ +package com.android.imftest.samples; + +import android.app.Activity; +import android.os.Bundle; +import android.view.KeyEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.AutoCompleteTextView; +import android.widget.ArrayAdapter; + +import com.android.internal.R; + +/* + * Activity with AutoCompleteTextView (Candidate bar should not appear) + */ +public class AutoCompleteTextViewActivityPortrait extends Activity +{ + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + setContentView(R.layout.auto_complete_list); + + ArrayAdapter adapter = new ArrayAdapter(this, + android.R.layout.simple_dropdown_item_1line, COUNTRIES); + AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit); + textView.setAdapter(adapter); + } + + static final String[] COUNTRIES = new String[] { + "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", + "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", + "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", + "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", + "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", + "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", + "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", + "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde", + "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", + "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", + "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic", + "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic", + "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", + "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland", + "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia", + "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", + "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", + "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary", + "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", + "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos", + "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", + "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", + "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", + "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", + "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", + "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas", + "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", + "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar", + "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena", + "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon", + "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal", + "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", + "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea", + "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", + "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas", + "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", + "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda", + "Ukraine", "United Arab Emirates", "United Kingdom", + "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", + "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara", + "Yemen", "Yugoslavia", "Zambia", "Zimbabwe" + }; +} diff --git a/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityNonScrollablePanScan.java b/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityNonScrollablePanScan.java new file mode 100644 index 0000000000000000000000000000000000000000..9754381e2ce379b22c971a4f69c6f633db573ebd --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityNonScrollablePanScan.java @@ -0,0 +1,49 @@ +package com.android.imftest.samples; + +import com.android.imftest.R; + +import android.app.Activity; +import android.os.Bundle; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; + +public class BigEditTextActivityNonScrollablePanScan extends Activity { + + private View mRootView; + private View mDefaultFocusedView; + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); + + mRootView = new LinearLayout(this); + ((LinearLayout) mRootView).setOrientation(LinearLayout.VERTICAL); + mRootView.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + + View view = getLayoutInflater().inflate( + R.layout.full_screen_edit_text, ((LinearLayout) mRootView), false); + + ((LinearLayout) mRootView).addView(view); + + mDefaultFocusedView = view.findViewById(R.id.data); + + setContentView(mRootView); + } + + public View getRootView() { + return mRootView; + } + + public View getDefaultFocusedView() { + return mDefaultFocusedView; + } + +} diff --git a/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityNonScrollableResize.java b/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityNonScrollableResize.java new file mode 100644 index 0000000000000000000000000000000000000000..701795fe4a7be59dc3de542e51af552da7e04ca3 --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityNonScrollableResize.java @@ -0,0 +1,49 @@ +package com.android.imftest.samples; + +import com.android.imftest.R; + +import android.app.Activity; +import android.os.Bundle; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; + +public class BigEditTextActivityNonScrollableResize extends Activity { + + private View mRootView; + private View mDefaultFocusedView; + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + + mRootView = new LinearLayout(this); + ((LinearLayout) mRootView).setOrientation(LinearLayout.VERTICAL); + mRootView.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + + View view = getLayoutInflater().inflate( + R.layout.full_screen_edit_text, ((LinearLayout) mRootView), false); + + ((LinearLayout) mRootView).addView(view); + + mDefaultFocusedView = view.findViewById(R.id.data); + + setContentView(mRootView); + } + + public View getRootView() { + return mRootView; + } + + public View getDefaultFocusedView() { + return mDefaultFocusedView; + } + +} diff --git a/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityScrollablePanScan.java b/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityScrollablePanScan.java new file mode 100644 index 0000000000000000000000000000000000000000..bb3f7671a8603c3b8362e5da9c31324f7c15ed80 --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityScrollablePanScan.java @@ -0,0 +1,57 @@ +package com.android.imftest.samples; + +import com.android.imftest.R; + +import android.app.Activity; +import android.os.Bundle; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; + +public class BigEditTextActivityScrollablePanScan extends Activity { + + private View mRootView; + private View mDefaultFocusedView; + private LinearLayout mLayout; + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); + + mRootView = new ScrollView(this); + ((ScrollView) mRootView).setFillViewport(true); + mRootView.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + + mLayout = new LinearLayout(this); + mLayout.setOrientation(LinearLayout.VERTICAL); + mLayout.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + + View view = getLayoutInflater().inflate( + R.layout.full_screen_edit_text, ((ScrollView) mRootView), false); + + mLayout.addView(view); + + ((ScrollView) mRootView).addView(mLayout); + mDefaultFocusedView = view.findViewById(R.id.data); + + setContentView(mRootView); + } + + public View getRootView() { + return mRootView; + } + + public View getDefaultFocusedView() { + return mDefaultFocusedView; + } + +} diff --git a/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityScrollableResize.java b/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityScrollableResize.java new file mode 100644 index 0000000000000000000000000000000000000000..f2cae1cdfca7e7bcd38f5dcc200dfd308dd0dd46 --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/BigEditTextActivityScrollableResize.java @@ -0,0 +1,57 @@ +package com.android.imftest.samples; + +import com.android.imftest.R; + +import android.app.Activity; +import android.os.Bundle; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; + +public class BigEditTextActivityScrollableResize extends Activity { + + private View mRootView; + private View mDefaultFocusedView; + private LinearLayout mLayout; + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + + mRootView = new ScrollView(this); + ((ScrollView) mRootView).setFillViewport(true); + mRootView.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + + mLayout = new LinearLayout(this); + mLayout.setOrientation(LinearLayout.VERTICAL); + mLayout.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + + View view = getLayoutInflater().inflate( + R.layout.full_screen_edit_text, ((ScrollView) mRootView), false); + + mLayout.addView(view); + + ((ScrollView) mRootView).addView(mLayout); + mDefaultFocusedView = view.findViewById(R.id.data); + + setContentView(mRootView); + } + + public View getRootView() { + return mRootView; + } + + public View getDefaultFocusedView() { + return mDefaultFocusedView; + } + +} diff --git a/tests/ImfTest/src/com/android/imftest/samples/BottomEditTextActivityPanScan.java b/tests/ImfTest/src/com/android/imftest/samples/BottomEditTextActivityPanScan.java new file mode 100644 index 0000000000000000000000000000000000000000..51f5045ea2021942477825e0ffc01d56b79209d4 --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/BottomEditTextActivityPanScan.java @@ -0,0 +1,46 @@ +package com.android.imftest.samples; + +import android.app.Activity; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.widget.EditText; +import android.widget.ScrollView; +import android.widget.TextView; + +import com.android.imftest.R; + +/* + * Activity with EditText at the bottom (Pan&Scan) + */ +public class BottomEditTextActivityPanScan extends Activity +{ + private View mRootView; + private View mDefaultFocusedView; + + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + mRootView = new LinearLayout(this); + ((LinearLayout) mRootView).setOrientation(LinearLayout.VERTICAL); + + View view = getLayoutInflater().inflate(R.layout.one_edit_text_activity, ((LinearLayout) mRootView), false); + mDefaultFocusedView = view.findViewById(R.id.dialog_edit_text); + ((LinearLayout) mRootView).addView(view); + + setContentView(mRootView); + this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); + } + + public View getRootView() { + return mRootView; + } + + public View getDefaultFocusedView() { + return mDefaultFocusedView; + } +} \ No newline at end of file diff --git a/tests/ImfTest/src/com/android/imftest/samples/BottomEditTextActivityResize.java b/tests/ImfTest/src/com/android/imftest/samples/BottomEditTextActivityResize.java new file mode 100644 index 0000000000000000000000000000000000000000..eb94b4f2ee383b28be26a993416855c98e9c6d21 --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/BottomEditTextActivityResize.java @@ -0,0 +1,46 @@ +package com.android.imftest.samples; + +import android.app.Activity; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.widget.EditText; +import android.widget.ScrollView; +import android.widget.TextView; + +import com.android.imftest.R; + +/* + * Activity with EditText at the bottom (Resize) + */ +public class BottomEditTextActivityResize extends Activity +{ + private View mRootView; + private View mDefaultFocusedView; + + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + mRootView = new LinearLayout(this); + ((LinearLayout) mRootView).setOrientation(LinearLayout.VERTICAL); + + View view = getLayoutInflater().inflate(R.layout.one_edit_text_activity, ((LinearLayout) mRootView), false); + mDefaultFocusedView = view.findViewById(R.id.dialog_edit_text); + ((LinearLayout) mRootView).addView(view); + + setContentView(mRootView); + this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + } + + public View getRootView() { + return mRootView; + } + + public View getDefaultFocusedView() { + return mDefaultFocusedView; + } +} \ No newline at end of file diff --git a/tests/ImfTest/src/com/android/imftest/samples/ButtonActivity.java b/tests/ImfTest/src/com/android/imftest/samples/ButtonActivity.java index 4233811a60ed86a1293f2392b0810830cc39a5f9..1191f198198a45b58aca945689d64ea9ff223aaf 100644 --- a/tests/ImfTest/src/com/android/imftest/samples/ButtonActivity.java +++ b/tests/ImfTest/src/com/android/imftest/samples/ButtonActivity.java @@ -13,6 +13,8 @@ import android.widget.TextView; public class ButtonActivity extends Activity { static boolean mKeyboardIsActive = false; + public static final int BUTTON_ID = 0; + private View mRootView; @Override public void onCreate(Bundle savedInstanceState) @@ -23,6 +25,8 @@ public class ButtonActivity extends Activity final Button myButton = new Button(this); myButton.setClickable(true); myButton.setText("Keyboard UP!"); + myButton.setId(BUTTON_ID); + myButton.setFocusableInTouchMode(true); myButton.setOnClickListener(new View.OnClickListener() { public void onClick (View v) @@ -36,7 +40,8 @@ public class ButtonActivity extends Activity } else { - imm.showSoftInput(null, 0); + myButton.requestFocusFromTouch(); + imm.showSoftInput(v, 0); myButton.setText("Keyboard DOWN!"); } @@ -48,5 +53,10 @@ public class ButtonActivity extends Activity layout.setOrientation(LinearLayout.VERTICAL); layout.addView(myButton); setContentView(layout); + mRootView = layout; + } + + public View getRootView() { + return mRootView; } } diff --git a/tests/ImfTest/src/com/android/imftest/samples/DialogActivity.java b/tests/ImfTest/src/com/android/imftest/samples/DialogActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..e49301cd9821be41c361e72710a0e241b309f9fc --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/DialogActivity.java @@ -0,0 +1,102 @@ +package com.android.imftest.samples; + +import android.app.Activity; +import android.os.Bundle; +import android.view.KeyEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.widget.EditText; +import android.widget.Button; +import android.view.LayoutInflater; +import android.app.Dialog; + +import com.android.internal.R; + +public class DialogActivity extends Activity { + + private static final int DIALOG_WITHOUT_EDITTEXT = 0; + private static final int DIALOG_WITH_EDITTEXT = 1; + + private LinearLayout mLayout; + private LayoutInflater mInflater; + private Button mButton1; + private Button mButton2; + private EditText mEditText; + + + @Override + protected void onCreate(Bundle icicle) + { + super.onCreate(icicle); + + mLayout = new LinearLayout(this); + mLayout.setOrientation(LinearLayout.VERTICAL); + mLayout.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + + mButton1 = new Button(this); + mButton1.setText("Dialog WITHOUT EditText");//(R.string.open_dialog_scrollable); + mButton1.setOnClickListener(new View.OnClickListener() + { + public void onClick(View v) + { + showDialog(DIALOG_WITHOUT_EDITTEXT); + } + }); + + mButton2 = new Button(this); + mButton2.setText("Dialog WITH EditText");//(R.string.open_dialog_nonscrollable); + mButton2.setOnClickListener(new View.OnClickListener() + { + public void onClick(View v) + { + showDialog(DIALOG_WITH_EDITTEXT); + } + }); + + mEditText = new EditText(this); + mLayout.addView(mEditText); + mLayout.addView(mButton1); + mLayout.addView(mButton2); + + setContentView(mLayout); + } + + @Override + protected Dialog onCreateDialog(int id) + { + switch (id) + { + case DIALOG_WITHOUT_EDITTEXT: + return createDialog(false); + case DIALOG_WITH_EDITTEXT: + return createDialog(true); + } + + return super.onCreateDialog(id); + } + + protected Dialog createDialog(boolean bEditText) + { + LinearLayout layout; + layout = new LinearLayout(this); + layout.setOrientation(LinearLayout.VERTICAL); + + if(bEditText) + { + EditText editText; + editText = new EditText(this); + layout.addView(editText); + } + + Dialog d = new Dialog(this); + d.setTitle("The DIALOG!!!"); + d.setCancelable(true); + d.setContentView(layout); + return d; + } + + } diff --git a/tests/ImfTest/src/com/android/imftest/samples/EditTextActivityDialog.java b/tests/ImfTest/src/com/android/imftest/samples/EditTextActivityDialog.java new file mode 100644 index 0000000000000000000000000000000000000000..bd1e934364f662a86bbaf9659522512f798ca634 --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/EditTextActivityDialog.java @@ -0,0 +1,96 @@ +package com.android.imftest.samples; + +import com.android.imftest.R; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; + +public class EditTextActivityDialog extends Activity { + + private static final int SCROLLABLE_DIALOG_ID = 0; + private static final int NONSCROLLABLE_DIALOG_ID = 1; + + private LinearLayout mLayout; + private ScrollView mScrollView; + private LayoutInflater mInflater; + private Button mButton1; + private Button mButton2; + + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + mLayout = new LinearLayout(this); + mLayout.setOrientation(LinearLayout.VERTICAL); + mLayout.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + + mButton1 = new Button(this); + mButton1.setText(R.string.open_dialog_scrollable); + mButton1.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + showDialog(SCROLLABLE_DIALOG_ID); + } + }); + + mButton2 = new Button(this); + mButton2.setText(R.string.open_dialog_nonscrollable); + mButton2.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + showDialog(NONSCROLLABLE_DIALOG_ID); + } + }); + + mLayout.addView(mButton1); + mLayout.addView(mButton2); + + setContentView(mLayout); + } + + @Override + protected Dialog onCreateDialog(int id) { + switch (id) { + case SCROLLABLE_DIALOG_ID: + return createDialog(true); + case NONSCROLLABLE_DIALOG_ID: + return createDialog(false); + } + + return super.onCreateDialog(id); + } + + protected Dialog createDialog(boolean scrollable) { + View layout; + EditText editText; + + if (scrollable) { + layout = new ScrollView(EditTextActivityDialog.this); + ((ScrollView) layout).setMinimumHeight(mLayout.getHeight()); + + ((ScrollView) layout).addView(( + LinearLayout) View.inflate(EditTextActivityDialog.this, + R.layout.dialog_edit_text_no_scroll, null)); + } else { + layout = View.inflate(EditTextActivityDialog.this, + R.layout.dialog_edit_text_no_scroll, null); + } + + Dialog d = new Dialog(EditTextActivityDialog.this); + d.setTitle(getString(R.string.test_dialog)); + d.setCancelable(true); + d.setContentView(layout); + return d; + } + +} diff --git a/tests/ImfTest/src/com/android/imftest/samples/InputTypeActivity.java b/tests/ImfTest/src/com/android/imftest/samples/InputTypeActivity.java index f7aaa7bbabda942aa885413506c1c18817a12daf..17f6bdc15eb1bd2c9f0be393124c0ad38163583b 100755 --- a/tests/ImfTest/src/com/android/imftest/samples/InputTypeActivity.java +++ b/tests/ImfTest/src/com/android/imftest/samples/InputTypeActivity.java @@ -56,43 +56,63 @@ public class InputTypeActivity extends Activity { mParent = mLayout; /* Normal Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_NORMAL, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_NORMAL, R.string.normal_edit_text_label)); + /* Normal Edit Text w/Cap Chars Flag*/ + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_NORMAL|EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS, + R.string.cap_chars_edit_text_label)); + + /* Normal Edit Text w/Cap Words Flag*/ + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_NORMAL|EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS, + R.string.cap_words_edit_text_label)); + + /* Normal Edit Text w/Cap Multiline Flag */ + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_NORMAL|EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE, + R.string.multiline_edit_text_label)); + + /* Normal Edit Text w/Cap Sentences Flag */ + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_NORMAL|EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES, + R.string.cap_sentences_edit_text_label)); + + /* Normal Edit Text w/Auto-complete Flag */ + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_NORMAL|EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE, + R.string.auto_complete_edit_text_label)); + + /* Normal Edit Text w/Auto-correct Flag */ + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_NORMAL|EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT, + R.string.auto_correct_edit_text_label)); + /* Uri Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_URI, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_URI, R.string.uri_edit_text_label)); /* Email Address Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS, R.string.email_address_edit_text_label)); /* Email Subject Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT, R.string.email_subject_edit_text_label)); /* Email Content Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_EMAIL_CONTENT, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE, R.string.email_content_edit_text_label)); /* Person Name Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME, R.string.person_name_edit_text_label)); /* Postal Address Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_POSTAL_ADDRESS, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_POSTAL_ADDRESS, R.string.postal_address_edit_text_label)); /* Password Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_PASSWORD, R.string.password_edit_text_label)); - /* Search String Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_SEARCH_STRING, - R.string.search_string_edit_text_label)); - /* Web Edit Text */ - mLayout.addView(buildEntryView(EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT, + mLayout.addView(buildEntryView(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT, R.string.web_edit_text_label)); /* Signed Number Edit Text */ diff --git a/tests/ImfTest/src/com/android/imftest/samples/ManyEditTextActivityNoScrollPanScan.java b/tests/ImfTest/src/com/android/imftest/samples/ManyEditTextActivityNoScrollPanScan.java new file mode 100644 index 0000000000000000000000000000000000000000..54ab57a498bb2c4145bc99366a7ea65b53fa8eb1 --- /dev/null +++ b/tests/ImfTest/src/com/android/imftest/samples/ManyEditTextActivityNoScrollPanScan.java @@ -0,0 +1,50 @@ +package com.android.imftest.samples; + +import android.app.Activity; +import android.os.Bundle; +import android.view.KeyEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.Button; +import android.widget.TextView; +import android.widget.ScrollView; + +import com.android.internal.R; + +/* + * Full screen of EditTexts (Non-Scrollable, Pan&Scan) + */ +public class ManyEditTextActivityNoScrollPanScan extends Activity +{ + public static final int NUM_EDIT_TEXTS = 9; + + private View mRootView; + + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + mRootView = new LinearLayout(this); + ((LinearLayout) mRootView).setOrientation(LinearLayout.VERTICAL); + + for (int i=0; i + + + + + + + + + + + + + diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityNonScrollablePanScanTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityNonScrollablePanScanTests.java new file mode 100755 index 0000000000000000000000000000000000000000..a1c5fd285c34146f99e6f3dd8337e2e7c1cc19d7 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityNonScrollablePanScanTests.java @@ -0,0 +1,49 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.View; + +import com.android.imftest.R; + + +public class BigEditTextActivityNonScrollablePanScanTests extends ImfBaseTestCase { + + public final String TAG = "BigEditTextActivityNonScrollablePanScanTests"; + + public BigEditTextActivityNonScrollablePanScanTests() { + super(BigEditTextActivityNonScrollablePanScan.class); + } + + @LargeTest + public void testAppAdjustmentPanScan() { + // Give the IME 2 seconds to appear. + pause(2000); + + View rootView = ((BigEditTextActivityNonScrollablePanScan) mTargetActivity).getRootView(); + View servedView = ((BigEditTextActivityNonScrollablePanScan) mTargetActivity).getDefaultFocusedView(); + + assertNotNull(rootView); + assertNotNull(servedView); + + destructiveCheckImeInitialState(rootView, servedView); + + verifyEditTextAdjustment(servedView, rootView.getMeasuredHeight()); + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityNonScrollableResizeTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityNonScrollableResizeTests.java new file mode 100755 index 0000000000000000000000000000000000000000..2e0b0eb6e903152be1ac797fa6a1373fc51820a7 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityNonScrollableResizeTests.java @@ -0,0 +1,48 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.View; + +import com.android.imftest.R; + + +public class BigEditTextActivityNonScrollableResizeTests extends ImfBaseTestCase { + + public final String TAG = "BigEditTextActivityNonScrollableResizeTests"; + + public BigEditTextActivityNonScrollableResizeTests() { + super(BigEditTextActivityNonScrollableResize.class); + } + + @LargeTest + public void testAppAdjustmentPanScan() { // Give the IME 2 seconds to appear. + pause(2000); + + View rootView = ((BigEditTextActivityNonScrollableResize) mTargetActivity).getRootView(); + View servedView = ((BigEditTextActivityNonScrollableResize) mTargetActivity).getDefaultFocusedView(); + + assertNotNull(rootView); + assertNotNull(servedView); + + destructiveCheckImeInitialState(rootView, servedView); + + verifyEditTextAdjustment(servedView, rootView.getMeasuredHeight()); + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityScrollablePanScanTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityScrollablePanScanTests.java new file mode 100755 index 0000000000000000000000000000000000000000..d3eefb5b48c15a68e66adc56e8878148c0d25fa1 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityScrollablePanScanTests.java @@ -0,0 +1,48 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.View; + +import com.android.imftest.R; + + +public class BigEditTextActivityScrollablePanScanTests extends ImfBaseTestCase { + + public final String TAG = "BigEditTextActivityScrollablePanScanTests"; + + public BigEditTextActivityScrollablePanScanTests() { + super(BigEditTextActivityScrollablePanScan.class); + } + + @LargeTest + public void testAppAdjustmentPanScan() { // Give the IME 2 seconds to appear. + pause(2000); + + View rootView = ((BigEditTextActivityScrollablePanScan) mTargetActivity).getRootView(); + View servedView = ((BigEditTextActivityScrollablePanScan) mTargetActivity).getDefaultFocusedView(); + + assertNotNull(rootView); + assertNotNull(servedView); + + destructiveCheckImeInitialState(rootView, servedView); + + verifyEditTextAdjustment(servedView, rootView.getMeasuredHeight()); + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityScrollableResizeTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityScrollableResizeTests.java new file mode 100755 index 0000000000000000000000000000000000000000..5c40e6d966d651df2a7a237dd67539fcfe40454e --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/BigEditTextActivityScrollableResizeTests.java @@ -0,0 +1,49 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.View; + +import com.android.imftest.R; + + +public class BigEditTextActivityScrollableResizeTests extends ImfBaseTestCase { + + public final String TAG = "BigEditTextActivityScrollableResizeTests"; + + public BigEditTextActivityScrollableResizeTests() { + super(BigEditTextActivityScrollableResize.class); + } + + @LargeTest + public void testAppAdjustmentPanScan() { + // Give the IME 2 seconds to appear. + pause(2000); + + View rootView = ((BigEditTextActivityScrollableResize) mTargetActivity).getRootView(); + View servedView = ((BigEditTextActivityScrollableResize) mTargetActivity).getDefaultFocusedView(); + + assertNotNull(rootView); + assertNotNull(servedView); + + destructiveCheckImeInitialState(rootView, servedView); + + verifyEditTextAdjustment(servedView, rootView.getMeasuredHeight()); + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/BottomEditTextActivityPanScanTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/BottomEditTextActivityPanScanTests.java new file mode 100755 index 0000000000000000000000000000000000000000..9a931331adcd654f8a4dc5b4cd1d82a51890dfa2 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/BottomEditTextActivityPanScanTests.java @@ -0,0 +1,49 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.View; + +import com.android.imftest.R; + + +public class BottomEditTextActivityPanScanTests extends ImfBaseTestCase { + + public final String TAG = "BottomEditTextActivityPanScanTests"; + + public BottomEditTextActivityPanScanTests() { + super(BottomEditTextActivityPanScan.class); + } + + @LargeTest + public void testAppAdjustmentPanScan() { + // Give the IME 2 seconds to appear. + pause(2000); + + View rootView = ((BottomEditTextActivityPanScan) mTargetActivity).getRootView(); + View servedView = ((BottomEditTextActivityPanScan) mTargetActivity).getDefaultFocusedView(); + + assertNotNull(rootView); + assertNotNull(servedView); + + destructiveCheckImeInitialState(rootView, servedView); + + verifyEditTextAdjustment(servedView, rootView.getMeasuredHeight()); + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/BottomEditTextActivityResizeTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/BottomEditTextActivityResizeTests.java new file mode 100755 index 0000000000000000000000000000000000000000..9a69fd5098449898e768a4dea43e437e7eb60f03 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/BottomEditTextActivityResizeTests.java @@ -0,0 +1,49 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.View; + +import com.android.imftest.R; + + +public class BottomEditTextActivityResizeTests extends ImfBaseTestCase { + + public final String TAG = "BottomEditTextActivityResizeTests"; + + public BottomEditTextActivityResizeTests() { + super(BottomEditTextActivityResize.class); + } + + @LargeTest + public void testAppAdjustmentResize() { + // Give the IME 2 seconds to appear. + pause(2000); + + View rootView = ((BottomEditTextActivityResize) mTargetActivity).getRootView(); + View servedView = ((BottomEditTextActivityResize) mTargetActivity).getDefaultFocusedView(); + + assertNotNull(rootView); + assertNotNull(servedView); + + destructiveCheckImeInitialState(rootView, servedView); + + verifyEditTextAdjustment(servedView, rootView.getMeasuredHeight()); + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/ButtonActivityTest.java b/tests/ImfTest/tests/src/com/android/imftest/samples/ButtonActivityTest.java new file mode 100755 index 0000000000000000000000000000000000000000..ae900c34ba3b7377bab009b937be5d9a830a5c84 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/ButtonActivityTest.java @@ -0,0 +1,58 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.KeyEvent; +import android.widget.Button; + + +public class ButtonActivityTest extends ImfBaseTestCase { + + final public String TAG = "ButtonActivityTest"; + + public ButtonActivityTest() { + super(ButtonActivity.class); + } + + @LargeTest + public void testButtonActivatesIme() { + + final Button button = (Button) mTargetActivity.findViewById(ButtonActivity.BUTTON_ID); + + // Push button + // Bring the target EditText into focus. + mTargetActivity.runOnUiThread(new Runnable() { + public void run() { + button.requestFocus(); + } + }); + + sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); + + // Give it a couple seconds + pause(2000); + + // We should have initialized imm.mServedView and imm.mCurrentTextBoxAttribute + assertTrue(mImm.isActive()); + // imm.mServedInputConnection should be null since Button doesn't override onCreateInputConnection(). + assertFalse(mImm.isAcceptingText()); + + destructiveCheckImeInitialState(mTargetActivity.getRootView(), button); + + } +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/ImfBaseTestCase.java b/tests/ImfTest/tests/src/com/android/imftest/samples/ImfBaseTestCase.java new file mode 100755 index 0000000000000000000000000000000000000000..61dc61193a95f90b2df92c3ccb8fdd17531c9b99 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/ImfBaseTestCase.java @@ -0,0 +1,135 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.app.Activity; +import android.os.SystemClock; +import android.test.InstrumentationTestCase; +import android.view.KeyEvent; +import android.view.View; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; + +import com.android.imftest.R; + +public abstract class ImfBaseTestCase extends InstrumentationTestCase { + + /* + * The amount of time we are willing to wait for the IME to appear after a user action + * before we give up and fail the test. + */ + public final long WAIT_FOR_IME = 5000; + + /* + * Unfortunately there is now way for us to know how tall the IME is, + * so we have to hard code a minimum and maximum value. + */ + public final int IME_MIN_HEIGHT = 150; + public final int IME_MAX_HEIGHT = 300; + + public final String TARGET_PACKAGE_NAME = "com.android.imftest"; + protected InputMethodManager mImm; + protected T mTargetActivity; + protected boolean mExpectAutoPop; + private Class mTargetActivityClass; + + public ImfBaseTestCase(Class activityClass) { + mTargetActivityClass = activityClass; + } + + @Override + public void setUp() throws Exception { + super.setUp(); + + mTargetActivity = launchActivity(TARGET_PACKAGE_NAME, mTargetActivityClass, null); + mExpectAutoPop = mTargetActivity.getResources().getBoolean(R.bool.def_expect_ime_autopop); + mImm = InputMethodManager.getInstance(mTargetActivity); + } + + // Utility test methods + public void verifyEditTextAdjustment(final View editText, int rootViewHeight) { + + int[] origLocation = new int[2]; + int[] newLocation = new int[2]; + + // Tell the keyboard to go away. + mImm.hideSoftInputFromWindow(editText.getWindowToken(), 0); + + // Bring the target EditText into focus. + mTargetActivity.runOnUiThread(new Runnable() { + public void run() { + editText.requestFocus(); + } + }); + + // Get the original location of the EditText. + editText.getLocationOnScreen(origLocation); + + // Tap the EditText to bring up the IME. + sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); + + // Wait until the EditText pops above the IME or until we hit the timeout. + editText.getLocationOnScreen(newLocation); + long timeoutTime = SystemClock.uptimeMillis() + WAIT_FOR_IME; + while (newLocation[1] > rootViewHeight - IME_MIN_HEIGHT && SystemClock.uptimeMillis() < timeoutTime) { + editText.getLocationOnScreen(newLocation); + pause(100); + } + + assertTrue(newLocation[1] <= rootViewHeight - IME_MIN_HEIGHT); + + // Tell the keyboard to go away. + mImm.hideSoftInputFromWindow(editText.getWindowToken(), 0); + } + + public void destructiveCheckImeInitialState(View rootView, View servedView) { + if (mExpectAutoPop && (mTargetActivity.getWindow().getAttributes(). + softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) + == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) { + assertTrue(destructiveCheckImeUp(rootView, servedView)); + } else { + assertFalse(destructiveCheckImeUp(rootView, servedView)); + } + } + + public boolean destructiveCheckImeUp(View rootView, View servedView) { + int origHeight; + int newHeight; + + origHeight = rootView.getHeight(); + + // Tell the keyboard to go away. + mImm.hideSoftInputFromWindow(servedView.getWindowToken(), 0); + + // Give it five seconds to adjust + newHeight = rootView.getHeight(); + long timeoutTime = SystemClock.uptimeMillis() + WAIT_FOR_IME; + while (Math.abs(newHeight - origHeight) < IME_MIN_HEIGHT && SystemClock.uptimeMillis() < timeoutTime) { + newHeight = rootView.getHeight(); + } + + return (Math.abs(origHeight - newHeight) >= IME_MIN_HEIGHT); + } + + void pause(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + } + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityBaseTestCase.java b/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityBaseTestCase.java new file mode 100755 index 0000000000000000000000000000000000000000..278efb1f68db5ee7db16589c2c8c9e81792ebdd7 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityBaseTestCase.java @@ -0,0 +1,40 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.app.Activity; +import android.widget.EditText; + + +public abstract class ManyEditTextActivityBaseTestCase extends ImfBaseTestCase { + + public ManyEditTextActivityBaseTestCase(Class activityClass){ + super(activityClass); + } + + public abstract void testAllEditTextsAdjust(); + + public void verifyAllEditTextAdjustment(int numEditTexts, int rootViewHeight) { + + for (int i = 0; i < numEditTexts; i++) { + final EditText lastEditText = (EditText) mTargetActivity.findViewById(i); + verifyEditTextAdjustment(lastEditText, rootViewHeight); + } + + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityNoScrollPanScanTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityNoScrollPanScanTests.java new file mode 100755 index 0000000000000000000000000000000000000000..4f8d14e88ad5a40e538b480821b113051aa5de0a --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityNoScrollPanScanTests.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; + + +public class ManyEditTextActivityNoScrollPanScanTests extends ManyEditTextActivityBaseTestCase { + + public final String TAG = "ManyEditTextActivityNoScrollPanScanTests"; + + public ManyEditTextActivityNoScrollPanScanTests() { + super(ManyEditTextActivityNoScrollPanScan.class); + } + + + @LargeTest + public void testAllEditTextsAdjust() { + verifyAllEditTextAdjustment(mTargetActivity.NUM_EDIT_TEXTS, + mTargetActivity.getRootView().getMeasuredHeight()); + } +} diff --git a/location/java/com/android/internal/location/protocol/GlatlngMessageTypes.java b/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityScrollPanScanTests.java old mode 100644 new mode 100755 similarity index 50% rename from location/java/com/android/internal/location/protocol/GlatlngMessageTypes.java rename to tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityScrollPanScanTests.java index b6a908611a1ded8791d6b4a77ee702795789ac18..7f98f7fbdf21425a71626e3da6c476d10c488a15 --- a/location/java/com/android/internal/location/protocol/GlatlngMessageTypes.java +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityScrollPanScanTests.java @@ -14,19 +14,24 @@ * limitations under the License. */ -package com.android.internal.location.protocol; +package com.android.imftest.samples; -import com.google.common.io.protocol.ProtoBufType; +import android.test.suitebuilder.annotation.LargeTest; -public class GlatlngMessageTypes { - public static final ProtoBufType GLAT_LNG = new ProtoBufType(); - static { - GLAT_LNG - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_FIXED32, - GLatLng.LAT_E7, null) - .addElement(ProtoBufType.REQUIRED | ProtoBufType.TYPE_FIXED32, - GLatLng.LNG_E7, null); +public class ManyEditTextActivityScrollPanScanTests extends ManyEditTextActivityBaseTestCase { + + public final String TAG = "ManyEditTextActivityScrollPanScanTests"; + + + public ManyEditTextActivityScrollPanScanTests() { + super(ManyEditTextActivityScrollPanScan.class); + } + + @LargeTest + public void testAllEditTextsAdjust() { + verifyAllEditTextAdjustment(mTargetActivity.NUM_EDIT_TEXTS, + mTargetActivity.getRootView().getMeasuredHeight()); + } - } } diff --git a/include/GLES/egltypes.h b/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityScrollResizeTests.java old mode 100644 new mode 100755 similarity index 50% rename from include/GLES/egltypes.h rename to tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityScrollResizeTests.java index 698239b210b08228bd1edd4fe60fe276c247f50e..68dae87ea5c99b428c26c7bc5d77e719f7f653eb --- a/include/GLES/egltypes.h +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/ManyEditTextActivityScrollResizeTests.java @@ -14,34 +14,24 @@ * limitations under the License. */ -#ifndef ANDROID_EGL_TYPES_H -#define ANDROID_EGL_TYPES_H +package com.android.imftest.samples; -#include +import android.test.suitebuilder.annotation.LargeTest; -#ifdef __cplusplus -extern "C" { -#endif -typedef unsigned int EGLBoolean; -typedef int32_t EGLint; -typedef int EGLenum; -typedef void *EGLDisplay; -typedef void *EGLConfig; -typedef void *EGLSurface; -typedef void *EGLContext; -typedef void *EGLClientBuffer; +public class ManyEditTextActivityScrollResizeTests extends ManyEditTextActivityBaseTestCase { -#define EGL_DEFAULT_DISPLAY ((NativeDisplayType)0) + public final String TAG = "ManyEditTextActivityScrollResizeTests"; + + + public ManyEditTextActivityScrollResizeTests() { + super(ManyEditTextActivityScrollResize.class); + } -#define EGL_NO_CONTEXT ((EGLContext)0) -#define EGL_NO_DISPLAY ((EGLDisplay)0) -#define EGL_NO_SURFACE ((EGLSurface)0) + @LargeTest + public void testAllEditTextsAdjust() { + verifyAllEditTextAdjustment(mTargetActivity.NUM_EDIT_TEXTS, + mTargetActivity.getRootView().getMeasuredHeight()); + } - -#ifdef __cplusplus } -#endif - - -#endif /* ANDROID_EGL_TYPES_H */ diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/OneEditTextActivityNotSelectedTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/OneEditTextActivityNotSelectedTests.java new file mode 100755 index 0000000000000000000000000000000000000000..ed5b0c9f17289d3354df327f2a8b803ab1f667b0 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/OneEditTextActivityNotSelectedTests.java @@ -0,0 +1,50 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.View; + + +public class OneEditTextActivityNotSelectedTests extends ImfBaseTestCase { + + public final String TAG = "OneEditTextActivityNotSelectedTests"; + + public OneEditTextActivityNotSelectedTests() { + super(OneEditTextActivityNotSelected.class); + } + + @LargeTest + public void testSoftKeyboardNoAutoPop() { + + // Give the IME 2 seconds to appear. + pause(2000); + + assertFalse(mImm.isAcceptingText()); + + View rootView = ((OneEditTextActivityNotSelected) mTargetActivity).getRootView(); + View servedView = ((OneEditTextActivityNotSelected) mTargetActivity).getDefaultFocusedView(); + + assertNotNull(rootView); + assertNotNull(servedView); + + destructiveCheckImeInitialState(rootView, servedView); + + verifyEditTextAdjustment(servedView, rootView.getMeasuredHeight()); + } + +} diff --git a/tests/ImfTest/tests/src/com/android/imftest/samples/OneEditTextActivitySelectedTests.java b/tests/ImfTest/tests/src/com/android/imftest/samples/OneEditTextActivitySelectedTests.java new file mode 100755 index 0000000000000000000000000000000000000000..42fcd66f792276ccb4d79c46c2fe7aa8e12b4203 --- /dev/null +++ b/tests/ImfTest/tests/src/com/android/imftest/samples/OneEditTextActivitySelectedTests.java @@ -0,0 +1,53 @@ +/* + * 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. + */ + +package com.android.imftest.samples; + +import com.android.imftest.R; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.KeyEvent; +import android.view.View; + + +public class OneEditTextActivitySelectedTests extends ImfBaseTestCase { + + public final String TAG = "OneEditTextActivitySelectedTests"; + + public OneEditTextActivitySelectedTests() { + super(OneEditTextActivitySelected.class); + } + + @LargeTest + public void testSoftKeyboardAutoPop() { + + // Give the IME 2 seconds to appear. + pause(2000); + + assertTrue(mImm.isAcceptingText()); + + View rootView = ((OneEditTextActivitySelected) mTargetActivity).getRootView(); + View servedView = ((OneEditTextActivitySelected) mTargetActivity).getDefaultFocusedView(); + + assertNotNull(rootView); + assertNotNull(servedView); + + destructiveCheckImeInitialState(rootView, servedView); + + verifyEditTextAdjustment(servedView, rootView.getMeasuredHeight()); + } + +} diff --git a/tests/SmokeTest/tests/AndroidManifest.xml b/tests/SmokeTest/tests/AndroidManifest.xml index 20b33ee063e77f45bea3641e0a73d3678bcdfd02..517eb1ea9cb444060db7dd0a45f924856b27fa56 100644 --- a/tests/SmokeTest/tests/AndroidManifest.xml +++ b/tests/SmokeTest/tests/AndroidManifest.xml @@ -25,8 +25,6 @@ - - + + + + + + + + + + diff --git a/tests/appwidgets/AppWidgetHostTest/res/drawable/oh_hai_icon.png b/tests/appwidgets/AppWidgetHostTest/res/drawable/oh_hai_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..30ff2671a2f6d50c2742b8b099e315397deb2f1f Binary files /dev/null and b/tests/appwidgets/AppWidgetHostTest/res/drawable/oh_hai_icon.png differ diff --git a/tests/GadgetHost/res/layout/gadget_host.xml b/tests/appwidgets/AppWidgetHostTest/res/layout/appwidget_host.xml similarity index 82% rename from tests/GadgetHost/res/layout/gadget_host.xml rename to tests/appwidgets/AppWidgetHostTest/res/layout/appwidget_host.xml index 824cc44ed7e2749719bc05511dfb56c03d006909..e5c3b288f4fa059b90bf6ec52481469fad7e672f 100644 --- a/tests/GadgetHost/res/layout/gadget_host.xml +++ b/tests/appwidgets/AppWidgetHostTest/res/layout/appwidget_host.xml @@ -22,7 +22,7 @@ -