ScreenMagnifier.java revision ee44fae19664594d4a17dd86723106533f4b218a
1/*
2 * Copyright (C) 2012 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
17package com.android.server.accessibility;
18
19import android.animation.Animator;
20import android.animation.Animator.AnimatorListener;
21import android.animation.ObjectAnimator;
22import android.animation.TypeEvaluator;
23import android.animation.ValueAnimator;
24import android.content.BroadcastReceiver;
25import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.graphics.Canvas;
29import android.graphics.Color;
30import android.graphics.PixelFormat;
31import android.graphics.PorterDuff.Mode;
32import android.graphics.Rect;
33import android.graphics.drawable.Drawable;
34import android.hardware.display.DisplayManager;
35import android.hardware.display.DisplayManager.DisplayListener;
36import android.os.AsyncTask;
37import android.os.Handler;
38import android.os.Message;
39import android.os.RemoteException;
40import android.os.ServiceManager;
41import android.provider.Settings;
42import android.util.Property;
43import android.util.Slog;
44import android.view.Display;
45import android.view.DisplayInfo;
46import android.view.GestureDetector;
47import android.view.GestureDetector.SimpleOnGestureListener;
48import android.view.Gravity;
49import android.view.IDisplayContentChangeListener;
50import android.view.IWindowManager;
51import android.view.MotionEvent;
52import android.view.MotionEvent.PointerCoords;
53import android.view.MotionEvent.PointerProperties;
54import android.view.ScaleGestureDetector;
55import android.view.ScaleGestureDetector.OnScaleGestureListener;
56import android.view.Surface;
57import android.view.View;
58import android.view.ViewConfiguration;
59import android.view.ViewGroup;
60import android.view.WindowInfo;
61import android.view.WindowManager;
62import android.view.WindowManagerPolicy;
63import android.view.accessibility.AccessibilityEvent;
64import android.view.animation.DecelerateInterpolator;
65import android.view.animation.Interpolator;
66
67import com.android.internal.R;
68import com.android.internal.os.SomeArgs;
69
70import java.util.ArrayList;
71import java.util.Collections;
72import java.util.Comparator;
73
74/**
75 * This class handles the screen magnification when accessibility is enabled.
76 * The behavior is as follows:
77 *
78 * 1. Triple tap toggles permanent screen magnification which is magnifying
79 *    the area around the location of the triple tap. One can think of the
80 *    location of the triple tap as the center of the magnified viewport.
81 *    For example, a triple tap when not magnified would magnify the screen
82 *    and leave it in a magnified state. A triple tapping when magnified would
83 *    clear magnification and leave the screen in a not magnified state.
84 *
85 * 2. Triple tap and hold would magnify the screen if not magnified and enable
86 *    viewport dragging mode until the finger goes up. One can think of this
87 *    mode as a way to move the magnified viewport since the area around the
88 *    moving finger will be magnified to fit the screen. For example, if the
89 *    screen was not magnified and the user triple taps and holds the screen
90 *    would magnify and the viewport will follow the user's finger. When the
91 *    finger goes up the screen will clear zoom out. If the same user interaction
92 *    is performed when the screen is magnified, the viewport movement will
93 *    be the same but when the finger goes up the screen will stay magnified.
94 *    In other words, the initial magnified state is sticky.
95 *
96 * 3. Pinching with any number of additional fingers when viewport dragging
97 *    is enabled, i.e. the user triple tapped and holds, would adjust the
98 *    magnification scale which will become the current default magnification
99 *    scale. The next time the user magnifies the same magnification scale
100 *    would be used.
101 *
102 * 4. When in a permanent magnified state the user can use two or more fingers
103 *    to pan the viewport. Note that in this mode the content is panned as
104 *    opposed to the viewport dragging mode in which the viewport is moved.
105 *
106 * 5. When in a permanent magnified state the user can use three or more
107 *    fingers to change the magnification scale which will become the current
108 *    default magnification scale. The next time the user magnifies the same
109 *    magnification scale would be used.
110 *
111 * 6. The magnification scale will be persisted in settings and in the cloud.
112 */
113public final class ScreenMagnifier implements EventStreamTransformation {
114
115    private static final boolean DEBUG_STATE_TRANSITIONS = false;
116    private static final boolean DEBUG_DETECTING = false;
117    private static final boolean DEBUG_TRANSFORMATION = false;
118    private static final boolean DEBUG_PANNING = false;
119    private static final boolean DEBUG_SCALING = false;
120    private static final boolean DEBUG_VIEWPORT_WINDOW = false;
121    private static final boolean DEBUG_WINDOW_TRANSITIONS = false;
122    private static final boolean DEBUG_ROTATION = false;
123    private static final boolean DEBUG_MAGNIFICATION_CONTROLLER = false;
124
125    private static final String LOG_TAG = ScreenMagnifier.class.getSimpleName();
126
127    private static final int STATE_DELEGATING = 1;
128    private static final int STATE_DETECTING = 2;
129    private static final int STATE_VIEWPORT_DRAGGING = 3;
130    private static final int STATE_MAGNIFIED_INTERACTION = 4;
131
132    private static final float DEFAULT_MAGNIFICATION_SCALE = 2.0f;
133    private static final int DEFAULT_SCREEN_MAGNIFICATION_AUTO_UPDATE = 1;
134    private static final float DEFAULT_WINDOW_ANIMATION_SCALE = 1.0f;
135
136    private static final int MULTI_TAP_TIME_SLOP_ADJUSTMENT = 50;
137
138    private final IWindowManager mWindowManagerService = IWindowManager.Stub.asInterface(
139            ServiceManager.getService("window"));
140    private final WindowManager mWindowManager;
141    private final DisplayProvider mDisplayProvider;
142
143    private final DetectingStateHandler mDetectingStateHandler = new DetectingStateHandler();
144    private final MagnifiedContentInteractonStateHandler mMagnifiedContentInteractonStateHandler;
145    private final StateViewportDraggingHandler mStateViewportDraggingHandler =
146            new StateViewportDraggingHandler();
147
148    private final Interpolator mInterpolator = new DecelerateInterpolator(2.5f);
149
150    private final MagnificationController mMagnificationController;
151    private final DisplayContentObserver mDisplayContentObserver;
152    private final ScreenStateObserver mScreenStateObserver;
153    private final Viewport mViewport;
154
155    private final int mTapTimeSlop = ViewConfiguration.getTapTimeout();
156    private final int mMultiTapTimeSlop =
157            ViewConfiguration.getDoubleTapTimeout() - MULTI_TAP_TIME_SLOP_ADJUSTMENT;
158    private final int mTapDistanceSlop;
159    private final int mMultiTapDistanceSlop;
160
161    private final int mShortAnimationDuration;
162    private final int mLongAnimationDuration;
163    private final float mWindowAnimationScale;
164
165    private final Context mContext;
166
167    private EventStreamTransformation mNext;
168
169    private int mCurrentState;
170    private int mPreviousState;
171    private boolean mTranslationEnabledBeforePan;
172
173    private PointerCoords[] mTempPointerCoords;
174    private PointerProperties[] mTempPointerProperties;
175
176    public ScreenMagnifier(Context context) {
177        mContext = context;
178        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
179
180        mShortAnimationDuration = context.getResources().getInteger(
181                com.android.internal.R.integer.config_shortAnimTime);
182        mLongAnimationDuration = context.getResources().getInteger(
183                com.android.internal.R.integer.config_longAnimTime);
184        mTapDistanceSlop = ViewConfiguration.get(context).getScaledTouchSlop();
185        mMultiTapDistanceSlop = ViewConfiguration.get(context).getScaledDoubleTapSlop();
186        mWindowAnimationScale = Settings.Global.getFloat(context.getContentResolver(),
187                Settings.Global.WINDOW_ANIMATION_SCALE, DEFAULT_WINDOW_ANIMATION_SCALE);
188
189        mMagnificationController = new MagnificationController(mShortAnimationDuration);
190        mDisplayProvider = new DisplayProvider(context, mWindowManager);
191        mViewport = new Viewport(mContext, mWindowManager, mWindowManagerService,
192                mDisplayProvider, mInterpolator, mShortAnimationDuration);
193        mDisplayContentObserver = new DisplayContentObserver(mContext, mViewport,
194                mMagnificationController, mWindowManagerService, mDisplayProvider,
195                mLongAnimationDuration, mWindowAnimationScale);
196        mScreenStateObserver = new ScreenStateObserver(mContext, mViewport,
197                mMagnificationController);
198
199        mMagnifiedContentInteractonStateHandler = new MagnifiedContentInteractonStateHandler(
200                context);
201
202        transitionToState(STATE_DETECTING);
203    }
204
205    @Override
206    public void onMotionEvent(MotionEvent event, MotionEvent rawEvent,
207            int policyFlags) {
208        mMagnifiedContentInteractonStateHandler.onMotionEvent(event);
209        switch (mCurrentState) {
210            case STATE_DELEGATING: {
211                handleMotionEventStateDelegating(event, rawEvent, policyFlags);
212            } break;
213            case STATE_DETECTING: {
214                mDetectingStateHandler.onMotionEvent(event, rawEvent, policyFlags);
215            } break;
216            case STATE_VIEWPORT_DRAGGING: {
217                mStateViewportDraggingHandler.onMotionEvent(event, policyFlags);
218            } break;
219            case STATE_MAGNIFIED_INTERACTION: {
220                // mMagnifiedContentInteractonStateHandler handles events only
221                // if this is the current state since it uses ScaleGestureDetecotr
222                // and a GestureDetector which need well formed event stream.
223            } break;
224            default: {
225                throw new IllegalStateException("Unknown state: " + mCurrentState);
226            }
227        }
228    }
229
230    @Override
231    public void onAccessibilityEvent(AccessibilityEvent event) {
232        if (mNext != null) {
233            mNext.onAccessibilityEvent(event);
234        }
235    }
236
237    @Override
238    public void setNext(EventStreamTransformation next) {
239        mNext = next;
240    }
241
242    @Override
243    public void clear() {
244        mCurrentState = STATE_DETECTING;
245        mDetectingStateHandler.clear();
246        mStateViewportDraggingHandler.clear();
247        mMagnifiedContentInteractonStateHandler.clear();
248        if (mNext != null) {
249            mNext.clear();
250        }
251    }
252
253    @Override
254    public void onDestroy() {
255        mMagnificationController.setScaleAndMagnifiedRegionCenter(1.0f,
256                0, 0, true);
257        mViewport.setFrameShown(false, true);
258        mDisplayProvider.destroy();
259        mDisplayContentObserver.destroy();
260        mScreenStateObserver.destroy();
261    }
262
263    private void handleMotionEventStateDelegating(MotionEvent event,
264            MotionEvent rawEvent, int policyFlags) {
265        if (event.getActionMasked() == MotionEvent.ACTION_UP) {
266            if (mDetectingStateHandler.mDelayedEventQueue == null) {
267                transitionToState(STATE_DETECTING);
268            }
269        }
270        if (mNext != null) {
271            // If the event is within the magnified portion of the screen we have
272            // to change its location to be where the user thinks he is poking the
273            // UI which may have been magnified and panned.
274            final float eventX = event.getX();
275            final float eventY = event.getY();
276            if (mMagnificationController.isMagnifying()
277                    && mViewport.getBounds().contains((int) eventX, (int) eventY)) {
278                final float scale = mMagnificationController.getScale();
279                final float scaledOffsetX = mMagnificationController.getScaledOffsetX();
280                final float scaledOffsetY = mMagnificationController.getScaledOffsetY();
281                final int pointerCount = event.getPointerCount();
282                PointerCoords[] coords = getTempPointerCoordsWithMinSize(pointerCount);
283                PointerProperties[] properties = getTempPointerPropertiesWithMinSize(pointerCount);
284                for (int i = 0; i < pointerCount; i++) {
285                    event.getPointerCoords(i, coords[i]);
286                    coords[i].x = (coords[i].x - scaledOffsetX) / scale;
287                    coords[i].y = (coords[i].y - scaledOffsetY) / scale;
288                    event.getPointerProperties(i, properties[i]);
289                }
290                event = MotionEvent.obtain(event.getDownTime(),
291                        event.getEventTime(), event.getAction(), pointerCount, properties,
292                        coords, 0, 0, 1.0f, 1.0f, event.getDeviceId(), 0, event.getSource(),
293                        event.getFlags());
294            }
295            mNext.onMotionEvent(event, rawEvent, policyFlags);
296        }
297    }
298
299    private PointerCoords[] getTempPointerCoordsWithMinSize(int size) {
300        final int oldSize = (mTempPointerCoords != null) ? mTempPointerCoords.length : 0;
301        if (oldSize < size) {
302            PointerCoords[] oldTempPointerCoords = mTempPointerCoords;
303            mTempPointerCoords = new PointerCoords[size];
304            if (oldTempPointerCoords != null) {
305                System.arraycopy(oldTempPointerCoords, 0, mTempPointerCoords, 0, oldSize);
306            }
307        }
308        for (int i = oldSize; i < size; i++) {
309            mTempPointerCoords[i] = new PointerCoords();
310        }
311        return mTempPointerCoords;
312    }
313
314    private PointerProperties[] getTempPointerPropertiesWithMinSize(int size) {
315        final int oldSize = (mTempPointerProperties != null) ? mTempPointerProperties.length : 0;
316        if (oldSize < size) {
317            PointerProperties[] oldTempPointerProperties = mTempPointerProperties;
318            mTempPointerProperties = new PointerProperties[size];
319            if (oldTempPointerProperties != null) {
320                System.arraycopy(oldTempPointerProperties, 0, mTempPointerProperties, 0, oldSize);
321            }
322        }
323        for (int i = oldSize; i < size; i++) {
324            mTempPointerProperties[i] = new PointerProperties();
325        }
326        return mTempPointerProperties;
327    }
328
329    private void transitionToState(int state) {
330        if (DEBUG_STATE_TRANSITIONS) {
331            switch (state) {
332                case STATE_DELEGATING: {
333                    Slog.i(LOG_TAG, "mCurrentState: STATE_DELEGATING");
334                } break;
335                case STATE_DETECTING: {
336                    Slog.i(LOG_TAG, "mCurrentState: STATE_DETECTING");
337                } break;
338                case STATE_VIEWPORT_DRAGGING: {
339                    Slog.i(LOG_TAG, "mCurrentState: STATE_VIEWPORT_DRAGGING");
340                } break;
341                case STATE_MAGNIFIED_INTERACTION: {
342                    Slog.i(LOG_TAG, "mCurrentState: STATE_MAGNIFIED_INTERACTION");
343                } break;
344                default: {
345                    throw new IllegalArgumentException("Unknown state: " + state);
346                }
347            }
348        }
349        mPreviousState = mCurrentState;
350        mCurrentState = state;
351    }
352
353    private final class MagnifiedContentInteractonStateHandler
354            extends SimpleOnGestureListener implements OnScaleGestureListener {
355        private static final float MIN_SCALE = 1.3f;
356        private static final float MAX_SCALE = 5.0f;
357
358        private static final float SCALING_THRESHOLD = 0.3f;
359
360        private final ScaleGestureDetector mScaleGestureDetector;
361        private final GestureDetector mGestureDetector;
362
363        private float mInitialScaleFactor = -1;
364        private boolean mScaling;
365
366        public MagnifiedContentInteractonStateHandler(Context context) {
367            mScaleGestureDetector = new ScaleGestureDetector(context, this);
368            mGestureDetector = new GestureDetector(context, this);
369        }
370
371        public void onMotionEvent(MotionEvent event) {
372            mScaleGestureDetector.onTouchEvent(event);
373            mGestureDetector.onTouchEvent(event);
374            if (mCurrentState != STATE_MAGNIFIED_INTERACTION) {
375                return;
376            }
377            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
378                clear();
379                final float scale = Math.min(Math.max(mMagnificationController.getScale(),
380                        MIN_SCALE), MAX_SCALE);
381                if (scale != getPersistedScale()) {
382                    persistScale(scale);
383                }
384                if (mPreviousState == STATE_VIEWPORT_DRAGGING) {
385                    transitionToState(STATE_VIEWPORT_DRAGGING);
386                } else {
387                    transitionToState(STATE_DETECTING);
388                }
389            }
390        }
391
392        @Override
393        public boolean onScroll(MotionEvent first, MotionEvent second, float distanceX,
394                float distanceY) {
395            if (mCurrentState != STATE_MAGNIFIED_INTERACTION) {
396                return true;
397            }
398            final float scale = mMagnificationController.getScale();
399            final float scrollX = distanceX / scale;
400            final float scrollY = distanceY / scale;
401            final float centerX = mMagnificationController.getMagnifiedRegionCenterX() + scrollX;
402            final float centerY = mMagnificationController.getMagnifiedRegionCenterY() + scrollY;
403            if (DEBUG_PANNING) {
404                Slog.i(LOG_TAG, "Panned content by scrollX: " + scrollX
405                        + " scrollY: " + scrollY);
406            }
407            mMagnificationController.setMagnifiedRegionCenter(centerX, centerY, false);
408            return true;
409        }
410
411        @Override
412        public boolean onScale(ScaleGestureDetector detector) {
413            if (!mScaling) {
414                if (mInitialScaleFactor < 0) {
415                    mInitialScaleFactor = detector.getScaleFactor();
416                } else {
417                    final float deltaScale = detector.getScaleFactor() - mInitialScaleFactor;
418                    if (Math.abs(deltaScale) > SCALING_THRESHOLD) {
419                        mScaling = true;
420                        return true;
421                    }
422                }
423                return false;
424            }
425            final float newScale = mMagnificationController.getScale()
426                    * detector.getScaleFactor();
427            final float normalizedNewScale = Math.min(Math.max(newScale, MIN_SCALE), MAX_SCALE);
428            if (DEBUG_SCALING) {
429                Slog.i(LOG_TAG, "normalizedNewScale: " + normalizedNewScale);
430            }
431            mMagnificationController.setScale(normalizedNewScale, detector.getFocusX(),
432                    detector.getFocusY(), false);
433            return true;
434        }
435
436        @Override
437        public boolean onScaleBegin(ScaleGestureDetector detector) {
438            return (mCurrentState == STATE_MAGNIFIED_INTERACTION);
439        }
440
441        @Override
442        public void onScaleEnd(ScaleGestureDetector detector) {
443            clear();
444        }
445
446        private void clear() {
447            mInitialScaleFactor = -1;
448            mScaling = false;
449        }
450    }
451
452    private final class StateViewportDraggingHandler {
453        private boolean mLastMoveOutsideMagnifiedRegion;
454
455        private void onMotionEvent(MotionEvent event, int policyFlags) {
456            final int action = event.getActionMasked();
457            switch (action) {
458                case MotionEvent.ACTION_DOWN: {
459                    throw new IllegalArgumentException("Unexpected event type: ACTION_DOWN");
460                }
461                case MotionEvent.ACTION_POINTER_DOWN: {
462                    clear();
463                    transitionToState(STATE_MAGNIFIED_INTERACTION);
464                } break;
465                case MotionEvent.ACTION_MOVE: {
466                    if (event.getPointerCount() != 1) {
467                        throw new IllegalStateException("Should have one pointer down.");
468                    }
469                    final float eventX = event.getX();
470                    final float eventY = event.getY();
471                    if (mViewport.getBounds().contains((int) eventX, (int) eventY)) {
472                        if (mLastMoveOutsideMagnifiedRegion) {
473                            mLastMoveOutsideMagnifiedRegion = false;
474                            mMagnificationController.setMagnifiedRegionCenter(eventX,
475                                    eventY, true);
476                        } else {
477                            mMagnificationController.setMagnifiedRegionCenter(eventX,
478                                    eventY, false);
479                        }
480                    } else {
481                        mLastMoveOutsideMagnifiedRegion = true;
482                    }
483                } break;
484                case MotionEvent.ACTION_UP: {
485                    if (!mTranslationEnabledBeforePan) {
486                        mMagnificationController.reset(true);
487                        mViewport.setFrameShown(false, true);
488                    }
489                    clear();
490                    transitionToState(STATE_DETECTING);
491                } break;
492                case MotionEvent.ACTION_POINTER_UP: {
493                    throw new IllegalArgumentException("Unexpected event type: ACTION_POINTER_UP");
494                }
495            }
496        }
497
498        public void clear() {
499            mLastMoveOutsideMagnifiedRegion = false;
500        }
501    }
502
503    private final class DetectingStateHandler {
504
505        private static final int MESSAGE_ON_ACTION_TAP_AND_HOLD = 1;
506
507        private static final int MESSAGE_TRANSITION_TO_DELEGATING_STATE = 2;
508
509        private static final int ACTION_TAP_COUNT = 3;
510
511        private MotionEventInfo mDelayedEventQueue;
512
513        private MotionEvent mLastDownEvent;
514        private MotionEvent mLastTapUpEvent;
515        private int mTapCount;
516
517        private final Handler mHandler = new Handler() {
518            @Override
519            public void handleMessage(Message message) {
520                final int type = message.what;
521                switch (type) {
522                    case MESSAGE_ON_ACTION_TAP_AND_HOLD: {
523                        MotionEvent event = (MotionEvent) message.obj;
524                        final int policyFlags = message.arg1;
525                        onActionTapAndHold(event, policyFlags);
526                    } break;
527                    case MESSAGE_TRANSITION_TO_DELEGATING_STATE: {
528                        transitionToState(STATE_DELEGATING);
529                        sendDelayedMotionEvents();
530                        clear();
531                    } break;
532                    default: {
533                        throw new IllegalArgumentException("Unknown message type: " + type);
534                    }
535                }
536            }
537        };
538
539        public void onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
540            cacheDelayedMotionEvent(event, rawEvent, policyFlags);
541            final int action = event.getActionMasked();
542            switch (action) {
543                case MotionEvent.ACTION_DOWN: {
544                    mHandler.removeMessages(MESSAGE_TRANSITION_TO_DELEGATING_STATE);
545                    if (!mViewport.getBounds().contains((int) event.getX(),
546                            (int) event.getY())) {
547                        transitionToDelegatingStateAndClear();
548                        return;
549                    }
550                    if (mTapCount == ACTION_TAP_COUNT - 1 && mLastDownEvent != null
551                            && GestureUtils.isMultiTap(mLastDownEvent, event,
552                                    mMultiTapTimeSlop, mMultiTapDistanceSlop, 0)) {
553                        Message message = mHandler.obtainMessage(MESSAGE_ON_ACTION_TAP_AND_HOLD,
554                                policyFlags, 0, event);
555                        mHandler.sendMessageDelayed(message,
556                                ViewConfiguration.getLongPressTimeout());
557                    } else if (mTapCount < ACTION_TAP_COUNT) {
558                        Message message = mHandler.obtainMessage(
559                                MESSAGE_TRANSITION_TO_DELEGATING_STATE);
560                        mHandler.sendMessageDelayed(message, mMultiTapTimeSlop);
561                    }
562                    clearLastDownEvent();
563                    mLastDownEvent = MotionEvent.obtain(event);
564                } break;
565                case MotionEvent.ACTION_POINTER_DOWN: {
566                    if (mMagnificationController.isMagnifying()) {
567                        transitionToState(STATE_MAGNIFIED_INTERACTION);
568                        clear();
569                    } else {
570                        transitionToDelegatingStateAndClear();
571                    }
572                } break;
573                case MotionEvent.ACTION_MOVE: {
574                    if (mLastDownEvent != null && mTapCount < ACTION_TAP_COUNT - 1) {
575                        final double distance = GestureUtils.computeDistance(mLastDownEvent,
576                                event, 0);
577                        if (Math.abs(distance) > mTapDistanceSlop) {
578                            transitionToDelegatingStateAndClear();
579                        }
580                    }
581                } break;
582                case MotionEvent.ACTION_UP: {
583                    if (mLastDownEvent == null) {
584                        return;
585                    }
586                    mHandler.removeMessages(MESSAGE_ON_ACTION_TAP_AND_HOLD);
587                    if (!mViewport.getBounds().contains((int) event.getX(), (int) event.getY())) {
588                         transitionToDelegatingStateAndClear();
589                         return;
590                    }
591                    if (!GestureUtils.isTap(mLastDownEvent, event, mTapTimeSlop,
592                            mTapDistanceSlop, 0)) {
593                        transitionToDelegatingStateAndClear();
594                        return;
595                    }
596                    if (mLastTapUpEvent != null && !GestureUtils.isMultiTap(mLastTapUpEvent,
597                            event, mMultiTapTimeSlop, mMultiTapDistanceSlop, 0)) {
598                        transitionToDelegatingStateAndClear();
599                        return;
600                    }
601                    mTapCount++;
602                    if (DEBUG_DETECTING) {
603                        Slog.i(LOG_TAG, "Tap count:" + mTapCount);
604                    }
605                    if (mTapCount == ACTION_TAP_COUNT) {
606                        clear();
607                        onActionTap(event, policyFlags);
608                        return;
609                    }
610                    clearLastTapUpEvent();
611                    mLastTapUpEvent = MotionEvent.obtain(event);
612                } break;
613                case MotionEvent.ACTION_POINTER_UP: {
614                    /* do nothing */
615                } break;
616            }
617        }
618
619        public void clear() {
620            mHandler.removeMessages(MESSAGE_ON_ACTION_TAP_AND_HOLD);
621            mHandler.removeMessages(MESSAGE_TRANSITION_TO_DELEGATING_STATE);
622            clearTapDetectionState();
623            clearDelayedMotionEvents();
624        }
625
626        private void clearTapDetectionState() {
627            mTapCount = 0;
628            clearLastTapUpEvent();
629            clearLastDownEvent();
630        }
631
632        private void clearLastTapUpEvent() {
633            if (mLastTapUpEvent != null) {
634                mLastTapUpEvent.recycle();
635                mLastTapUpEvent = null;
636            }
637        }
638
639        private void clearLastDownEvent() {
640            if (mLastDownEvent != null) {
641                mLastDownEvent.recycle();
642                mLastDownEvent = null;
643            }
644        }
645
646        private void cacheDelayedMotionEvent(MotionEvent event, MotionEvent rawEvent,
647                int policyFlags) {
648            MotionEventInfo info = MotionEventInfo.obtain(event, rawEvent,
649                    policyFlags);
650            if (mDelayedEventQueue == null) {
651                mDelayedEventQueue = info;
652            } else {
653                MotionEventInfo tail = mDelayedEventQueue;
654                while (tail.mNext != null) {
655                    tail = tail.mNext;
656                }
657                tail.mNext = info;
658            }
659        }
660
661        private void sendDelayedMotionEvents() {
662            while (mDelayedEventQueue != null) {
663                MotionEventInfo info = mDelayedEventQueue;
664                mDelayedEventQueue = info.mNext;
665                ScreenMagnifier.this.onMotionEvent(info.mEvent, info.mRawEvent,
666                        info.mPolicyFlags);
667                info.recycle();
668            }
669        }
670
671        private void clearDelayedMotionEvents() {
672            while (mDelayedEventQueue != null) {
673                MotionEventInfo info = mDelayedEventQueue;
674                mDelayedEventQueue = info.mNext;
675                info.recycle();
676            }
677        }
678
679        private void transitionToDelegatingStateAndClear() {
680            transitionToState(STATE_DELEGATING);
681            sendDelayedMotionEvents();
682            clear();
683        }
684
685        private void onActionTap(MotionEvent up, int policyFlags) {
686            if (DEBUG_DETECTING) {
687                Slog.i(LOG_TAG, "onActionTap()");
688            }
689            if (!mMagnificationController.isMagnifying()) {
690                mMagnificationController.setScaleAndMagnifiedRegionCenter(getPersistedScale(),
691                        up.getX(), up.getY(), true);
692                mViewport.setFrameShown(true, true);
693            } else {
694                mMagnificationController.reset(true);
695                mViewport.setFrameShown(false, true);
696            }
697        }
698
699        private void onActionTapAndHold(MotionEvent down, int policyFlags) {
700            if (DEBUG_DETECTING) {
701                Slog.i(LOG_TAG, "onActionTapAndHold()");
702            }
703            clear();
704            mTranslationEnabledBeforePan = mMagnificationController.isMagnifying();
705            mMagnificationController.setScaleAndMagnifiedRegionCenter(getPersistedScale(),
706                    down.getX(), down.getY(), true);
707            mViewport.setFrameShown(true, true);
708            transitionToState(STATE_VIEWPORT_DRAGGING);
709        }
710    }
711
712    private void persistScale(final float scale) {
713        new AsyncTask<Void, Void, Void>() {
714            @Override
715            protected Void doInBackground(Void... params) {
716                Settings.Secure.putFloat(mContext.getContentResolver(),
717                        Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE, scale);
718                return null;
719            }
720        }.execute();
721    }
722
723    private float getPersistedScale() {
724        return Settings.Secure.getFloat(mContext.getContentResolver(),
725                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE,
726                DEFAULT_MAGNIFICATION_SCALE);
727    }
728
729    private static boolean isScreenMagnificationAutoUpdateEnabled(Context context) {
730        return (Settings.Secure.getInt(context.getContentResolver(),
731                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE,
732                DEFAULT_SCREEN_MAGNIFICATION_AUTO_UPDATE) == 1);
733    }
734
735    private static final class MotionEventInfo {
736
737        private static final int MAX_POOL_SIZE = 10;
738
739        private static final Object sLock = new Object();
740        private static MotionEventInfo sPool;
741        private static int sPoolSize;
742
743        private MotionEventInfo mNext;
744        private boolean mInPool;
745
746        public MotionEvent mEvent;
747        public MotionEvent mRawEvent;
748        public int mPolicyFlags;
749
750        public static MotionEventInfo obtain(MotionEvent event, MotionEvent rawEvent,
751                int policyFlags) {
752            synchronized (sLock) {
753                MotionEventInfo info;
754                if (sPoolSize > 0) {
755                    sPoolSize--;
756                    info = sPool;
757                    sPool = info.mNext;
758                    info.mNext = null;
759                    info.mInPool = false;
760                } else {
761                    info = new MotionEventInfo();
762                }
763                info.initialize(event, rawEvent, policyFlags);
764                return info;
765            }
766        }
767
768        private void initialize(MotionEvent event, MotionEvent rawEvent,
769                int policyFlags) {
770            mEvent = MotionEvent.obtain(event);
771            mRawEvent = MotionEvent.obtain(rawEvent);
772            mPolicyFlags = policyFlags;
773        }
774
775        public void recycle() {
776            synchronized (sLock) {
777                if (mInPool) {
778                    throw new IllegalStateException("Already recycled.");
779                }
780                clear();
781                if (sPoolSize < MAX_POOL_SIZE) {
782                    sPoolSize++;
783                    mNext = sPool;
784                    sPool = this;
785                    mInPool = true;
786                }
787            }
788        }
789
790        private void clear() {
791            mEvent.recycle();
792            mEvent = null;
793            mRawEvent.recycle();
794            mRawEvent = null;
795            mPolicyFlags = 0;
796        }
797    }
798
799    private static final class ScreenStateObserver extends BroadcastReceiver {
800
801        private static final int MESSAGE_ON_SCREEN_STATE_CHANGE = 1;
802
803        private final Handler mHandler = new Handler() {
804            @Override
805            public void handleMessage(Message message) {
806                switch (message.what) {
807                    case MESSAGE_ON_SCREEN_STATE_CHANGE: {
808                        String action = (String) message.obj;
809                        handleOnScreenStateChange(action);
810                    } break;
811                }
812            }
813        };
814
815        private final Context mContext;
816        private final Viewport mViewport;
817        private final MagnificationController mMagnificationController;
818
819        public ScreenStateObserver(Context context, Viewport viewport,
820                MagnificationController magnificationController) {
821            mContext = context;
822            mViewport = viewport;
823            mMagnificationController = magnificationController;
824            mContext.registerReceiver(this, new IntentFilter(Intent.ACTION_SCREEN_OFF));
825        }
826
827        public void destroy() {
828            mContext.unregisterReceiver(this);
829        }
830
831        @Override
832        public void onReceive(Context context, Intent intent) {
833            mHandler.obtainMessage(MESSAGE_ON_SCREEN_STATE_CHANGE,
834                    intent.getAction()).sendToTarget();
835        }
836
837        private void handleOnScreenStateChange(String action) {
838            if (action.equals(Intent.ACTION_SCREEN_OFF)
839                    && mMagnificationController.isMagnifying()
840                    && isScreenMagnificationAutoUpdateEnabled(mContext)) {
841                mMagnificationController.reset(false);
842                mViewport.setFrameShown(false, false);
843            }
844        }
845    }
846
847    private static final class DisplayContentObserver {
848
849        private static final int MESSAGE_SHOW_VIEWPORT_FRAME = 1;
850        private static final int MESSAGE_ON_RECTANGLE_ON_SCREEN_REQUESTED = 3;
851        private static final int MESSAGE_ON_WINDOW_TRANSITION = 4;
852        private static final int MESSAGE_ON_ROTATION_CHANGED = 5;
853
854        private final Handler mHandler = new MyHandler();
855
856        private final Rect mTempRect = new Rect();
857
858        private final IDisplayContentChangeListener mDisplayContentChangeListener;
859
860        private final Context mContext;
861        private final Viewport mViewport;
862        private final MagnificationController mMagnificationController;
863        private final IWindowManager mWindowManagerService;
864        private final DisplayProvider mDisplayProvider;
865        private final long mLongAnimationDuration;
866        private final float mWindowAnimationScale;
867
868        public DisplayContentObserver(Context context, Viewport viewport,
869                MagnificationController magnificationController,
870                IWindowManager windowManagerService, DisplayProvider displayProvider,
871                long longAnimationDuration, float windowAnimationScale) {
872            mContext = context;
873            mViewport = viewport;
874            mMagnificationController = magnificationController;
875            mWindowManagerService = windowManagerService;
876            mDisplayProvider = displayProvider;
877            mLongAnimationDuration = longAnimationDuration;
878            mWindowAnimationScale = windowAnimationScale;
879
880            mDisplayContentChangeListener = new IDisplayContentChangeListener.Stub() {
881                @Override
882                public void onWindowTransition(int displayId, int transition, WindowInfo info) {
883                    Message message = mHandler.obtainMessage(MESSAGE_ON_WINDOW_TRANSITION,
884                            transition, 0, WindowInfo.obtain(info));
885                    // TODO: This makes me quite unhappy but for the time being the
886                    //       least risky fix for cases where the keyguard is removed but
887                    //       the windows it force hides are not made visible yet. Hence,
888                    //       we would compute the magnified frame before we have a stable
889                    //       state. One more reason to move the magnified frame computation
890                    //       in the window manager!
891                    if (info.type == WindowManager.LayoutParams.TYPE_KEYGUARD
892                                || info.type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
893                            && (transition == WindowManagerPolicy.TRANSIT_EXIT
894                                || transition == WindowManagerPolicy.TRANSIT_HIDE)) {
895                        final long delay = (long) (2 * mLongAnimationDuration
896                                * mWindowAnimationScale);
897                        mHandler.sendMessageDelayed(message, delay);
898                    } else {
899                        message.sendToTarget();
900                    }
901                }
902
903                @Override
904                public void onRectangleOnScreenRequested(int dsiplayId, Rect rectangle,
905                        boolean immediate) {
906                    SomeArgs args = SomeArgs.obtain();
907                    args.argi1 = rectangle.left;
908                    args.argi2 = rectangle.top;
909                    args.argi3 = rectangle.right;
910                    args.argi4 = rectangle.bottom;
911                    mHandler.obtainMessage(MESSAGE_ON_RECTANGLE_ON_SCREEN_REQUESTED, 0,
912                            immediate ? 1 : 0, args).sendToTarget();
913                }
914
915                @Override
916                public void onRotationChanged(int rotation) throws RemoteException {
917                    mHandler.obtainMessage(MESSAGE_ON_ROTATION_CHANGED, rotation, 0)
918                            .sendToTarget();
919                }
920            };
921
922            try {
923                mWindowManagerService.addDisplayContentChangeListener(
924                        mDisplayProvider.getDisplay().getDisplayId(),
925                        mDisplayContentChangeListener);
926            } catch (RemoteException re) {
927                /* ignore */
928            }
929        }
930
931        public void destroy() {
932            try {
933                mWindowManagerService.removeDisplayContentChangeListener(
934                        mDisplayProvider.getDisplay().getDisplayId(),
935                        mDisplayContentChangeListener);
936            } catch (RemoteException re) {
937                /* ignore*/
938            }
939        }
940
941        private void handleOnRotationChanged(int rotation) {
942            if (DEBUG_ROTATION) {
943                Slog.i(LOG_TAG, "Rotation: " + rotationToString(rotation));
944            }
945            resetMagnificationIfNeeded();
946            mViewport.setFrameShown(false, false);
947            mViewport.rotationChanged();
948            mViewport.recomputeBounds(false);
949            if (mMagnificationController.isMagnifying()) {
950                final long delay = (long) (2 * mLongAnimationDuration * mWindowAnimationScale);
951                Message message = mHandler.obtainMessage(MESSAGE_SHOW_VIEWPORT_FRAME);
952                mHandler.sendMessageDelayed(message, delay);
953            }
954        }
955
956        private void handleOnWindowTransition(int transition, WindowInfo info) {
957            if (DEBUG_WINDOW_TRANSITIONS) {
958                Slog.i(LOG_TAG, "Window transitioning: "
959                        + windowTransitionToString(transition));
960            }
961            try {
962                final boolean magnifying = mMagnificationController.isMagnifying();
963                if (magnifying) {
964                    switch (transition) {
965                        case WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN:
966                        case WindowManagerPolicy.TRANSIT_TASK_OPEN:
967                        case WindowManagerPolicy.TRANSIT_TASK_TO_FRONT:
968                        case WindowManagerPolicy.TRANSIT_WALLPAPER_OPEN:
969                        case WindowManagerPolicy.TRANSIT_WALLPAPER_CLOSE:
970                        case WindowManagerPolicy.TRANSIT_WALLPAPER_INTRA_OPEN: {
971                            resetMagnificationIfNeeded();
972                        }
973                    }
974                }
975                if (info.type == WindowManager.LayoutParams.TYPE_NAVIGATION_BAR
976                        || info.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD
977                        || info.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG
978                        || info.type == WindowManager.LayoutParams.TYPE_KEYGUARD
979                        || info.type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {
980                    switch (transition) {
981                        case WindowManagerPolicy.TRANSIT_ENTER:
982                        case WindowManagerPolicy.TRANSIT_SHOW:
983                        case WindowManagerPolicy.TRANSIT_EXIT:
984                        case WindowManagerPolicy.TRANSIT_HIDE: {
985                            mViewport.recomputeBounds(mMagnificationController.isMagnifying());
986                        } break;
987                    }
988                } else {
989                    switch (transition) {
990                        case WindowManagerPolicy.TRANSIT_ENTER:
991                        case WindowManagerPolicy.TRANSIT_SHOW: {
992                            if (!magnifying || !isScreenMagnificationAutoUpdateEnabled(mContext)) {
993                                break;
994                            }
995                            final int type = info.type;
996                            switch (type) {
997                                // TODO: Are these all the windows we want to make
998                                //       visible when they appear on the screen?
999                                //       Do we need to take some of them out?
1000                                case WindowManager.LayoutParams.TYPE_APPLICATION_PANEL:
1001                                case WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA:
1002                                case WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL:
1003                                case WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG:
1004                                case WindowManager.LayoutParams.TYPE_SEARCH_BAR:
1005                                case WindowManager.LayoutParams.TYPE_PHONE:
1006                                case WindowManager.LayoutParams.TYPE_SYSTEM_ALERT:
1007                                case WindowManager.LayoutParams.TYPE_TOAST:
1008                                case WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY:
1009                                case WindowManager.LayoutParams.TYPE_PRIORITY_PHONE:
1010                                case WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG:
1011                                case WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG:
1012                                case WindowManager.LayoutParams.TYPE_SYSTEM_ERROR:
1013                                case WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY:
1014                                case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL:
1015                                case WindowManager.LayoutParams.TYPE_RECENTS_OVERLAY: {
1016                                    Rect magnifiedRegionBounds = mMagnificationController
1017                                            .getMagnifiedRegionBounds();
1018                                    Rect touchableRegion = info.touchableRegion;
1019                                    if (!magnifiedRegionBounds.intersect(touchableRegion)) {
1020                                        ensureRectangleInMagnifiedRegionBounds(
1021                                                magnifiedRegionBounds, touchableRegion);
1022                                    }
1023                                } break;
1024                            } break;
1025                        }
1026                    }
1027                }
1028            } finally {
1029                if (info != null) {
1030                    info.recycle();
1031                }
1032            }
1033        }
1034
1035        private void handleOnRectangleOnScreenRequested(Rect rectangle, boolean immediate) {
1036            if (!mMagnificationController.isMagnifying()) {
1037                return;
1038            }
1039            Rect magnifiedRegionBounds = mMagnificationController.getMagnifiedRegionBounds();
1040            if (magnifiedRegionBounds.contains(rectangle)) {
1041                return;
1042            }
1043            ensureRectangleInMagnifiedRegionBounds(magnifiedRegionBounds, rectangle);
1044        }
1045
1046        private void ensureRectangleInMagnifiedRegionBounds(Rect magnifiedRegionBounds,
1047                Rect rectangle) {
1048            if (!Rect.intersects(rectangle, mViewport.getBounds())) {
1049                return;
1050            }
1051            final float scrollX;
1052            final float scrollY;
1053            if (rectangle.width() > magnifiedRegionBounds.width()) {
1054                scrollX = rectangle.left - magnifiedRegionBounds.left;
1055            } else if (rectangle.left < magnifiedRegionBounds.left) {
1056                scrollX = rectangle.left - magnifiedRegionBounds.left;
1057            } else if (rectangle.right > magnifiedRegionBounds.right) {
1058                scrollX = rectangle.right - magnifiedRegionBounds.right;
1059            } else {
1060                scrollX = 0;
1061            }
1062            if (rectangle.height() > magnifiedRegionBounds.height()) {
1063                scrollY = rectangle.top - magnifiedRegionBounds.top;
1064            } else if (rectangle.top < magnifiedRegionBounds.top) {
1065                scrollY = rectangle.top - magnifiedRegionBounds.top;
1066            } else if (rectangle.bottom > magnifiedRegionBounds.bottom) {
1067                scrollY = rectangle.bottom - magnifiedRegionBounds.bottom;
1068            } else {
1069                scrollY = 0;
1070            }
1071            final float viewportCenterX = mMagnificationController.getMagnifiedRegionCenterX()
1072                    + scrollX;
1073            final float viewportCenterY = mMagnificationController.getMagnifiedRegionCenterY()
1074                    + scrollY;
1075            mMagnificationController.setMagnifiedRegionCenter(viewportCenterX, viewportCenterY,
1076                    true);
1077        }
1078
1079        private void resetMagnificationIfNeeded() {
1080            if (mMagnificationController.isMagnifying()
1081                    && isScreenMagnificationAutoUpdateEnabled(mContext)) {
1082                mMagnificationController.reset(true);
1083                mViewport.setFrameShown(false, true);
1084            }
1085        }
1086
1087        private String windowTransitionToString(int transition) {
1088            switch (transition) {
1089                case WindowManagerPolicy.TRANSIT_UNSET: {
1090                    return "TRANSIT_UNSET";
1091                }
1092                case WindowManagerPolicy.TRANSIT_NONE: {
1093                    return "TRANSIT_NONE";
1094                }
1095                case WindowManagerPolicy.TRANSIT_ENTER: {
1096                    return "TRANSIT_ENTER";
1097                }
1098                case WindowManagerPolicy.TRANSIT_EXIT: {
1099                    return "TRANSIT_EXIT";
1100                }
1101                case WindowManagerPolicy.TRANSIT_SHOW: {
1102                    return "TRANSIT_SHOW";
1103                }
1104                case WindowManagerPolicy.TRANSIT_EXIT_MASK: {
1105                    return "TRANSIT_EXIT_MASK";
1106                }
1107                case WindowManagerPolicy.TRANSIT_PREVIEW_DONE: {
1108                    return "TRANSIT_PREVIEW_DONE";
1109                }
1110                case WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN: {
1111                    return "TRANSIT_ACTIVITY_OPEN";
1112                }
1113                case WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE: {
1114                    return "TRANSIT_ACTIVITY_CLOSE";
1115                }
1116                case WindowManagerPolicy.TRANSIT_TASK_OPEN: {
1117                    return "TRANSIT_TASK_OPEN";
1118                }
1119                case WindowManagerPolicy.TRANSIT_TASK_CLOSE: {
1120                    return "TRANSIT_TASK_CLOSE";
1121                }
1122                case WindowManagerPolicy.TRANSIT_TASK_TO_FRONT: {
1123                    return "TRANSIT_TASK_TO_FRONT";
1124                }
1125                case WindowManagerPolicy.TRANSIT_TASK_TO_BACK: {
1126                    return "TRANSIT_TASK_TO_BACK";
1127                }
1128                case WindowManagerPolicy.TRANSIT_WALLPAPER_CLOSE: {
1129                    return "TRANSIT_WALLPAPER_CLOSE";
1130                }
1131                case WindowManagerPolicy.TRANSIT_WALLPAPER_OPEN: {
1132                    return "TRANSIT_WALLPAPER_OPEN";
1133                }
1134                case WindowManagerPolicy.TRANSIT_WALLPAPER_INTRA_OPEN: {
1135                    return "TRANSIT_WALLPAPER_INTRA_OPEN";
1136                }
1137                case WindowManagerPolicy.TRANSIT_WALLPAPER_INTRA_CLOSE: {
1138                    return "TRANSIT_WALLPAPER_INTRA_CLOSE";
1139                }
1140                default: {
1141                    return "<UNKNOWN>";
1142                }
1143            }
1144        }
1145
1146        private String rotationToString(int rotation) {
1147            switch (rotation) {
1148                case Surface.ROTATION_0: {
1149                    return "ROTATION_0";
1150                }
1151                case Surface.ROTATION_90: {
1152                    return "ROATATION_90";
1153                }
1154                case Surface.ROTATION_180: {
1155                    return "ROATATION_180";
1156                }
1157                case Surface.ROTATION_270: {
1158                    return "ROATATION_270";
1159                }
1160                default: {
1161                    throw new IllegalArgumentException("Invalid rotation: "
1162                        + rotation);
1163                }
1164            }
1165        }
1166
1167        private final class MyHandler extends Handler {
1168            @Override
1169            public void handleMessage(Message message) {
1170                final int action = message.what;
1171                switch (action) {
1172                    case MESSAGE_SHOW_VIEWPORT_FRAME: {
1173                        mViewport.setFrameShown(true, true);
1174                    } break;
1175                    case MESSAGE_ON_RECTANGLE_ON_SCREEN_REQUESTED: {
1176                        SomeArgs args = (SomeArgs) message.obj;
1177                        try {
1178                            mTempRect.set(args.argi1, args.argi2, args.argi3, args.argi4);
1179                            final boolean immediate = (message.arg1 == 1);
1180                            handleOnRectangleOnScreenRequested(mTempRect, immediate);
1181                        } finally {
1182                            args.recycle();
1183                        }
1184                    } break;
1185                    case MESSAGE_ON_WINDOW_TRANSITION: {
1186                        final int transition = message.arg1;
1187                        WindowInfo info = (WindowInfo) message.obj;
1188                        handleOnWindowTransition(transition, info);
1189                    } break;
1190                    case MESSAGE_ON_ROTATION_CHANGED: {
1191                        final int rotation = message.arg1;
1192                        handleOnRotationChanged(rotation);
1193                    } break;
1194                    default: {
1195                        throw new IllegalArgumentException("Unknown message: " + action);
1196                    }
1197                }
1198            }
1199        }
1200    }
1201
1202    private final class MagnificationController {
1203
1204        private static final String PROPERTY_NAME_ACCESSIBILITY_TRANSFORMATION =
1205                "accessibilityTransformation";
1206
1207        private final MagnificationSpec mSentMagnificationSpec = new MagnificationSpec();
1208
1209        private final MagnificationSpec mCurrentMagnificationSpec = new MagnificationSpec();
1210
1211        private final Rect mTempRect = new Rect();
1212
1213        private final ValueAnimator mTransformationAnimator;
1214
1215        public MagnificationController(int animationDuration) {
1216            Property<MagnificationController, MagnificationSpec> property =
1217                    Property.of(MagnificationController.class, MagnificationSpec.class,
1218                    PROPERTY_NAME_ACCESSIBILITY_TRANSFORMATION);
1219            TypeEvaluator<MagnificationSpec> evaluator = new TypeEvaluator<MagnificationSpec>() {
1220                private final MagnificationSpec mTempTransformationSpec = new MagnificationSpec();
1221                @Override
1222                public MagnificationSpec evaluate(float fraction, MagnificationSpec fromSpec,
1223                        MagnificationSpec toSpec) {
1224                    MagnificationSpec result = mTempTransformationSpec;
1225                    result.mScale = fromSpec.mScale
1226                            + (toSpec.mScale - fromSpec.mScale) * fraction;
1227                    result.mMagnifiedRegionCenterX = fromSpec.mMagnifiedRegionCenterX
1228                            + (toSpec.mMagnifiedRegionCenterX - fromSpec.mMagnifiedRegionCenterX)
1229                            * fraction;
1230                    result.mMagnifiedRegionCenterY = fromSpec.mMagnifiedRegionCenterY
1231                            + (toSpec.mMagnifiedRegionCenterY - fromSpec.mMagnifiedRegionCenterY)
1232                            * fraction;
1233                    result.mScaledOffsetX = fromSpec.mScaledOffsetX
1234                            + (toSpec.mScaledOffsetX - fromSpec.mScaledOffsetX)
1235                            * fraction;
1236                    result.mScaledOffsetY = fromSpec.mScaledOffsetY
1237                            + (toSpec.mScaledOffsetY - fromSpec.mScaledOffsetY)
1238                            * fraction;
1239                    return result;
1240                }
1241            };
1242            mTransformationAnimator = ObjectAnimator.ofObject(this, property,
1243                    evaluator, mSentMagnificationSpec, mCurrentMagnificationSpec);
1244            mTransformationAnimator.setDuration((long) (animationDuration));
1245            mTransformationAnimator.setInterpolator(mInterpolator);
1246        }
1247
1248        public boolean isMagnifying() {
1249            return mCurrentMagnificationSpec.mScale > 1.0f;
1250        }
1251
1252        public void reset(boolean animate) {
1253            if (mTransformationAnimator.isRunning()) {
1254                mTransformationAnimator.cancel();
1255            }
1256            mCurrentMagnificationSpec.reset();
1257            if (animate) {
1258                animateAccessibilityTranformation(mSentMagnificationSpec,
1259                        mCurrentMagnificationSpec);
1260            } else {
1261                setAccessibilityTransformation(mCurrentMagnificationSpec);
1262            }
1263        }
1264
1265        public Rect getMagnifiedRegionBounds() {
1266            mTempRect.set(mViewport.getBounds());
1267            mTempRect.offset((int) -mCurrentMagnificationSpec.mScaledOffsetX,
1268                    (int) -mCurrentMagnificationSpec.mScaledOffsetY);
1269            mTempRect.scale(1.0f / mCurrentMagnificationSpec.mScale);
1270            return mTempRect;
1271        }
1272
1273        public float getScale() {
1274            return mCurrentMagnificationSpec.mScale;
1275        }
1276
1277        public float getMagnifiedRegionCenterX() {
1278            return mCurrentMagnificationSpec.mMagnifiedRegionCenterX;
1279        }
1280
1281        public float getMagnifiedRegionCenterY() {
1282            return mCurrentMagnificationSpec.mMagnifiedRegionCenterY;
1283        }
1284
1285        public float getScaledOffsetX() {
1286            return mCurrentMagnificationSpec.mScaledOffsetX;
1287        }
1288
1289        public float getScaledOffsetY() {
1290            return mCurrentMagnificationSpec.mScaledOffsetY;
1291        }
1292
1293        public void setScale(float scale, float pivotX, float pivotY, boolean animate) {
1294            MagnificationSpec spec = mCurrentMagnificationSpec;
1295            final float oldScale = spec.mScale;
1296            final float oldCenterX = spec.mMagnifiedRegionCenterX;
1297            final float oldCenterY = spec.mMagnifiedRegionCenterY;
1298            final float normPivotX = (-spec.mScaledOffsetX + pivotX) / oldScale;
1299            final float normPivotY = (-spec.mScaledOffsetY + pivotY) / oldScale;
1300            final float offsetX = (oldCenterX - normPivotX) * (oldScale / scale);
1301            final float offsetY = (oldCenterY - normPivotY) * (oldScale / scale);
1302            final float centerX = normPivotX + offsetX;
1303            final float centerY = normPivotY + offsetY;
1304            setScaleAndMagnifiedRegionCenter(scale, centerX, centerY, animate);
1305        }
1306
1307        public void setMagnifiedRegionCenter(float centerX, float centerY, boolean animate) {
1308            setScaleAndMagnifiedRegionCenter(mCurrentMagnificationSpec.mScale, centerX, centerY,
1309                    animate);
1310        }
1311
1312        public void setScaleAndMagnifiedRegionCenter(float scale, float centerX, float centerY,
1313                boolean animate) {
1314            if (Float.compare(mCurrentMagnificationSpec.mScale, scale) == 0
1315                    && Float.compare(mCurrentMagnificationSpec.mMagnifiedRegionCenterX,
1316                            centerX) == 0
1317                    && Float.compare(mCurrentMagnificationSpec.mMagnifiedRegionCenterY,
1318                            centerY) == 0) {
1319                return;
1320            }
1321            if (mTransformationAnimator.isRunning()) {
1322                mTransformationAnimator.cancel();
1323            }
1324            if (DEBUG_MAGNIFICATION_CONTROLLER) {
1325                Slog.i(LOG_TAG, "scale: " + scale + " centerX: " + centerX
1326                        + " centerY: " + centerY);
1327            }
1328            mCurrentMagnificationSpec.initialize(scale, centerX, centerY);
1329            if (animate) {
1330                animateAccessibilityTranformation(mSentMagnificationSpec,
1331                        mCurrentMagnificationSpec);
1332            } else {
1333                setAccessibilityTransformation(mCurrentMagnificationSpec);
1334            }
1335        }
1336
1337        private void animateAccessibilityTranformation(MagnificationSpec fromSpec,
1338                MagnificationSpec toSpec) {
1339            mTransformationAnimator.setObjectValues(fromSpec, toSpec);
1340            mTransformationAnimator.start();
1341        }
1342
1343        @SuppressWarnings("unused")
1344        // Called from an animator.
1345        public MagnificationSpec getAccessibilityTransformation() {
1346            return mSentMagnificationSpec;
1347        }
1348
1349        public void setAccessibilityTransformation(MagnificationSpec transformation) {
1350            if (DEBUG_TRANSFORMATION) {
1351                Slog.i(LOG_TAG, "Transformation scale: " + transformation.mScale
1352                        + " offsetX: " + transformation.mScaledOffsetX
1353                        + " offsetY: " + transformation.mScaledOffsetY);
1354            }
1355            try {
1356                mSentMagnificationSpec.updateFrom(transformation);
1357                mWindowManagerService.magnifyDisplay(mDisplayProvider.getDisplay().getDisplayId(),
1358                        transformation.mScale, transformation.mScaledOffsetX,
1359                        transformation.mScaledOffsetY);
1360            } catch (RemoteException re) {
1361                /* ignore */
1362            }
1363        }
1364
1365        private class MagnificationSpec {
1366
1367            private static final float DEFAULT_SCALE = 1.0f;
1368
1369            public float mScale = DEFAULT_SCALE;
1370
1371            public float mMagnifiedRegionCenterX;
1372
1373            public float mMagnifiedRegionCenterY;
1374
1375            public float mScaledOffsetX;
1376
1377            public float mScaledOffsetY;
1378
1379            public void initialize(float scale, float magnifiedRegionCenterX,
1380                    float magnifiedRegionCenterY) {
1381                mScale = scale;
1382
1383                final int viewportWidth = mViewport.getBounds().width();
1384                final int viewportHeight = mViewport.getBounds().height();
1385                final float minMagnifiedRegionCenterX = (viewportWidth / 2) / scale;
1386                final float minMagnifiedRegionCenterY = (viewportHeight / 2) / scale;
1387                final float maxMagnifiedRegionCenterX = viewportWidth - minMagnifiedRegionCenterX;
1388                final float maxMagnifiedRegionCenterY = viewportHeight - minMagnifiedRegionCenterY;
1389
1390                mMagnifiedRegionCenterX = Math.min(Math.max(magnifiedRegionCenterX,
1391                        minMagnifiedRegionCenterX), maxMagnifiedRegionCenterX);
1392                mMagnifiedRegionCenterY = Math.min(Math.max(magnifiedRegionCenterY,
1393                        minMagnifiedRegionCenterY), maxMagnifiedRegionCenterY);
1394
1395                mScaledOffsetX = -(mMagnifiedRegionCenterX * scale - viewportWidth / 2);
1396                mScaledOffsetY = -(mMagnifiedRegionCenterY * scale - viewportHeight / 2);
1397            }
1398
1399            public void updateFrom(MagnificationSpec other) {
1400                mScale = other.mScale;
1401                mMagnifiedRegionCenterX = other.mMagnifiedRegionCenterX;
1402                mMagnifiedRegionCenterY = other.mMagnifiedRegionCenterY;
1403                mScaledOffsetX = other.mScaledOffsetX;
1404                mScaledOffsetY = other.mScaledOffsetY;
1405            }
1406
1407            public void reset() {
1408                mScale = DEFAULT_SCALE;
1409                mMagnifiedRegionCenterX = 0;
1410                mMagnifiedRegionCenterY = 0;
1411                mScaledOffsetX = 0;
1412                mScaledOffsetY = 0;
1413            }
1414        }
1415    }
1416
1417    private static final class Viewport {
1418
1419        private static final String PROPERTY_NAME_ALPHA = "alpha";
1420
1421        private static final String PROPERTY_NAME_BOUNDS = "bounds";
1422
1423        private static final int MIN_ALPHA = 0;
1424
1425        private static final int MAX_ALPHA = 255;
1426
1427        private final ArrayList<WindowInfo> mTempWindowInfoList = new ArrayList<WindowInfo>();
1428
1429        private final Rect mTempRect1 = new Rect();
1430        private final Rect mTempRect2 = new Rect();
1431        private final Rect mTempRect3 = new Rect();
1432
1433        private final IWindowManager mWindowManagerService;
1434        private final DisplayProvider mDisplayProvider;
1435
1436        private final ViewportWindow mViewportFrame;
1437
1438        private final ValueAnimator mResizeFrameAnimator;
1439
1440        private final ValueAnimator mShowHideFrameAnimator;
1441
1442        public Viewport(Context context, WindowManager windowManager,
1443                IWindowManager windowManagerService, DisplayProvider displayInfoProvider,
1444                Interpolator animationInterpolator, long animationDuration) {
1445            mWindowManagerService = windowManagerService;
1446            mDisplayProvider = displayInfoProvider;
1447            mViewportFrame = new ViewportWindow(context, windowManager, displayInfoProvider);
1448
1449            mShowHideFrameAnimator = ObjectAnimator.ofInt(mViewportFrame, PROPERTY_NAME_ALPHA,
1450                  MIN_ALPHA, MAX_ALPHA);
1451            mShowHideFrameAnimator.setInterpolator(animationInterpolator);
1452            mShowHideFrameAnimator.setDuration(animationDuration);
1453            mShowHideFrameAnimator.addListener(new AnimatorListener() {
1454                @Override
1455                public void onAnimationEnd(Animator animation) {
1456                    if (mShowHideFrameAnimator.getAnimatedValue().equals(MIN_ALPHA)) {
1457                        mViewportFrame.hide();
1458                    }
1459                }
1460                @Override
1461                public void onAnimationStart(Animator animation) {
1462                    /* do nothing - stub */
1463                }
1464                @Override
1465                public void onAnimationCancel(Animator animation) {
1466                    /* do nothing - stub */
1467                }
1468                @Override
1469                public void onAnimationRepeat(Animator animation) {
1470                    /* do nothing - stub */
1471                }
1472            });
1473
1474            Property<ViewportWindow, Rect> property = Property.of(ViewportWindow.class,
1475                    Rect.class, PROPERTY_NAME_BOUNDS);
1476            TypeEvaluator<Rect> evaluator = new TypeEvaluator<Rect>() {
1477                private final Rect mReusableResultRect = new Rect();
1478                @Override
1479                public Rect evaluate(float fraction, Rect fromFrame, Rect toFrame) {
1480                    Rect result = mReusableResultRect;
1481                    result.left = (int) (fromFrame.left
1482                            + (toFrame.left - fromFrame.left) * fraction);
1483                    result.top = (int) (fromFrame.top
1484                            + (toFrame.top - fromFrame.top) * fraction);
1485                    result.right = (int) (fromFrame.right
1486                            + (toFrame.right - fromFrame.right) * fraction);
1487                    result.bottom = (int) (fromFrame.bottom
1488                            + (toFrame.bottom - fromFrame.bottom) * fraction);
1489                    return result;
1490                }
1491            };
1492            mResizeFrameAnimator = ObjectAnimator.ofObject(mViewportFrame, property,
1493                    evaluator, mViewportFrame.mBounds, mViewportFrame.mBounds);
1494            mResizeFrameAnimator.setDuration((long) (animationDuration));
1495            mResizeFrameAnimator.setInterpolator(animationInterpolator);
1496
1497            recomputeBounds(false);
1498        }
1499
1500        private final Comparator<WindowInfo> mWindowInfoInverseComparator =
1501                new Comparator<WindowInfo>() {
1502            @Override
1503            public int compare(WindowInfo lhs, WindowInfo rhs) {
1504                if (lhs.layer != rhs.layer) {
1505                    return rhs.layer - lhs.layer;
1506                }
1507                if (lhs.touchableRegion.top != rhs.touchableRegion.top) {
1508                    return rhs.touchableRegion.top - lhs.touchableRegion.top;
1509                }
1510                if (lhs.touchableRegion.left != rhs.touchableRegion.left) {
1511                    return rhs.touchableRegion.left - lhs.touchableRegion.left;
1512                }
1513                if (lhs.touchableRegion.right != rhs.touchableRegion.right) {
1514                    return rhs.touchableRegion.right - lhs.touchableRegion.right;
1515                }
1516                if (lhs.touchableRegion.bottom != rhs.touchableRegion.bottom) {
1517                    return rhs.touchableRegion.bottom - lhs.touchableRegion.bottom;
1518                }
1519                return 0;
1520            }
1521        };
1522
1523        public void recomputeBounds(boolean animate) {
1524            Rect magnifiedFrame = mTempRect1;
1525            magnifiedFrame.set(0, 0, 0, 0);
1526
1527            DisplayInfo displayInfo = mDisplayProvider.getDisplayInfo();
1528
1529            Rect availableFrame = mTempRect2;
1530            availableFrame.set(0, 0, displayInfo.logicalWidth, displayInfo.logicalHeight);
1531
1532            ArrayList<WindowInfo> infos = mTempWindowInfoList;
1533            infos.clear();
1534            int windowCount = 0;
1535            try {
1536                mWindowManagerService.getVisibleWindowsForDisplay(
1537                        mDisplayProvider.getDisplay().getDisplayId(), infos);
1538                Collections.sort(infos, mWindowInfoInverseComparator);
1539                windowCount = infos.size();
1540                for (int i = 0; i < windowCount; i++) {
1541                    WindowInfo info = infos.get(i);
1542                    if (info.type == WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY) {
1543                        continue;
1544                    }
1545                    Rect windowFrame = mTempRect3;
1546                    windowFrame.set(info.touchableRegion);
1547                    if (isWindowMagnified(info.type)) {
1548                        magnifiedFrame.union(windowFrame);
1549                        magnifiedFrame.intersect(availableFrame);
1550                    } else {
1551                        subtract(windowFrame, magnifiedFrame);
1552                        subtract(availableFrame, windowFrame);
1553                    }
1554                    if (availableFrame.equals(magnifiedFrame)) {
1555                        break;
1556                    }
1557                }
1558            } catch (RemoteException re) {
1559                /* ignore */
1560            } finally {
1561                for (int i = windowCount - 1; i >= 0; i--) {
1562                    infos.remove(i).recycle();
1563                }
1564            }
1565
1566            final int displayWidth = mDisplayProvider.getDisplayInfo().logicalWidth;
1567            final int displayHeight = mDisplayProvider.getDisplayInfo().logicalHeight;
1568            magnifiedFrame.intersect(0, 0, displayWidth, displayHeight);
1569
1570            resize(magnifiedFrame, animate);
1571        }
1572
1573        private boolean isWindowMagnified(int type) {
1574            return (type != WindowManager.LayoutParams.TYPE_NAVIGATION_BAR
1575                    && type != WindowManager.LayoutParams.TYPE_INPUT_METHOD
1576                    && type != WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG);
1577        }
1578
1579        public void rotationChanged() {
1580            mViewportFrame.rotationChanged();
1581        }
1582
1583        public Rect getBounds() {
1584            return mViewportFrame.getBounds();
1585        }
1586
1587        public void setFrameShown(boolean shown, boolean animate) {
1588            if (mViewportFrame.isShown() == shown) {
1589                return;
1590            }
1591            if (animate) {
1592                if (mShowHideFrameAnimator.isRunning()) {
1593                    mShowHideFrameAnimator.reverse();
1594                } else {
1595                    if (shown) {
1596                        mViewportFrame.show();
1597                        mShowHideFrameAnimator.start();
1598                    } else {
1599                        mShowHideFrameAnimator.reverse();
1600                    }
1601                }
1602            } else {
1603                mShowHideFrameAnimator.cancel();
1604                if (shown) {
1605                    mViewportFrame.show();
1606                } else {
1607                    mViewportFrame.hide();
1608                }
1609            }
1610        }
1611
1612        private void resize(Rect bounds, boolean animate) {
1613            if (mViewportFrame.getBounds().equals(bounds)) {
1614                return;
1615            }
1616            if (animate) {
1617                if (mResizeFrameAnimator.isRunning()) {
1618                    mResizeFrameAnimator.cancel();
1619                }
1620                mResizeFrameAnimator.setObjectValues(mViewportFrame.mBounds, bounds);
1621                mResizeFrameAnimator.start();
1622            } else {
1623                mViewportFrame.setBounds(bounds);
1624            }
1625        }
1626
1627        private boolean subtract(Rect lhs, Rect rhs) {
1628            if (lhs.right < rhs.left || lhs.left  > rhs.right
1629                    || lhs.bottom < rhs.top || lhs.top > rhs.bottom) {
1630                return false;
1631            }
1632            if (lhs.left < rhs.left) {
1633                lhs.right = rhs.left;
1634            }
1635            if (lhs.top < rhs.top) {
1636                lhs.bottom = rhs.top;
1637            }
1638            if (lhs.right > rhs.right) {
1639                lhs.left = rhs.right;
1640            }
1641            if (lhs.bottom > rhs.bottom) {
1642                lhs.top = rhs.bottom;
1643            }
1644            return true;
1645        }
1646
1647        private static final class ViewportWindow {
1648            private static final String WINDOW_TITLE = "Magnification Overlay";
1649
1650            private final WindowManager mWindowManager;
1651            private final DisplayProvider mDisplayProvider;
1652
1653            private final ContentView mWindowContent;
1654            private final WindowManager.LayoutParams mWindowParams;
1655
1656            private final Rect mBounds = new Rect();
1657            private boolean mShown;
1658            private int mAlpha;
1659
1660            public ViewportWindow(Context context, WindowManager windowManager,
1661                    DisplayProvider displayProvider) {
1662                mWindowManager = windowManager;
1663                mDisplayProvider = displayProvider;
1664
1665                ViewGroup.LayoutParams contentParams = new ViewGroup.LayoutParams(
1666                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
1667                mWindowContent = new ContentView(context);
1668                mWindowContent.setLayoutParams(contentParams);
1669                mWindowContent.setBackgroundColor(R.color.transparent);
1670
1671                mWindowParams = new WindowManager.LayoutParams(
1672                        WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY);
1673                mWindowParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1674                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1675                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
1676                mWindowParams.setTitle(WINDOW_TITLE);
1677                mWindowParams.gravity = Gravity.CENTER;
1678                mWindowParams.width = displayProvider.getDisplayInfo().logicalWidth;
1679                mWindowParams.height = displayProvider.getDisplayInfo().logicalHeight;
1680                mWindowParams.format = PixelFormat.TRANSLUCENT;
1681            }
1682
1683            public boolean isShown() {
1684                return mShown;
1685            }
1686
1687            public void show() {
1688                if (mShown) {
1689                    return;
1690                }
1691                mShown = true;
1692                mWindowManager.addView(mWindowContent, mWindowParams);
1693                if (DEBUG_VIEWPORT_WINDOW) {
1694                    Slog.i(LOG_TAG, "ViewportWindow shown.");
1695                }
1696            }
1697
1698            public void hide() {
1699                if (!mShown) {
1700                    return;
1701                }
1702                mShown = false;
1703                mWindowManager.removeView(mWindowContent);
1704                if (DEBUG_VIEWPORT_WINDOW) {
1705                    Slog.i(LOG_TAG, "ViewportWindow hidden.");
1706                }
1707            }
1708
1709            @SuppressWarnings("unused")
1710            // Called reflectively from an animator.
1711            public int getAlpha() {
1712                return mAlpha;
1713            }
1714
1715            @SuppressWarnings("unused")
1716            // Called reflectively from an animator.
1717            public void setAlpha(int alpha) {
1718                if (mAlpha == alpha) {
1719                    return;
1720                }
1721                mAlpha = alpha;
1722                if (mShown) {
1723                    mWindowContent.invalidate();
1724                }
1725                if (DEBUG_VIEWPORT_WINDOW) {
1726                    Slog.i(LOG_TAG, "ViewportFrame set alpha: " + alpha);
1727                }
1728            }
1729
1730            public Rect getBounds() {
1731                return mBounds;
1732            }
1733
1734            public void rotationChanged() {
1735                mWindowParams.width = mDisplayProvider.getDisplayInfo().logicalWidth;
1736                mWindowParams.height = mDisplayProvider.getDisplayInfo().logicalHeight;
1737                if (mShown) {
1738                    mWindowManager.updateViewLayout(mWindowContent, mWindowParams);
1739                }
1740            }
1741
1742            public void setBounds(Rect bounds) {
1743                if (mBounds.equals(bounds)) {
1744                    return;
1745                }
1746                mBounds.set(bounds);
1747                if (mShown) {
1748                    mWindowContent.invalidate();
1749                }
1750                if (DEBUG_VIEWPORT_WINDOW) {
1751                    Slog.i(LOG_TAG, "ViewportFrame set bounds: " + bounds);
1752                }
1753            }
1754
1755            private final class ContentView extends View {
1756                private final Drawable mHighlightFrame;
1757
1758                public ContentView(Context context) {
1759                    super(context);
1760                    mHighlightFrame = context.getResources().getDrawable(
1761                            R.drawable.magnified_region_frame);
1762                }
1763
1764                @Override
1765                public void onDraw(Canvas canvas) {
1766                    canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
1767                    mHighlightFrame.setBounds(mBounds);
1768                    mHighlightFrame.setAlpha(mAlpha);
1769                    mHighlightFrame.draw(canvas);
1770                }
1771            }
1772        }
1773    }
1774
1775    private static class DisplayProvider implements DisplayListener {
1776        private final WindowManager mWindowManager;
1777        private final DisplayManager mDisplayManager;
1778        private final Display mDefaultDisplay;
1779        private final DisplayInfo mDefaultDisplayInfo = new DisplayInfo();
1780
1781        public DisplayProvider(Context context, WindowManager windowManager) {
1782            mWindowManager = windowManager;
1783            mDisplayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
1784            mDefaultDisplay = mWindowManager.getDefaultDisplay();
1785            mDisplayManager.registerDisplayListener(this, null);
1786            updateDisplayInfo();
1787        }
1788
1789        public DisplayInfo getDisplayInfo() {
1790            return mDefaultDisplayInfo;
1791        }
1792
1793        public Display getDisplay() {
1794            return mDefaultDisplay;
1795        }
1796
1797        private void updateDisplayInfo() {
1798            if (!mDefaultDisplay.getDisplayInfo(mDefaultDisplayInfo)) {
1799                Slog.e(LOG_TAG, "Default display is not valid.");
1800            }
1801        }
1802
1803        public void destroy() {
1804            mDisplayManager.unregisterDisplayListener(this);
1805        }
1806
1807        @Override
1808        public void onDisplayAdded(int displayId) {
1809            /* do noting */
1810        }
1811
1812        @Override
1813        public void onDisplayRemoved(int displayId) {
1814            // Having no default display
1815        }
1816
1817        @Override
1818        public void onDisplayChanged(int displayId) {
1819            updateDisplayInfo();
1820        }
1821    }
1822}
1823