SurfaceView.java revision bac16fae7e6fceb1e516252ede673844b772e7c3
1/*
2 * Copyright (C) 2006 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 android.view;
18
19import com.android.internal.view.BaseIWindow;
20
21import android.content.Context;
22import android.content.res.Configuration;
23import android.content.res.CompatibilityInfo.Translator;
24import android.graphics.Canvas;
25import android.graphics.PixelFormat;
26import android.graphics.PorterDuff;
27import android.graphics.Rect;
28import android.graphics.Region;
29import android.os.Handler;
30import android.os.Message;
31import android.os.RemoteException;
32import android.os.SystemClock;
33import android.os.ParcelFileDescriptor;
34import android.util.AttributeSet;
35import android.util.Log;
36
37import java.lang.ref.WeakReference;
38import java.util.ArrayList;
39import java.util.concurrent.locks.ReentrantLock;
40
41/**
42 * Provides a dedicated drawing surface embedded inside of a view hierarchy.
43 * You can control the format of this surface and, if you like, its size; the
44 * SurfaceView takes care of placing the surface at the correct location on the
45 * screen
46 *
47 * <p>The surface is Z ordered so that it is behind the window holding its
48 * SurfaceView; the SurfaceView punches a hole in its window to allow its
49 * surface to be displayed. The view hierarchy will take care of correctly
50 * compositing with the Surface any siblings of the SurfaceView that would
51 * normally appear on top of it. This can be used to place overlays such as
52 * buttons on top of the Surface, though note however that it can have an
53 * impact on performance since a full alpha-blended composite will be performed
54 * each time the Surface changes.
55 *
56 * <p> The transparent region that makes the surface visible is based on the
57 * layout positions in the view hierarchy. If the post-layout transform
58 * properties are used to draw a sibling view on top of the SurfaceView, the
59 * view may not be properly composited with the surface.
60 *
61 * <p>Access to the underlying surface is provided via the SurfaceHolder interface,
62 * which can be retrieved by calling {@link #getHolder}.
63 *
64 * <p>The Surface will be created for you while the SurfaceView's window is
65 * visible; you should implement {@link SurfaceHolder.Callback#surfaceCreated}
66 * and {@link SurfaceHolder.Callback#surfaceDestroyed} to discover when the
67 * Surface is created and destroyed as the window is shown and hidden.
68 *
69 * <p>One of the purposes of this class is to provide a surface in which a
70 * secondary thread can render into the screen. If you are going to use it
71 * this way, you need to be aware of some threading semantics:
72 *
73 * <ul>
74 * <li> All SurfaceView and
75 * {@link SurfaceHolder.Callback SurfaceHolder.Callback} methods will be called
76 * from the thread running the SurfaceView's window (typically the main thread
77 * of the application). They thus need to correctly synchronize with any
78 * state that is also touched by the drawing thread.
79 * <li> You must ensure that the drawing thread only touches the underlying
80 * Surface while it is valid -- between
81 * {@link SurfaceHolder.Callback#surfaceCreated SurfaceHolder.Callback.surfaceCreated()}
82 * and
83 * {@link SurfaceHolder.Callback#surfaceDestroyed SurfaceHolder.Callback.surfaceDestroyed()}.
84 * </ul>
85 */
86public class SurfaceView extends View {
87    static private final String TAG = "SurfaceView";
88    static private final boolean DEBUG = false;
89
90    final ArrayList<SurfaceHolder.Callback> mCallbacks
91            = new ArrayList<SurfaceHolder.Callback>();
92
93    final int[] mLocation = new int[2];
94
95    final ReentrantLock mSurfaceLock = new ReentrantLock();
96    final Surface mSurface = new Surface();       // Current surface in use
97    final Surface mNewSurface = new Surface();    // New surface we are switching to
98    boolean mDrawingStopped = true;
99
100    final WindowManager.LayoutParams mLayout
101            = new WindowManager.LayoutParams();
102    IWindowSession mSession;
103    MyWindow mWindow;
104    final Rect mVisibleInsets = new Rect();
105    final Rect mWinFrame = new Rect();
106    final Rect mOverscanInsets = new Rect();
107    final Rect mContentInsets = new Rect();
108    final Configuration mConfiguration = new Configuration();
109
110    static final int KEEP_SCREEN_ON_MSG = 1;
111    static final int GET_NEW_SURFACE_MSG = 2;
112    static final int UPDATE_WINDOW_MSG = 3;
113
114    int mWindowType = WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
115
116    boolean mIsCreating = false;
117
118    final Handler mHandler = new Handler() {
119        @Override
120        public void handleMessage(Message msg) {
121            switch (msg.what) {
122                case KEEP_SCREEN_ON_MSG: {
123                    setKeepScreenOn(msg.arg1 != 0);
124                } break;
125                case GET_NEW_SURFACE_MSG: {
126                    handleGetNewSurface();
127                } break;
128                case UPDATE_WINDOW_MSG: {
129                    updateWindow(false, false);
130                } break;
131            }
132        }
133    };
134
135    final ViewTreeObserver.OnScrollChangedListener mScrollChangedListener
136            = new ViewTreeObserver.OnScrollChangedListener() {
137                    @Override
138                    public void onScrollChanged() {
139                        updateWindow(false, false);
140                    }
141            };
142
143    boolean mRequestedVisible = false;
144    boolean mWindowVisibility = false;
145    boolean mViewVisibility = false;
146    int mRequestedWidth = -1;
147    int mRequestedHeight = -1;
148    /* Set SurfaceView's format to 565 by default to maintain backward
149     * compatibility with applications assuming this format.
150     */
151    int mRequestedFormat = PixelFormat.RGB_565;
152
153    boolean mHaveFrame = false;
154    boolean mSurfaceCreated = false;
155    long mLastLockTime = 0;
156
157    boolean mVisible = false;
158    int mLeft = -1;
159    int mTop = -1;
160    int mWidth = -1;
161    int mHeight = -1;
162    int mFormat = -1;
163    final Rect mSurfaceFrame = new Rect();
164    int mLastSurfaceWidth = -1, mLastSurfaceHeight = -1;
165    boolean mUpdateWindowNeeded;
166    boolean mReportDrawNeeded;
167    private Translator mTranslator;
168
169    private final ViewTreeObserver.OnPreDrawListener mDrawListener =
170            new ViewTreeObserver.OnPreDrawListener() {
171                @Override
172                public boolean onPreDraw() {
173                    // reposition ourselves where the surface is
174                    mHaveFrame = getWidth() > 0 && getHeight() > 0;
175                    updateWindow(false, false);
176                    return true;
177                }
178            };
179    private boolean mGlobalListenersAdded;
180
181    public SurfaceView(Context context) {
182        super(context);
183        init();
184    }
185
186    public SurfaceView(Context context, AttributeSet attrs) {
187        super(context, attrs);
188        init();
189    }
190
191    public SurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
192        super(context, attrs, defStyleAttr);
193        init();
194    }
195
196    public SurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
197        super(context, attrs, defStyleAttr, defStyleRes);
198        init();
199    }
200
201    private void init() {
202        setWillNotDraw(true);
203    }
204
205    /**
206     * Return the SurfaceHolder providing access and control over this
207     * SurfaceView's underlying surface.
208     *
209     * @return SurfaceHolder The holder of the surface.
210     */
211    public SurfaceHolder getHolder() {
212        return mSurfaceHolder;
213    }
214
215    @Override
216    protected void onAttachedToWindow() {
217        super.onAttachedToWindow();
218        mParent.requestTransparentRegion(this);
219        mSession = getWindowSession();
220        mLayout.token = getWindowToken();
221        mLayout.setTitle("SurfaceView");
222        mViewVisibility = getVisibility() == VISIBLE;
223
224        if (!mGlobalListenersAdded) {
225            ViewTreeObserver observer = getViewTreeObserver();
226            observer.addOnScrollChangedListener(mScrollChangedListener);
227            observer.addOnPreDrawListener(mDrawListener);
228            mGlobalListenersAdded = true;
229        }
230    }
231
232    @Override
233    protected void onWindowVisibilityChanged(int visibility) {
234        super.onWindowVisibilityChanged(visibility);
235        mWindowVisibility = visibility == VISIBLE;
236        mRequestedVisible = mWindowVisibility && mViewVisibility;
237        updateWindow(false, false);
238    }
239
240    @Override
241    public void setVisibility(int visibility) {
242        super.setVisibility(visibility);
243        mViewVisibility = visibility == VISIBLE;
244        boolean newRequestedVisible = mWindowVisibility && mViewVisibility;
245        if (newRequestedVisible != mRequestedVisible) {
246            // our base class (View) invalidates the layout only when
247            // we go from/to the GONE state. However, SurfaceView needs
248            // to request a re-layout when the visibility changes at all.
249            // This is needed because the transparent region is computed
250            // as part of the layout phase, and it changes (obviously) when
251            // the visibility changes.
252            requestLayout();
253        }
254        mRequestedVisible = newRequestedVisible;
255        updateWindow(false, false);
256    }
257
258    @Override
259    protected void onDetachedFromWindow() {
260        if (mGlobalListenersAdded) {
261            ViewTreeObserver observer = getViewTreeObserver();
262            observer.removeOnScrollChangedListener(mScrollChangedListener);
263            observer.removeOnPreDrawListener(mDrawListener);
264            mGlobalListenersAdded = false;
265        }
266
267        mRequestedVisible = false;
268        updateWindow(false, false);
269        mHaveFrame = false;
270        if (mWindow != null) {
271            try {
272                mSession.remove(mWindow);
273            } catch (RemoteException ex) {
274                // Not much we can do here...
275            }
276            mWindow = null;
277        }
278        mSession = null;
279        mLayout.token = null;
280
281        super.onDetachedFromWindow();
282    }
283
284    @Override
285    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
286        int width = mRequestedWidth >= 0
287                ? resolveSizeAndState(mRequestedWidth, widthMeasureSpec, 0)
288                : getDefaultSize(0, widthMeasureSpec);
289        int height = mRequestedHeight >= 0
290                ? resolveSizeAndState(mRequestedHeight, heightMeasureSpec, 0)
291                : getDefaultSize(0, heightMeasureSpec);
292        setMeasuredDimension(width, height);
293    }
294
295    /** @hide */
296    @Override
297    protected boolean setFrame(int left, int top, int right, int bottom) {
298        boolean result = super.setFrame(left, top, right, bottom);
299        updateWindow(false, false);
300        return result;
301    }
302
303    @Override
304    public boolean gatherTransparentRegion(Region region) {
305        if (mWindowType == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
306            return super.gatherTransparentRegion(region);
307        }
308
309        boolean opaque = true;
310        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == 0) {
311            // this view draws, remove it from the transparent region
312            opaque = super.gatherTransparentRegion(region);
313        } else if (region != null) {
314            int w = getWidth();
315            int h = getHeight();
316            if (w>0 && h>0) {
317                getLocationInWindow(mLocation);
318                // otherwise, punch a hole in the whole hierarchy
319                int l = mLocation[0];
320                int t = mLocation[1];
321                region.op(l, t, l+w, t+h, Region.Op.UNION);
322            }
323        }
324        if (PixelFormat.formatHasAlpha(mRequestedFormat)) {
325            opaque = false;
326        }
327        return opaque;
328    }
329
330    @Override
331    public void draw(Canvas canvas) {
332        if (mWindowType != WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
333            // draw() is not called when SKIP_DRAW is set
334            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == 0) {
335                // punch a whole in the view-hierarchy below us
336                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
337            }
338        }
339        super.draw(canvas);
340    }
341
342    @Override
343    protected void dispatchDraw(Canvas canvas) {
344        if (mWindowType != WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
345            // if SKIP_DRAW is cleared, draw() has already punched a hole
346            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
347                // punch a whole in the view-hierarchy below us
348                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
349            }
350        }
351        super.dispatchDraw(canvas);
352    }
353
354    /**
355     * Control whether the surface view's surface is placed on top of another
356     * regular surface view in the window (but still behind the window itself).
357     * This is typically used to place overlays on top of an underlying media
358     * surface view.
359     *
360     * <p>Note that this must be set before the surface view's containing
361     * window is attached to the window manager.
362     *
363     * <p>Calling this overrides any previous call to {@link #setZOrderOnTop}.
364     */
365    public void setZOrderMediaOverlay(boolean isMediaOverlay) {
366        mWindowType = isMediaOverlay
367                ? WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY
368                : WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
369    }
370
371    /**
372     * Control whether the surface view's surface is placed on top of its
373     * window.  Normally it is placed behind the window, to allow it to
374     * (for the most part) appear to composite with the views in the
375     * hierarchy.  By setting this, you cause it to be placed above the
376     * window.  This means that none of the contents of the window this
377     * SurfaceView is in will be visible on top of its surface.
378     *
379     * <p>Note that this must be set before the surface view's containing
380     * window is attached to the window manager.
381     *
382     * <p>Calling this overrides any previous call to {@link #setZOrderMediaOverlay}.
383     */
384    public void setZOrderOnTop(boolean onTop) {
385        if (onTop) {
386            mWindowType = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
387            // ensures the surface is placed below the IME
388            mLayout.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
389        } else {
390            mWindowType = WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
391            mLayout.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
392        }
393    }
394
395    /**
396     * Control whether the surface view's content should be treated as secure,
397     * preventing it from appearing in screenshots or from being viewed on
398     * non-secure displays.
399     *
400     * <p>Note that this must be set before the surface view's containing
401     * window is attached to the window manager.
402     *
403     * <p>See {@link android.view.Display#FLAG_SECURE} for details.
404     *
405     * @param isSecure True if the surface view is secure.
406     */
407    public void setSecure(boolean isSecure) {
408        if (isSecure) {
409            mLayout.flags |= WindowManager.LayoutParams.FLAG_SECURE;
410        } else {
411            mLayout.flags &= ~WindowManager.LayoutParams.FLAG_SECURE;
412        }
413    }
414
415    /**
416     * Hack to allow special layering of windows.  The type is one of the
417     * types in WindowManager.LayoutParams.  This is a hack so:
418     * @hide
419     */
420    public void setWindowType(int type) {
421        mWindowType = type;
422    }
423
424    /**
425     * @hide
426     */
427    protected void updateWindow(boolean force, boolean redrawNeeded) {
428        if (!mHaveFrame) {
429            return;
430        }
431        ViewRootImpl viewRoot = getViewRootImpl();
432        if (viewRoot != null) {
433            mTranslator = viewRoot.mTranslator;
434        }
435
436        if (mTranslator != null) {
437            mSurface.setCompatibilityTranslator(mTranslator);
438        }
439
440        int myWidth = mRequestedWidth;
441        if (myWidth <= 0) myWidth = getWidth();
442        int myHeight = mRequestedHeight;
443        if (myHeight <= 0) myHeight = getHeight();
444
445        getLocationInWindow(mLocation);
446        final boolean creating = mWindow == null;
447        final boolean formatChanged = mFormat != mRequestedFormat;
448        final boolean sizeChanged = mWidth != myWidth || mHeight != myHeight;
449        final boolean visibleChanged = mVisible != mRequestedVisible;
450
451        if (force || creating || formatChanged || sizeChanged || visibleChanged
452            || mLeft != mLocation[0] || mTop != mLocation[1]
453            || mUpdateWindowNeeded || mReportDrawNeeded || redrawNeeded) {
454
455            if (DEBUG) Log.i(TAG, "Changes: creating=" + creating
456                    + " format=" + formatChanged + " size=" + sizeChanged
457                    + " visible=" + visibleChanged
458                    + " left=" + (mLeft != mLocation[0])
459                    + " top=" + (mTop != mLocation[1]));
460
461            try {
462                final boolean visible = mVisible = mRequestedVisible;
463                mLeft = mLocation[0];
464                mTop = mLocation[1];
465                mWidth = myWidth;
466                mHeight = myHeight;
467                mFormat = mRequestedFormat;
468
469                // Scaling/Translate window's layout here because mLayout is not used elsewhere.
470
471                // Places the window relative
472                mLayout.x = mLeft;
473                mLayout.y = mTop;
474                mLayout.width = getWidth();
475                mLayout.height = getHeight();
476                if (mTranslator != null) {
477                    mTranslator.translateLayoutParamsInAppWindowToScreen(mLayout);
478                }
479
480                mLayout.format = mRequestedFormat;
481                mLayout.flags |=WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
482                              | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
483                              | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
484                              | WindowManager.LayoutParams.FLAG_SCALED
485                              | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
486                              | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
487                              ;
488                if (!getContext().getResources().getCompatibilityInfo().supportsScreen()) {
489                    mLayout.privateFlags |=
490                            WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
491                }
492                mLayout.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION;
493
494                if (mWindow == null) {
495                    Display display = getDisplay();
496                    mWindow = new MyWindow(this);
497                    mLayout.type = mWindowType;
498                    mLayout.gravity = Gravity.START|Gravity.TOP;
499                    mSession.addToDisplayWithoutInputChannel(mWindow, mWindow.mSeq, mLayout,
500                            mVisible ? VISIBLE : GONE, display.getDisplayId(), mContentInsets);
501                }
502
503                boolean realSizeChanged;
504                boolean reportDrawNeeded;
505
506                int relayoutResult;
507
508                mSurfaceLock.lock();
509                try {
510                    mUpdateWindowNeeded = false;
511                    reportDrawNeeded = mReportDrawNeeded;
512                    mReportDrawNeeded = false;
513                    mDrawingStopped = !visible;
514
515                    if (DEBUG) Log.i(TAG, "Cur surface: " + mSurface);
516
517                    relayoutResult = mSession.relayout(
518                        mWindow, mWindow.mSeq, mLayout, mWidth, mHeight,
519                            visible ? VISIBLE : GONE,
520                            WindowManagerGlobal.RELAYOUT_DEFER_SURFACE_DESTROY,
521                            mWinFrame, mOverscanInsets, mContentInsets,
522                            mVisibleInsets, mConfiguration, mNewSurface);
523                    if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
524                        mReportDrawNeeded = true;
525                    }
526
527                    if (DEBUG) Log.i(TAG, "New surface: " + mNewSurface
528                            + ", vis=" + visible + ", frame=" + mWinFrame);
529
530                    mSurfaceFrame.left = 0;
531                    mSurfaceFrame.top = 0;
532                    if (mTranslator == null) {
533                        mSurfaceFrame.right = mWinFrame.width();
534                        mSurfaceFrame.bottom = mWinFrame.height();
535                    } else {
536                        float appInvertedScale = mTranslator.applicationInvertedScale;
537                        mSurfaceFrame.right = (int) (mWinFrame.width() * appInvertedScale + 0.5f);
538                        mSurfaceFrame.bottom = (int) (mWinFrame.height() * appInvertedScale + 0.5f);
539                    }
540
541                    final int surfaceWidth = mSurfaceFrame.right;
542                    final int surfaceHeight = mSurfaceFrame.bottom;
543                    realSizeChanged = mLastSurfaceWidth != surfaceWidth
544                            || mLastSurfaceHeight != surfaceHeight;
545                    mLastSurfaceWidth = surfaceWidth;
546                    mLastSurfaceHeight = surfaceHeight;
547                } finally {
548                    mSurfaceLock.unlock();
549                }
550
551                try {
552                    redrawNeeded |= creating | reportDrawNeeded;
553
554                    SurfaceHolder.Callback callbacks[] = null;
555
556                    final boolean surfaceChanged = (relayoutResult
557                            & WindowManagerGlobal.RELAYOUT_RES_SURFACE_CHANGED) != 0;
558                    if (mSurfaceCreated && (surfaceChanged || (!visible && visibleChanged))) {
559                        mSurfaceCreated = false;
560                        if (mSurface.isValid()) {
561                            if (DEBUG) Log.i(TAG, "visibleChanged -- surfaceDestroyed");
562                            callbacks = getSurfaceCallbacks();
563                            for (SurfaceHolder.Callback c : callbacks) {
564                                c.surfaceDestroyed(mSurfaceHolder);
565                            }
566                        }
567                    }
568
569                    mSurface.transferFrom(mNewSurface);
570
571                    if (visible && mSurface.isValid()) {
572                        if (!mSurfaceCreated && (surfaceChanged || visibleChanged)) {
573                            mSurfaceCreated = true;
574                            mIsCreating = true;
575                            if (DEBUG) Log.i(TAG, "visibleChanged -- surfaceCreated");
576                            if (callbacks == null) {
577                                callbacks = getSurfaceCallbacks();
578                            }
579                            for (SurfaceHolder.Callback c : callbacks) {
580                                c.surfaceCreated(mSurfaceHolder);
581                            }
582                        }
583                        if (creating || formatChanged || sizeChanged
584                                || visibleChanged || realSizeChanged) {
585                            if (DEBUG) Log.i(TAG, "surfaceChanged -- format=" + mFormat
586                                    + " w=" + myWidth + " h=" + myHeight);
587                            if (callbacks == null) {
588                                callbacks = getSurfaceCallbacks();
589                            }
590                            for (SurfaceHolder.Callback c : callbacks) {
591                                c.surfaceChanged(mSurfaceHolder, mFormat, myWidth, myHeight);
592                            }
593                        }
594                        if (redrawNeeded) {
595                            if (DEBUG) Log.i(TAG, "surfaceRedrawNeeded");
596                            if (callbacks == null) {
597                                callbacks = getSurfaceCallbacks();
598                            }
599                            for (SurfaceHolder.Callback c : callbacks) {
600                                if (c instanceof SurfaceHolder.Callback2) {
601                                    ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
602                                            mSurfaceHolder);
603                                }
604                            }
605                        }
606                    }
607                } finally {
608                    mIsCreating = false;
609                    if (redrawNeeded) {
610                        if (DEBUG) Log.i(TAG, "finishedDrawing");
611                        mSession.finishDrawing(mWindow);
612                    }
613                    mSession.performDeferredDestroy(mWindow);
614                }
615            } catch (RemoteException ex) {
616            }
617            if (DEBUG) Log.v(
618                TAG, "Layout: x=" + mLayout.x + " y=" + mLayout.y +
619                " w=" + mLayout.width + " h=" + mLayout.height +
620                ", frame=" + mSurfaceFrame);
621        }
622    }
623
624    private SurfaceHolder.Callback[] getSurfaceCallbacks() {
625        SurfaceHolder.Callback callbacks[];
626        synchronized (mCallbacks) {
627            callbacks = new SurfaceHolder.Callback[mCallbacks.size()];
628            mCallbacks.toArray(callbacks);
629        }
630        return callbacks;
631    }
632
633    void handleGetNewSurface() {
634        updateWindow(false, false);
635    }
636
637    /**
638     * Check to see if the surface has fixed size dimensions or if the surface's
639     * dimensions are dimensions are dependent on its current layout.
640     *
641     * @return true if the surface has dimensions that are fixed in size
642     * @hide
643     */
644    public boolean isFixedSize() {
645        return (mRequestedWidth != -1 || mRequestedHeight != -1);
646    }
647
648    private static class MyWindow extends BaseIWindow {
649        private final WeakReference<SurfaceView> mSurfaceView;
650
651        public MyWindow(SurfaceView surfaceView) {
652            mSurfaceView = new WeakReference<SurfaceView>(surfaceView);
653        }
654
655        @Override
656        public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
657                Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
658            SurfaceView surfaceView = mSurfaceView.get();
659            if (surfaceView != null) {
660                if (DEBUG) Log.v(
661                        "SurfaceView", surfaceView + " got resized: w=" + frame.width()
662                        + " h=" + frame.height() + ", cur w=" + mCurWidth + " h=" + mCurHeight);
663                surfaceView.mSurfaceLock.lock();
664                try {
665                    if (reportDraw) {
666                        surfaceView.mUpdateWindowNeeded = true;
667                        surfaceView.mReportDrawNeeded = true;
668                        surfaceView.mHandler.sendEmptyMessage(UPDATE_WINDOW_MSG);
669                    } else if (surfaceView.mWinFrame.width() != frame.width()
670                            || surfaceView.mWinFrame.height() != frame.height()) {
671                        surfaceView.mUpdateWindowNeeded = true;
672                        surfaceView.mHandler.sendEmptyMessage(UPDATE_WINDOW_MSG);
673                    }
674                } finally {
675                    surfaceView.mSurfaceLock.unlock();
676                }
677            }
678        }
679
680        @Override
681        public void dispatchAppVisibility(boolean visible) {
682            // The point of SurfaceView is to let the app control the surface.
683        }
684
685        @Override
686        public void dispatchGetNewSurface() {
687            SurfaceView surfaceView = mSurfaceView.get();
688            if (surfaceView != null) {
689                Message msg = surfaceView.mHandler.obtainMessage(GET_NEW_SURFACE_MSG);
690                surfaceView.mHandler.sendMessage(msg);
691            }
692        }
693
694        @Override
695        public void windowFocusChanged(boolean hasFocus, boolean touchEnabled) {
696            Log.w("SurfaceView", "Unexpected focus in surface: focus=" + hasFocus + ", touchEnabled=" + touchEnabled);
697        }
698
699        @Override
700        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
701        }
702
703        int mCurWidth = -1;
704        int mCurHeight = -1;
705    }
706
707    private final SurfaceHolder mSurfaceHolder = new SurfaceHolder() {
708
709        private static final String LOG_TAG = "SurfaceHolder";
710
711        @Override
712        public boolean isCreating() {
713            return mIsCreating;
714        }
715
716        @Override
717        public void addCallback(Callback callback) {
718            synchronized (mCallbacks) {
719                // This is a linear search, but in practice we'll
720                // have only a couple callbacks, so it doesn't matter.
721                if (mCallbacks.contains(callback) == false) {
722                    mCallbacks.add(callback);
723                }
724            }
725        }
726
727        @Override
728        public void removeCallback(Callback callback) {
729            synchronized (mCallbacks) {
730                mCallbacks.remove(callback);
731            }
732        }
733
734        @Override
735        public void setFixedSize(int width, int height) {
736            if (mRequestedWidth != width || mRequestedHeight != height) {
737                mRequestedWidth = width;
738                mRequestedHeight = height;
739                requestLayout();
740            }
741        }
742
743        @Override
744        public void setSizeFromLayout() {
745            if (mRequestedWidth != -1 || mRequestedHeight != -1) {
746                mRequestedWidth = mRequestedHeight = -1;
747                requestLayout();
748            }
749        }
750
751        @Override
752        public void setFormat(int format) {
753
754            // for backward compatibility reason, OPAQUE always
755            // means 565 for SurfaceView
756            if (format == PixelFormat.OPAQUE)
757                format = PixelFormat.RGB_565;
758
759            mRequestedFormat = format;
760            if (mWindow != null) {
761                updateWindow(false, false);
762            }
763        }
764
765        /**
766         * @deprecated setType is now ignored.
767         */
768        @Override
769        @Deprecated
770        public void setType(int type) { }
771
772        @Override
773        public void setKeepScreenOn(boolean screenOn) {
774            Message msg = mHandler.obtainMessage(KEEP_SCREEN_ON_MSG);
775            msg.arg1 = screenOn ? 1 : 0;
776            mHandler.sendMessage(msg);
777        }
778
779        /**
780         * Gets a {@link Canvas} for drawing into the SurfaceView's Surface
781         *
782         * After drawing into the provided {@link Canvas}, the caller must
783         * invoke {@link #unlockCanvasAndPost} to post the new contents to the surface.
784         *
785         * The caller must redraw the entire surface.
786         * @return A canvas for drawing into the surface.
787         */
788        @Override
789        public Canvas lockCanvas() {
790            return internalLockCanvas(null);
791        }
792
793        /**
794         * Gets a {@link Canvas} for drawing into the SurfaceView's Surface
795         *
796         * After drawing into the provided {@link Canvas}, the caller must
797         * invoke {@link #unlockCanvasAndPost} to post the new contents to the surface.
798         *
799         * @param inOutDirty A rectangle that represents the dirty region that the caller wants
800         * to redraw.  This function may choose to expand the dirty rectangle if for example
801         * the surface has been resized or if the previous contents of the surface were
802         * not available.  The caller must redraw the entire dirty region as represented
803         * by the contents of the inOutDirty rectangle upon return from this function.
804         * The caller may also pass <code>null</code> instead, in the case where the
805         * entire surface should be redrawn.
806         * @return A canvas for drawing into the surface.
807         */
808        @Override
809        public Canvas lockCanvas(Rect inOutDirty) {
810            return internalLockCanvas(inOutDirty);
811        }
812
813        private final Canvas internalLockCanvas(Rect dirty) {
814            mSurfaceLock.lock();
815
816            if (DEBUG) Log.i(TAG, "Locking canvas... stopped="
817                    + mDrawingStopped + ", win=" + mWindow);
818
819            Canvas c = null;
820            if (!mDrawingStopped && mWindow != null) {
821                try {
822                    c = mSurface.lockCanvas(dirty);
823                } catch (Exception e) {
824                    Log.e(LOG_TAG, "Exception locking surface", e);
825                }
826            }
827
828            if (DEBUG) Log.i(TAG, "Returned canvas: " + c);
829            if (c != null) {
830                mLastLockTime = SystemClock.uptimeMillis();
831                return c;
832            }
833
834            // If the Surface is not ready to be drawn, then return null,
835            // but throttle calls to this function so it isn't called more
836            // than every 100ms.
837            long now = SystemClock.uptimeMillis();
838            long nextTime = mLastLockTime + 100;
839            if (nextTime > now) {
840                try {
841                    Thread.sleep(nextTime-now);
842                } catch (InterruptedException e) {
843                }
844                now = SystemClock.uptimeMillis();
845            }
846            mLastLockTime = now;
847            mSurfaceLock.unlock();
848
849            return null;
850        }
851
852        /**
853         * Posts the new contents of the {@link Canvas} to the surface and
854         * releases the {@link Canvas}.
855         *
856         * @param canvas The canvas previously obtained from {@link #lockCanvas}.
857         */
858        @Override
859        public void unlockCanvasAndPost(Canvas canvas) {
860            mSurface.unlockCanvasAndPost(canvas);
861            mSurfaceLock.unlock();
862        }
863
864        @Override
865        public Surface getSurface() {
866            return mSurface;
867        }
868
869        @Override
870        public Rect getSurfaceFrame() {
871            return mSurfaceFrame;
872        }
873    };
874}
875