SurfaceView.java revision 30b06eb8b98b6e6dc685cf65ad4faa25a85008c5
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 android.content.Context; 20import android.content.res.Resources; 21import android.content.res.CompatibilityInfo.Translator; 22import android.graphics.Canvas; 23import android.graphics.PixelFormat; 24import android.graphics.PorterDuff; 25import android.graphics.Rect; 26import android.graphics.Region; 27import android.os.Handler; 28import android.os.Message; 29import android.os.RemoteException; 30import android.os.SystemClock; 31import android.os.ParcelFileDescriptor; 32import android.util.AttributeSet; 33import android.util.Config; 34import android.util.Log; 35 36import java.lang.ref.WeakReference; 37import java.util.ArrayList; 38import java.util.concurrent.locks.ReentrantLock; 39import java.lang.ref.WeakReference; 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>Access to the underlying surface is provided via the SurfaceHolder interface, 57 * which can be retrieved by calling {@link #getHolder}. 58 * 59 * <p>The Surface will be created for you while the SurfaceView's window is 60 * visible; you should implement {@link SurfaceHolder.Callback#surfaceCreated} 61 * and {@link SurfaceHolder.Callback#surfaceDestroyed} to discover when the 62 * Surface is created and destroyed as the window is shown and hidden. 63 * 64 * <p>One of the purposes of this class is to provide a surface in which a 65 * secondary thread can render in to the screen. If you are going to use it 66 * this way, you need to be aware of some threading semantics: 67 * 68 * <ul> 69 * <li> All SurfaceView and 70 * {@link SurfaceHolder.Callback SurfaceHolder.Callback} methods will be called 71 * from the thread running the SurfaceView's window (typically the main thread 72 * of the application). They thus need to correctly synchronize with any 73 * state that is also touched by the drawing thread. 74 * <li> You must ensure that the drawing thread only touches the underlying 75 * Surface while it is valid -- between 76 * {@link SurfaceHolder.Callback#surfaceCreated SurfaceHolder.Callback.surfaceCreated()} 77 * and 78 * {@link SurfaceHolder.Callback#surfaceDestroyed SurfaceHolder.Callback.surfaceDestroyed()}. 79 * </ul> 80 */ 81public class SurfaceView extends View { 82 static private final String TAG = "SurfaceView"; 83 static private final boolean DEBUG = false; 84 static private final boolean localLOGV = DEBUG ? true : Config.LOGV; 85 86 final ArrayList<SurfaceHolder.Callback> mCallbacks 87 = new ArrayList<SurfaceHolder.Callback>(); 88 89 final int[] mLocation = new int[2]; 90 91 final ReentrantLock mSurfaceLock = new ReentrantLock(); 92 final Surface mSurface = new Surface(); 93 boolean mDrawingStopped = true; 94 95 final WindowManager.LayoutParams mLayout 96 = new WindowManager.LayoutParams(); 97 IWindowSession mSession; 98 MyWindow mWindow; 99 final Rect mVisibleInsets = new Rect(); 100 final Rect mWinFrame = new Rect(); 101 final Rect mContentInsets = new Rect(); 102 103 static final int KEEP_SCREEN_ON_MSG = 1; 104 static final int GET_NEW_SURFACE_MSG = 2; 105 106 int mWindowType = WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA; 107 108 boolean mIsCreating = false; 109 110 final Handler mHandler = new Handler() { 111 @Override 112 public void handleMessage(Message msg) { 113 switch (msg.what) { 114 case KEEP_SCREEN_ON_MSG: { 115 setKeepScreenOn(msg.arg1 != 0); 116 } break; 117 case GET_NEW_SURFACE_MSG: { 118 handleGetNewSurface(); 119 } break; 120 } 121 } 122 }; 123 124 boolean mRequestedVisible = false; 125 int mRequestedWidth = -1; 126 int mRequestedHeight = -1; 127 int mRequestedFormat = PixelFormat.OPAQUE; 128 int mRequestedType = -1; 129 130 boolean mHaveFrame = false; 131 boolean mDestroyReportNeeded = false; 132 boolean mNewSurfaceNeeded = false; 133 long mLastLockTime = 0; 134 135 boolean mVisible = false; 136 int mLeft = -1; 137 int mTop = -1; 138 int mWidth = -1; 139 int mHeight = -1; 140 int mFormat = -1; 141 int mType = -1; 142 final Rect mSurfaceFrame = new Rect(); 143 private Translator mTranslator; 144 145 public SurfaceView(Context context) { 146 super(context); 147 setWillNotDraw(true); 148 } 149 150 public SurfaceView(Context context, AttributeSet attrs) { 151 super(context, attrs); 152 setWillNotDraw(true); 153 } 154 155 public SurfaceView(Context context, AttributeSet attrs, int defStyle) { 156 super(context, attrs, defStyle); 157 setWillNotDraw(true); 158 } 159 160 /** 161 * Return the SurfaceHolder providing access and control over this 162 * SurfaceView's underlying surface. 163 * 164 * @return SurfaceHolder The holder of the surface. 165 */ 166 public SurfaceHolder getHolder() { 167 return mSurfaceHolder; 168 } 169 170 @Override 171 protected void onAttachedToWindow() { 172 super.onAttachedToWindow(); 173 mParent.requestTransparentRegion(this); 174 mSession = getWindowSession(); 175 mLayout.token = getWindowToken(); 176 mLayout.setTitle("SurfaceView"); 177 } 178 179 @Override 180 protected void onWindowVisibilityChanged(int visibility) { 181 super.onWindowVisibilityChanged(visibility); 182 mRequestedVisible = visibility == VISIBLE; 183 updateWindow(false); 184 } 185 186 @Override 187 protected void onDetachedFromWindow() { 188 mRequestedVisible = false; 189 updateWindow(false); 190 mHaveFrame = false; 191 if (mWindow != null) { 192 try { 193 mSession.remove(mWindow); 194 } catch (RemoteException ex) { 195 } 196 mWindow = null; 197 } 198 mSession = null; 199 mLayout.token = null; 200 201 super.onDetachedFromWindow(); 202 } 203 204 @Override 205 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 206 int width = getDefaultSize(mRequestedWidth, widthMeasureSpec); 207 int height = getDefaultSize(mRequestedHeight, heightMeasureSpec); 208 setMeasuredDimension(width, height); 209 } 210 211 @Override 212 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 213 super.onScrollChanged(l, t, oldl, oldt); 214 updateWindow(false); 215 } 216 217 @Override 218 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 219 super.onSizeChanged(w, h, oldw, oldh); 220 updateWindow(false); 221 } 222 223 @Override 224 public boolean gatherTransparentRegion(Region region) { 225 boolean opaque = true; 226 if ((mPrivateFlags & SKIP_DRAW) == 0) { 227 // this view draws, remove it from the transparent region 228 opaque = super.gatherTransparentRegion(region); 229 } else if (region != null) { 230 int w = getWidth(); 231 int h = getHeight(); 232 if (w>0 && h>0) { 233 getLocationInWindow(mLocation); 234 // otherwise, punch a hole in the whole hierarchy 235 int l = mLocation[0]; 236 int t = mLocation[1]; 237 region.op(l, t, l+w, t+h, Region.Op.UNION); 238 } 239 } 240 if (PixelFormat.formatHasAlpha(mRequestedFormat)) { 241 opaque = false; 242 } 243 return opaque; 244 } 245 246 @Override 247 public void draw(Canvas canvas) { 248 // draw() is not called when SKIP_DRAW is set 249 if ((mPrivateFlags & SKIP_DRAW) == 0) { 250 // punch a whole in the view-hierarchy below us 251 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 252 } 253 super.draw(canvas); 254 } 255 256 @Override 257 protected void dispatchDraw(Canvas canvas) { 258 // if SKIP_DRAW is cleared, draw() has already punched a hole 259 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 260 // punch a whole in the view-hierarchy below us 261 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 262 } 263 // reposition ourselves where the surface is 264 mHaveFrame = true; 265 updateWindow(false); 266 super.dispatchDraw(canvas); 267 } 268 269 /** 270 * Hack to allow special layering of windows. The type is one of the 271 * types in WindowManager.LayoutParams. This is a hack so: 272 * @hide 273 */ 274 public void setWindowType(int type) { 275 mWindowType = type; 276 } 277 278 private void updateWindow(boolean force) { 279 if (!mHaveFrame) { 280 return; 281 } 282 ViewRoot viewRoot = (ViewRoot) getRootView().getParent(); 283 mTranslator = viewRoot.mTranslator; 284 285 Resources res = getContext().getResources(); 286 if (mTranslator != null || !res.getCompatibilityInfo().supportsScreen()) { 287 mSurface.setCompatibleDisplayMetrics(res.getDisplayMetrics(), mTranslator); 288 } 289 290 int myWidth = mRequestedWidth; 291 if (myWidth <= 0) myWidth = getWidth(); 292 int myHeight = mRequestedHeight; 293 if (myHeight <= 0) myHeight = getHeight(); 294 295 getLocationInWindow(mLocation); 296 final boolean creating = mWindow == null; 297 final boolean formatChanged = mFormat != mRequestedFormat; 298 final boolean sizeChanged = mWidth != myWidth || mHeight != myHeight; 299 final boolean visibleChanged = mVisible != mRequestedVisible 300 || mNewSurfaceNeeded; 301 final boolean typeChanged = mType != mRequestedType; 302 if (force || creating || formatChanged || sizeChanged || visibleChanged 303 || typeChanged || mLeft != mLocation[0] || mTop != mLocation[1]) { 304 305 if (localLOGV) Log.i(TAG, "Changes: creating=" + creating 306 + " format=" + formatChanged + " size=" + sizeChanged 307 + " visible=" + visibleChanged 308 + " left=" + (mLeft != mLocation[0]) 309 + " top=" + (mTop != mLocation[1])); 310 311 try { 312 final boolean visible = mVisible = mRequestedVisible; 313 mLeft = mLocation[0]; 314 mTop = mLocation[1]; 315 mWidth = myWidth; 316 mHeight = myHeight; 317 mFormat = mRequestedFormat; 318 mType = mRequestedType; 319 320 // Scaling/Translate window's layout here because mLayout is not used elsewhere. 321 322 // Places the window relative 323 mLayout.x = mLeft; 324 mLayout.y = mTop; 325 mLayout.width = getWidth(); 326 mLayout.height = getHeight(); 327 if (mTranslator != null) { 328 mTranslator.translateLayoutParamsInAppWindowToScreen(mLayout); 329 } 330 331 mLayout.format = mRequestedFormat; 332 mLayout.flags |=WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS 333 | WindowManager.LayoutParams.FLAG_SCALED 334 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 335 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE 336 ; 337 if (!getContext().getResources().getCompatibilityInfo().supportsScreen()) { 338 mLayout.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW; 339 } 340 341 mLayout.memoryType = mRequestedType; 342 343 if (mWindow == null) { 344 mWindow = new MyWindow(this); 345 mLayout.type = mWindowType; 346 mLayout.gravity = Gravity.LEFT|Gravity.TOP; 347 mSession.add(mWindow, mLayout, 348 mVisible ? VISIBLE : GONE, mContentInsets); 349 } 350 351 if (visibleChanged && (!visible || mNewSurfaceNeeded)) { 352 reportSurfaceDestroyed(); 353 } 354 355 mNewSurfaceNeeded = false; 356 357 mSurfaceLock.lock(); 358 mDrawingStopped = !visible; 359 360 final int relayoutResult = mSession.relayout( 361 mWindow, mLayout, mWidth, mHeight, 362 visible ? VISIBLE : GONE, false, mWinFrame, mContentInsets, 363 mVisibleInsets, mSurface); 364 365 if (localLOGV) Log.i(TAG, "New surface: " + mSurface 366 + ", vis=" + visible + ", frame=" + mWinFrame); 367 368 mSurfaceFrame.left = 0; 369 mSurfaceFrame.top = 0; 370 if (mTranslator == null) { 371 mSurfaceFrame.right = mWinFrame.width(); 372 mSurfaceFrame.bottom = mWinFrame.height(); 373 } else { 374 float appInvertedScale = mTranslator.applicationInvertedScale; 375 mSurfaceFrame.right = (int) (mWinFrame.width() * appInvertedScale + 0.5f); 376 mSurfaceFrame.bottom = (int) (mWinFrame.height() * appInvertedScale + 0.5f); 377 } 378 mSurfaceLock.unlock(); 379 380 try { 381 if (visible) { 382 mDestroyReportNeeded = true; 383 384 SurfaceHolder.Callback callbacks[]; 385 synchronized (mCallbacks) { 386 callbacks = new SurfaceHolder.Callback[mCallbacks.size()]; 387 mCallbacks.toArray(callbacks); 388 } 389 390 if (visibleChanged) { 391 mIsCreating = true; 392 for (SurfaceHolder.Callback c : callbacks) { 393 c.surfaceCreated(mSurfaceHolder); 394 } 395 } 396 if (creating || formatChanged || sizeChanged 397 || visibleChanged) { 398 for (SurfaceHolder.Callback c : callbacks) { 399 c.surfaceChanged(mSurfaceHolder, mFormat, mWidth, mHeight); 400 } 401 } 402 } 403 } finally { 404 mIsCreating = false; 405 if (creating || (relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) { 406 mSession.finishDrawing(mWindow); 407 } 408 } 409 } catch (RemoteException ex) { 410 } 411 if (localLOGV) Log.v( 412 TAG, "Layout: x=" + mLayout.x + " y=" + mLayout.y + 413 " w=" + mLayout.width + " h=" + mLayout.height + 414 ", frame=" + mSurfaceFrame); 415 } 416 } 417 418 private void reportSurfaceDestroyed() { 419 if (mDestroyReportNeeded) { 420 mDestroyReportNeeded = false; 421 SurfaceHolder.Callback callbacks[]; 422 synchronized (mCallbacks) { 423 callbacks = new SurfaceHolder.Callback[mCallbacks.size()]; 424 mCallbacks.toArray(callbacks); 425 } 426 for (SurfaceHolder.Callback c : callbacks) { 427 c.surfaceDestroyed(mSurfaceHolder); 428 } 429 } 430 super.onDetachedFromWindow(); 431 } 432 433 void handleGetNewSurface() { 434 mNewSurfaceNeeded = true; 435 updateWindow(false); 436 } 437 438 private static class MyWindow extends IWindow.Stub { 439 private final WeakReference<SurfaceView> mSurfaceView; 440 441 public MyWindow(SurfaceView surfaceView) { 442 mSurfaceView = new WeakReference<SurfaceView>(surfaceView); 443 } 444 445 public void resized(int w, int h, Rect coveredInsets, 446 Rect visibleInsets, boolean reportDraw) { 447 SurfaceView surfaceView = mSurfaceView.get(); 448 if (surfaceView != null) { 449 if (localLOGV) Log.v( 450 "SurfaceView", surfaceView + " got resized: w=" + 451 w + " h=" + h + ", cur w=" + mCurWidth + " h=" + mCurHeight); 452 synchronized (this) { 453 if (mCurWidth != w || mCurHeight != h) { 454 mCurWidth = w; 455 mCurHeight = h; 456 } 457 if (reportDraw) { 458 try { 459 surfaceView.mSession.finishDrawing(surfaceView.mWindow); 460 } catch (RemoteException e) { 461 } 462 } 463 } 464 } 465 } 466 467 public void dispatchKey(KeyEvent event) { 468 SurfaceView surfaceView = mSurfaceView.get(); 469 if (surfaceView != null) { 470 //Log.w("SurfaceView", "Unexpected key event in surface: " + event); 471 if (surfaceView.mSession != null && surfaceView.mSurface != null) { 472 try { 473 surfaceView.mSession.finishKey(surfaceView.mWindow); 474 } catch (RemoteException ex) { 475 } 476 } 477 } 478 } 479 480 public void dispatchPointer(MotionEvent event, long eventTime) { 481 Log.w("SurfaceView", "Unexpected pointer event in surface: " + event); 482 //if (mSession != null && mSurface != null) { 483 // try { 484 // //mSession.finishKey(mWindow); 485 // } catch (RemoteException ex) { 486 // } 487 //} 488 } 489 490 public void dispatchTrackball(MotionEvent event, long eventTime) { 491 Log.w("SurfaceView", "Unexpected trackball event in surface: " + event); 492 //if (mSession != null && mSurface != null) { 493 // try { 494 // //mSession.finishKey(mWindow); 495 // } catch (RemoteException ex) { 496 // } 497 //} 498 } 499 500 public void dispatchAppVisibility(boolean visible) { 501 // The point of SurfaceView is to let the app control the surface. 502 } 503 504 public void dispatchGetNewSurface() { 505 SurfaceView surfaceView = mSurfaceView.get(); 506 if (surfaceView != null) { 507 Message msg = surfaceView.mHandler.obtainMessage(GET_NEW_SURFACE_MSG); 508 surfaceView.mHandler.sendMessage(msg); 509 } 510 } 511 512 public void windowFocusChanged(boolean hasFocus, boolean touchEnabled) { 513 Log.w("SurfaceView", "Unexpected focus in surface: focus=" + hasFocus + ", touchEnabled=" + touchEnabled); 514 } 515 516 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) { 517 } 518 519 int mCurWidth = -1; 520 int mCurHeight = -1; 521 } 522 523 private SurfaceHolder mSurfaceHolder = new SurfaceHolder() { 524 525 private static final String LOG_TAG = "SurfaceHolder"; 526 private int mSaveCount; 527 528 public boolean isCreating() { 529 return mIsCreating; 530 } 531 532 public void addCallback(Callback callback) { 533 synchronized (mCallbacks) { 534 // This is a linear search, but in practice we'll 535 // have only a couple callbacks, so it doesn't matter. 536 if (mCallbacks.contains(callback) == false) { 537 mCallbacks.add(callback); 538 } 539 } 540 } 541 542 public void removeCallback(Callback callback) { 543 synchronized (mCallbacks) { 544 mCallbacks.remove(callback); 545 } 546 } 547 548 public void setFixedSize(int width, int height) { 549 if (mRequestedWidth != width || mRequestedHeight != height) { 550 mRequestedWidth = width; 551 mRequestedHeight = height; 552 requestLayout(); 553 } 554 } 555 556 public void setSizeFromLayout() { 557 if (mRequestedWidth != -1 || mRequestedHeight != -1) { 558 mRequestedWidth = mRequestedHeight = -1; 559 requestLayout(); 560 } 561 } 562 563 public void setFormat(int format) { 564 mRequestedFormat = format; 565 if (mWindow != null) { 566 updateWindow(false); 567 } 568 } 569 570 public void setType(int type) { 571 switch (type) { 572 case SURFACE_TYPE_NORMAL: 573 case SURFACE_TYPE_HARDWARE: 574 case SURFACE_TYPE_GPU: 575 case SURFACE_TYPE_PUSH_BUFFERS: 576 mRequestedType = type; 577 if (mWindow != null) { 578 updateWindow(false); 579 } 580 break; 581 } 582 } 583 584 public void setKeepScreenOn(boolean screenOn) { 585 Message msg = mHandler.obtainMessage(KEEP_SCREEN_ON_MSG); 586 msg.arg1 = screenOn ? 1 : 0; 587 mHandler.sendMessage(msg); 588 } 589 590 public Canvas lockCanvas() { 591 return internalLockCanvas(null); 592 } 593 594 public Canvas lockCanvas(Rect dirty) { 595 return internalLockCanvas(dirty); 596 } 597 598 private final Canvas internalLockCanvas(Rect dirty) { 599 if (mType == SURFACE_TYPE_PUSH_BUFFERS) { 600 throw new BadSurfaceTypeException( 601 "Surface type is SURFACE_TYPE_PUSH_BUFFERS"); 602 } 603 mSurfaceLock.lock(); 604 605 if (localLOGV) Log.i(TAG, "Locking canvas... stopped=" 606 + mDrawingStopped + ", win=" + mWindow); 607 608 Canvas c = null; 609 if (!mDrawingStopped && mWindow != null) { 610 Rect frame = dirty != null ? dirty : mSurfaceFrame; 611 try { 612 c = mSurface.lockCanvas(frame); 613 } catch (Exception e) { 614 Log.e(LOG_TAG, "Exception locking surface", e); 615 } 616 } 617 618 if (localLOGV) Log.i(TAG, "Returned canvas: " + c); 619 if (c != null) { 620 mLastLockTime = SystemClock.uptimeMillis(); 621 return c; 622 } 623 624 // If the Surface is not ready to be drawn, then return null, 625 // but throttle calls to this function so it isn't called more 626 // than every 100ms. 627 long now = SystemClock.uptimeMillis(); 628 long nextTime = mLastLockTime + 100; 629 if (nextTime > now) { 630 try { 631 Thread.sleep(nextTime-now); 632 } catch (InterruptedException e) { 633 } 634 now = SystemClock.uptimeMillis(); 635 } 636 mLastLockTime = now; 637 mSurfaceLock.unlock(); 638 639 return null; 640 } 641 642 public void unlockCanvasAndPost(Canvas canvas) { 643 mSurface.unlockCanvasAndPost(canvas); 644 mSurfaceLock.unlock(); 645 } 646 647 public Surface getSurface() { 648 return mSurface; 649 } 650 651 public Rect getSurfaceFrame() { 652 return mSurfaceFrame; 653 } 654 }; 655} 656