PointerController.cpp revision 9626b14a283ef82d16636cf5fb5ba8bb4d30381e
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "PointerController"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages about pointer updates
22#define DEBUG_POINTER_UPDATES 0
23
24#include "PointerController.h"
25
26#include <cutils/log.h>
27
28#include <SkBitmap.h>
29#include <SkCanvas.h>
30#include <SkColor.h>
31#include <SkPaint.h>
32#include <SkXfermode.h>
33
34namespace android {
35
36// --- PointerController ---
37
38// Time to wait before starting the fade when the pointer is inactive.
39static const nsecs_t INACTIVITY_FADE_DELAY_TIME_NORMAL = 15 * 1000 * 1000000LL; // 15 seconds
40static const nsecs_t INACTIVITY_FADE_DELAY_TIME_SHORT = 3 * 1000 * 1000000LL; // 3 seconds
41
42// Time to spend fading out the pointer completely.
43static const nsecs_t FADE_DURATION = 500 * 1000000LL; // 500 ms
44
45// Time to wait between frames.
46static const nsecs_t FADE_FRAME_INTERVAL = 1000000000LL / 60;
47
48// Amount to subtract from alpha per frame.
49static const float FADE_DECAY_PER_FRAME = float(FADE_FRAME_INTERVAL) / FADE_DURATION;
50
51
52PointerController::PointerController(const sp<Looper>& looper, int32_t pointerLayer) :
53        mLooper(looper), mPointerLayer(pointerLayer) {
54    AutoMutex _l(mLock);
55
56    mLocked.displayWidth = -1;
57    mLocked.displayHeight = -1;
58    mLocked.displayOrientation = DISPLAY_ORIENTATION_0;
59
60    mLocked.pointerX = 0;
61    mLocked.pointerY = 0;
62    mLocked.buttonState = 0;
63
64    mLocked.iconBitmap = NULL;
65    mLocked.iconHotSpotX = 0;
66    mLocked.iconHotSpotY = 0;
67
68    mLocked.fadeAlpha = 1;
69    mLocked.inactivityFadeDelay = INACTIVITY_FADE_DELAY_NORMAL;
70
71    mLocked.wantVisible = false;
72    mLocked.visible = false;
73    mLocked.drawn = false;
74
75    mHandler = new WeakMessageHandler(this);
76}
77
78PointerController::~PointerController() {
79    mLooper->removeMessages(mHandler);
80
81    if (mSurfaceControl != NULL) {
82        mSurfaceControl->clear();
83        mSurfaceControl.clear();
84    }
85
86    if (mSurfaceComposerClient != NULL) {
87        mSurfaceComposerClient->dispose();
88        mSurfaceComposerClient.clear();
89    }
90
91    delete mLocked.iconBitmap;
92}
93
94bool PointerController::getBounds(float* outMinX, float* outMinY,
95        float* outMaxX, float* outMaxY) const {
96    AutoMutex _l(mLock);
97
98    return getBoundsLocked(outMinX, outMinY, outMaxX, outMaxY);
99}
100
101bool PointerController::getBoundsLocked(float* outMinX, float* outMinY,
102        float* outMaxX, float* outMaxY) const {
103    if (mLocked.displayWidth <= 0 || mLocked.displayHeight <= 0) {
104        return false;
105    }
106
107    *outMinX = 0;
108    *outMinY = 0;
109    switch (mLocked.displayOrientation) {
110    case DISPLAY_ORIENTATION_90:
111    case DISPLAY_ORIENTATION_270:
112        *outMaxX = mLocked.displayHeight - 1;
113        *outMaxY = mLocked.displayWidth - 1;
114        break;
115    default:
116        *outMaxX = mLocked.displayWidth - 1;
117        *outMaxY = mLocked.displayHeight - 1;
118        break;
119    }
120    return true;
121}
122
123void PointerController::move(float deltaX, float deltaY) {
124#if DEBUG_POINTER_UPDATES
125    LOGD("Move pointer by deltaX=%0.3f, deltaY=%0.3f", deltaX, deltaY);
126#endif
127    if (deltaX == 0.0f && deltaY == 0.0f) {
128        return;
129    }
130
131    AutoMutex _l(mLock);
132
133    setPositionLocked(mLocked.pointerX + deltaX, mLocked.pointerY + deltaY);
134}
135
136void PointerController::setButtonState(uint32_t buttonState) {
137#if DEBUG_POINTER_UPDATES
138    LOGD("Set button state 0x%08x", buttonState);
139#endif
140    AutoMutex _l(mLock);
141
142    if (mLocked.buttonState != buttonState) {
143        mLocked.buttonState = buttonState;
144        unfadeBeforeUpdateLocked();
145        updateLocked();
146    }
147}
148
149uint32_t PointerController::getButtonState() const {
150    AutoMutex _l(mLock);
151
152    return mLocked.buttonState;
153}
154
155void PointerController::setPosition(float x, float y) {
156#if DEBUG_POINTER_UPDATES
157    LOGD("Set pointer position to x=%0.3f, y=%0.3f", x, y);
158#endif
159    AutoMutex _l(mLock);
160
161    setPositionLocked(x, y);
162}
163
164void PointerController::setPositionLocked(float x, float y) {
165    float minX, minY, maxX, maxY;
166    if (getBoundsLocked(&minX, &minY, &maxX, &maxY)) {
167        if (x <= minX) {
168            mLocked.pointerX = minX;
169        } else if (x >= maxX) {
170            mLocked.pointerX = maxX;
171        } else {
172            mLocked.pointerX = x;
173        }
174        if (y <= minY) {
175            mLocked.pointerY = minY;
176        } else if (y >= maxY) {
177            mLocked.pointerY = maxY;
178        } else {
179            mLocked.pointerY = y;
180        }
181        unfadeBeforeUpdateLocked();
182        updateLocked();
183    }
184}
185
186void PointerController::getPosition(float* outX, float* outY) const {
187    AutoMutex _l(mLock);
188
189    *outX = mLocked.pointerX;
190    *outY = mLocked.pointerY;
191}
192
193void PointerController::fade() {
194    AutoMutex _l(mLock);
195
196    startFadeLocked();
197}
198
199void PointerController::unfade() {
200    AutoMutex _l(mLock);
201
202    if (unfadeBeforeUpdateLocked()) {
203        updateLocked();
204    }
205}
206
207void PointerController::setInactivityFadeDelay(InactivityFadeDelay inactivityFadeDelay) {
208    AutoMutex _l(mLock);
209
210    if (mLocked.inactivityFadeDelay != inactivityFadeDelay) {
211        mLocked.inactivityFadeDelay = inactivityFadeDelay;
212        startInactivityFadeDelayLocked();
213    }
214}
215
216void PointerController::updateLocked() {
217    bool wantVisibleAndHavePointerIcon = mLocked.wantVisible && mLocked.iconBitmap;
218
219    if (wantVisibleAndHavePointerIcon) {
220        // Want the pointer to be visible.
221        // Ensure the surface is created and drawn.
222        if (!createSurfaceIfNeededLocked() || !drawPointerIfNeededLocked()) {
223            return;
224        }
225    } else {
226        // Don't want the pointer to be visible.
227        // If it is not visible then we are done.
228        if (mSurfaceControl == NULL || !mLocked.visible) {
229            return;
230        }
231    }
232
233    status_t status = mSurfaceComposerClient->openTransaction();
234    if (status) {
235        LOGE("Error opening surface transaction to update pointer surface.");
236        return;
237    }
238
239    if (wantVisibleAndHavePointerIcon) {
240        status = mSurfaceControl->setPosition(
241                mLocked.pointerX - mLocked.iconHotSpotX,
242                mLocked.pointerY - mLocked.iconHotSpotY);
243        if (status) {
244            LOGE("Error %d moving pointer surface.", status);
245            goto CloseTransaction;
246        }
247
248        status = mSurfaceControl->setAlpha(mLocked.fadeAlpha);
249        if (status) {
250            LOGE("Error %d setting pointer surface alpha.", status);
251            goto CloseTransaction;
252        }
253
254        if (!mLocked.visible) {
255            status = mSurfaceControl->setLayer(mPointerLayer);
256            if (status) {
257                LOGE("Error %d setting pointer surface layer.", status);
258                goto CloseTransaction;
259            }
260
261            status = mSurfaceControl->show(mPointerLayer);
262            if (status) {
263                LOGE("Error %d showing pointer surface.", status);
264                goto CloseTransaction;
265            }
266
267            mLocked.visible = true;
268        }
269    } else {
270        if (mLocked.visible) {
271            status = mSurfaceControl->hide();
272            if (status) {
273                LOGE("Error %d hiding pointer surface.", status);
274                goto CloseTransaction;
275            }
276
277            mLocked.visible = false;
278        }
279    }
280
281CloseTransaction:
282    status = mSurfaceComposerClient->closeTransaction();
283    if (status) {
284        LOGE("Error closing surface transaction to update pointer surface.");
285    }
286}
287
288void PointerController::setDisplaySize(int32_t width, int32_t height) {
289    AutoMutex _l(mLock);
290
291    if (mLocked.displayWidth != width || mLocked.displayHeight != height) {
292        mLocked.displayWidth = width;
293        mLocked.displayHeight = height;
294
295        float minX, minY, maxX, maxY;
296        if (getBoundsLocked(&minX, &minY, &maxX, &maxY)) {
297            mLocked.pointerX = (minX + maxX) * 0.5f;
298            mLocked.pointerY = (minY + maxY) * 0.5f;
299        } else {
300            mLocked.pointerX = 0;
301            mLocked.pointerY = 0;
302        }
303
304        updateLocked();
305    }
306}
307
308void PointerController::setDisplayOrientation(int32_t orientation) {
309    AutoMutex _l(mLock);
310
311    if (mLocked.displayOrientation != orientation) {
312        // Apply offsets to convert from the pixel top-left corner position to the pixel center.
313        // This creates an invariant frame of reference that we can easily rotate when
314        // taking into account that the pointer may be located at fractional pixel offsets.
315        float x = mLocked.pointerX + 0.5f;
316        float y = mLocked.pointerY + 0.5f;
317        float temp;
318
319        // Undo the previous rotation.
320        switch (mLocked.displayOrientation) {
321        case DISPLAY_ORIENTATION_90:
322            temp = x;
323            x = mLocked.displayWidth - y;
324            y = temp;
325            break;
326        case DISPLAY_ORIENTATION_180:
327            x = mLocked.displayWidth - x;
328            y = mLocked.displayHeight - y;
329            break;
330        case DISPLAY_ORIENTATION_270:
331            temp = x;
332            x = y;
333            y = mLocked.displayHeight - temp;
334            break;
335        }
336
337        // Perform the new rotation.
338        switch (orientation) {
339        case DISPLAY_ORIENTATION_90:
340            temp = x;
341            x = y;
342            y = mLocked.displayWidth - x;
343            break;
344        case DISPLAY_ORIENTATION_180:
345            x = mLocked.displayWidth - x;
346            y = mLocked.displayHeight - y;
347            break;
348        case DISPLAY_ORIENTATION_270:
349            temp = x;
350            x = mLocked.displayHeight - y;
351            y = temp;
352            break;
353        }
354
355        // Apply offsets to convert from the pixel center to the pixel top-left corner position
356        // and save the results.
357        mLocked.pointerX = x - 0.5f;
358        mLocked.pointerY = y - 0.5f;
359        mLocked.displayOrientation = orientation;
360
361        updateLocked();
362    }
363}
364
365void PointerController::setPointerIcon(const SkBitmap* bitmap, float hotSpotX, float hotSpotY) {
366    AutoMutex _l(mLock);
367
368    if (mLocked.iconBitmap) {
369        delete mLocked.iconBitmap;
370        mLocked.iconBitmap = NULL;
371    }
372
373    if (bitmap) {
374        mLocked.iconBitmap = new SkBitmap();
375        bitmap->copyTo(mLocked.iconBitmap, SkBitmap::kARGB_8888_Config);
376    }
377
378    mLocked.iconHotSpotX = hotSpotX;
379    mLocked.iconHotSpotY = hotSpotY;
380    mLocked.drawn = false;
381}
382
383bool PointerController::createSurfaceIfNeededLocked() {
384    if (!mLocked.iconBitmap) {
385        // If we don't have a pointer icon, then no point allocating a surface now.
386        return false;
387    }
388
389    if (mSurfaceComposerClient == NULL) {
390        mSurfaceComposerClient = new SurfaceComposerClient();
391    }
392
393    if (mSurfaceControl == NULL) {
394        mSurfaceControl = mSurfaceComposerClient->createSurface(getpid(),
395                String8("Pointer Icon"), 0,
396                mLocked.iconBitmap->width(), mLocked.iconBitmap->height(),
397                PIXEL_FORMAT_RGBA_8888);
398        if (mSurfaceControl == NULL) {
399            LOGE("Error creating pointer surface.");
400            return false;
401        }
402    }
403    return true;
404}
405
406bool PointerController::drawPointerIfNeededLocked() {
407    if (!mLocked.drawn) {
408        if (!mLocked.iconBitmap) {
409            return false;
410        }
411
412        if (!resizeSurfaceLocked(mLocked.iconBitmap->width(), mLocked.iconBitmap->height())) {
413            return false;
414        }
415
416        sp<Surface> surface = mSurfaceControl->getSurface();
417
418        Surface::SurfaceInfo surfaceInfo;
419        status_t status = surface->lock(&surfaceInfo);
420        if (status) {
421            LOGE("Error %d locking pointer surface before drawing.", status);
422            return false;
423        }
424
425        SkBitmap surfaceBitmap;
426        ssize_t bpr = surfaceInfo.s * bytesPerPixel(surfaceInfo.format);
427        surfaceBitmap.setConfig(SkBitmap::kARGB_8888_Config, surfaceInfo.w, surfaceInfo.h, bpr);
428        surfaceBitmap.setPixels(surfaceInfo.bits);
429
430        SkCanvas surfaceCanvas;
431        surfaceCanvas.setBitmapDevice(surfaceBitmap);
432
433        SkPaint paint;
434        paint.setXfermodeMode(SkXfermode::kSrc_Mode);
435        surfaceCanvas.drawBitmap(*mLocked.iconBitmap, 0, 0, &paint);
436
437        status = surface->unlockAndPost();
438        if (status) {
439            LOGE("Error %d unlocking pointer surface after drawing.", status);
440            return false;
441        }
442    }
443
444    mLocked.drawn = true;
445    return true;
446}
447
448bool PointerController::resizeSurfaceLocked(int32_t width, int32_t height) {
449    status_t status = mSurfaceComposerClient->openTransaction();
450    if (status) {
451        LOGE("Error opening surface transaction to resize pointer surface.");
452        return false;
453    }
454
455    status = mSurfaceControl->setSize(width, height);
456    if (status) {
457        LOGE("Error %d setting pointer surface size.", status);
458        return false;
459    }
460
461    status = mSurfaceComposerClient->closeTransaction();
462    if (status) {
463        LOGE("Error closing surface transaction to resize pointer surface.");
464        return false;
465    }
466
467    return true;
468}
469
470void PointerController::handleMessage(const Message& message) {
471    switch (message.what) {
472    case MSG_FADE_STEP: {
473        AutoMutex _l(mLock);
474        fadeStepLocked();
475        break;
476    }
477    }
478}
479
480bool PointerController::unfadeBeforeUpdateLocked() {
481    sendFadeStepMessageDelayedLocked(getInactivityFadeDelayTimeLocked());
482
483    if (isFadingLocked()) {
484        mLocked.wantVisible = true;
485        mLocked.fadeAlpha = 1;
486        return true; // update required to effect the unfade
487    }
488    return false; // update not required
489}
490
491void PointerController::startFadeLocked() {
492    if (!isFadingLocked()) {
493        sendFadeStepMessageDelayedLocked(0);
494    }
495}
496
497void PointerController::startInactivityFadeDelayLocked() {
498    if (!isFadingLocked()) {
499        sendFadeStepMessageDelayedLocked(getInactivityFadeDelayTimeLocked());
500    }
501}
502
503void PointerController::fadeStepLocked() {
504    if (mLocked.wantVisible) {
505        mLocked.fadeAlpha -= FADE_DECAY_PER_FRAME;
506        if (mLocked.fadeAlpha < 0) {
507            mLocked.fadeAlpha = 0;
508            mLocked.wantVisible = false;
509        } else {
510            sendFadeStepMessageDelayedLocked(FADE_FRAME_INTERVAL);
511        }
512        updateLocked();
513    }
514}
515
516bool PointerController::isFadingLocked() {
517    return !mLocked.wantVisible || mLocked.fadeAlpha != 1;
518}
519
520nsecs_t PointerController::getInactivityFadeDelayTimeLocked() {
521    return mLocked.inactivityFadeDelay == INACTIVITY_FADE_DELAY_SHORT
522            ? INACTIVITY_FADE_DELAY_TIME_SHORT : INACTIVITY_FADE_DELAY_TIME_NORMAL;
523}
524
525void PointerController::sendFadeStepMessageDelayedLocked(nsecs_t delayTime) {
526    mLooper->removeMessages(mHandler, MSG_FADE_STEP);
527    mLooper->sendMessageDelayed(delayTime, mHandler, Message(MSG_FADE_STEP));
528}
529
530} // namespace android
531