SurfaceFlinger.cpp revision 59119e658a12279e8fff508f8773843de2d90917
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include <stdlib.h> 18#include <stdio.h> 19#include <stdint.h> 20#include <unistd.h> 21#include <fcntl.h> 22#include <errno.h> 23#include <math.h> 24#include <limits.h> 25#include <sys/types.h> 26#include <sys/stat.h> 27#include <sys/ioctl.h> 28 29#include <cutils/log.h> 30#include <cutils/properties.h> 31 32#include <binder/IPCThreadState.h> 33#include <binder/IServiceManager.h> 34#include <binder/MemoryHeapBase.h> 35 36#include <utils/String8.h> 37#include <utils/String16.h> 38#include <utils/StopWatch.h> 39 40#include <ui/GraphicBufferAllocator.h> 41#include <ui/GraphicLog.h> 42#include <ui/PixelFormat.h> 43 44#include <pixelflinger/pixelflinger.h> 45#include <GLES/gl.h> 46 47#include "clz.h" 48#include "GLExtensions.h" 49#include "Layer.h" 50#include "LayerBlur.h" 51#include "LayerBuffer.h" 52#include "LayerDim.h" 53#include "SurfaceFlinger.h" 54 55#include "DisplayHardware/DisplayHardware.h" 56 57/* ideally AID_GRAPHICS would be in a semi-public header 58 * or there would be a way to map a user/group name to its id 59 */ 60#ifndef AID_GRAPHICS 61#define AID_GRAPHICS 1003 62#endif 63 64#define DISPLAY_COUNT 1 65 66namespace android { 67// --------------------------------------------------------------------------- 68 69SurfaceFlinger::SurfaceFlinger() 70 : BnSurfaceComposer(), Thread(false), 71 mTransactionFlags(0), 72 mTransactionCount(0), 73 mResizeTransationPending(false), 74 mLayersRemoved(false), 75 mBootTime(systemTime()), 76 mHardwareTest("android.permission.HARDWARE_TEST"), 77 mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"), 78 mReadFramebuffer("android.permission.READ_FRAME_BUFFER"), 79 mDump("android.permission.DUMP"), 80 mVisibleRegionsDirty(false), 81 mDeferReleaseConsole(false), 82 mFreezeDisplay(false), 83 mFreezeCount(0), 84 mFreezeDisplayTime(0), 85 mDebugRegion(0), 86 mDebugBackground(0), 87 mDebugInSwapBuffers(0), 88 mLastSwapBufferTime(0), 89 mDebugInTransaction(0), 90 mLastTransactionTime(0), 91 mBootFinished(false), 92 mConsoleSignals(0), 93 mSecureFrameBuffer(0) 94{ 95 init(); 96} 97 98void SurfaceFlinger::init() 99{ 100 LOGI("SurfaceFlinger is starting"); 101 102 // debugging stuff... 103 char value[PROPERTY_VALUE_MAX]; 104 property_get("debug.sf.showupdates", value, "0"); 105 mDebugRegion = atoi(value); 106 property_get("debug.sf.showbackground", value, "0"); 107 mDebugBackground = atoi(value); 108 109 LOGI_IF(mDebugRegion, "showupdates enabled"); 110 LOGI_IF(mDebugBackground, "showbackground enabled"); 111} 112 113SurfaceFlinger::~SurfaceFlinger() 114{ 115 glDeleteTextures(1, &mWormholeTexName); 116} 117 118overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const 119{ 120 return graphicPlane(0).displayHardware().getOverlayEngine(); 121} 122 123sp<IMemoryHeap> SurfaceFlinger::getCblk() const 124{ 125 return mServerHeap; 126} 127 128sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() 129{ 130 sp<ISurfaceComposerClient> bclient; 131 sp<Client> client(new Client(this)); 132 status_t err = client->initCheck(); 133 if (err == NO_ERROR) { 134 bclient = client; 135 } 136 return bclient; 137} 138 139sp<ISurfaceComposerClient> SurfaceFlinger::createClientConnection() 140{ 141 sp<ISurfaceComposerClient> bclient; 142 sp<UserClient> client(new UserClient(this)); 143 status_t err = client->initCheck(); 144 if (err == NO_ERROR) { 145 bclient = client; 146 } 147 return bclient; 148} 149 150 151const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const 152{ 153 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy); 154 const GraphicPlane& plane(mGraphicPlanes[dpy]); 155 return plane; 156} 157 158GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) 159{ 160 return const_cast<GraphicPlane&>( 161 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy)); 162} 163 164void SurfaceFlinger::bootFinished() 165{ 166 const nsecs_t now = systemTime(); 167 const nsecs_t duration = now - mBootTime; 168 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) ); 169 mBootFinished = true; 170 property_set("ctl.stop", "bootanim"); 171} 172 173void SurfaceFlinger::onFirstRef() 174{ 175 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY); 176 177 // Wait for the main thread to be done with its initialization 178 mReadyToRunBarrier.wait(); 179} 180 181static inline uint16_t pack565(int r, int g, int b) { 182 return (r<<11)|(g<<5)|b; 183} 184 185status_t SurfaceFlinger::readyToRun() 186{ 187 LOGI( "SurfaceFlinger's main thread ready to run. " 188 "Initializing graphics H/W..."); 189 190 // we only support one display currently 191 int dpy = 0; 192 193 { 194 // initialize the main display 195 GraphicPlane& plane(graphicPlane(dpy)); 196 DisplayHardware* const hw = new DisplayHardware(this, dpy); 197 plane.setDisplayHardware(hw); 198 } 199 200 // create the shared control-block 201 mServerHeap = new MemoryHeapBase(4096, 202 MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap"); 203 LOGE_IF(mServerHeap==0, "can't create shared memory dealer"); 204 205 mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase()); 206 LOGE_IF(mServerCblk==0, "can't get to shared control block's address"); 207 208 new(mServerCblk) surface_flinger_cblk_t; 209 210 // initialize primary screen 211 // (other display should be initialized in the same manner, but 212 // asynchronously, as they could come and go. None of this is supported 213 // yet). 214 const GraphicPlane& plane(graphicPlane(dpy)); 215 const DisplayHardware& hw = plane.displayHardware(); 216 const uint32_t w = hw.getWidth(); 217 const uint32_t h = hw.getHeight(); 218 const uint32_t f = hw.getFormat(); 219 hw.makeCurrent(); 220 221 // initialize the shared control block 222 mServerCblk->connected |= 1<<dpy; 223 display_cblk_t* dcblk = mServerCblk->displays + dpy; 224 memset(dcblk, 0, sizeof(display_cblk_t)); 225 dcblk->w = plane.getWidth(); 226 dcblk->h = plane.getHeight(); 227 dcblk->format = f; 228 dcblk->orientation = ISurfaceComposer::eOrientationDefault; 229 dcblk->xdpi = hw.getDpiX(); 230 dcblk->ydpi = hw.getDpiY(); 231 dcblk->fps = hw.getRefreshRate(); 232 dcblk->density = hw.getDensity(); 233 234 // Initialize OpenGL|ES 235 glPixelStorei(GL_UNPACK_ALIGNMENT, 4); 236 glPixelStorei(GL_PACK_ALIGNMENT, 4); 237 glEnableClientState(GL_VERTEX_ARRAY); 238 glEnable(GL_SCISSOR_TEST); 239 glShadeModel(GL_FLAT); 240 glDisable(GL_DITHER); 241 glDisable(GL_CULL_FACE); 242 243 const uint16_t g0 = pack565(0x0F,0x1F,0x0F); 244 const uint16_t g1 = pack565(0x17,0x2f,0x17); 245 const uint16_t textureData[4] = { g0, g1, g1, g0 }; 246 glGenTextures(1, &mWormholeTexName); 247 glBindTexture(GL_TEXTURE_2D, mWormholeTexName); 248 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 249 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 250 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 251 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 252 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, 253 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData); 254 255 glViewport(0, 0, w, h); 256 glMatrixMode(GL_PROJECTION); 257 glLoadIdentity(); 258 glOrthof(0, w, h, 0, 0, 1); 259 260 LayerDim::initDimmer(this, w, h); 261 262 mReadyToRunBarrier.open(); 263 264 /* 265 * We're now ready to accept clients... 266 */ 267 268 // start boot animation 269 property_set("ctl.start", "bootanim"); 270 271 return NO_ERROR; 272} 273 274// ---------------------------------------------------------------------------- 275#if 0 276#pragma mark - 277#pragma mark Events Handler 278#endif 279 280void SurfaceFlinger::waitForEvent() 281{ 282 while (true) { 283 nsecs_t timeout = -1; 284 const nsecs_t freezeDisplayTimeout = ms2ns(5000); 285 if (UNLIKELY(isFrozen())) { 286 // wait 5 seconds 287 const nsecs_t now = systemTime(); 288 if (mFreezeDisplayTime == 0) { 289 mFreezeDisplayTime = now; 290 } 291 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime); 292 timeout = waitTime>0 ? waitTime : 0; 293 } 294 295 sp<MessageBase> msg = mEventQueue.waitMessage(timeout); 296 297 // see if we timed out 298 if (isFrozen()) { 299 const nsecs_t now = systemTime(); 300 nsecs_t frozenTime = (now - mFreezeDisplayTime); 301 if (frozenTime >= freezeDisplayTimeout) { 302 // we timed out and are still frozen 303 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d", 304 mFreezeDisplay, mFreezeCount); 305 mFreezeDisplayTime = 0; 306 mFreezeCount = 0; 307 mFreezeDisplay = false; 308 } 309 } 310 311 if (msg != 0) { 312 switch (msg->what) { 313 case MessageQueue::INVALIDATE: 314 // invalidate message, just return to the main loop 315 return; 316 } 317 } 318 } 319} 320 321void SurfaceFlinger::signalEvent() { 322 mEventQueue.invalidate(); 323} 324 325void SurfaceFlinger::signal() const { 326 // this is the IPC call 327 const_cast<SurfaceFlinger*>(this)->signalEvent(); 328} 329 330status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg, 331 nsecs_t reltime, uint32_t flags) 332{ 333 return mEventQueue.postMessage(msg, reltime, flags); 334} 335 336status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, 337 nsecs_t reltime, uint32_t flags) 338{ 339 status_t res = mEventQueue.postMessage(msg, reltime, flags); 340 if (res == NO_ERROR) { 341 msg->wait(); 342 } 343 return res; 344} 345 346// ---------------------------------------------------------------------------- 347#if 0 348#pragma mark - 349#pragma mark Main loop 350#endif 351 352bool SurfaceFlinger::threadLoop() 353{ 354 waitForEvent(); 355 356 // check for transactions 357 if (UNLIKELY(mConsoleSignals)) { 358 handleConsoleEvents(); 359 } 360 361 if (LIKELY(mTransactionCount == 0)) { 362 // if we're in a global transaction, don't do anything. 363 const uint32_t mask = eTransactionNeeded | eTraversalNeeded; 364 uint32_t transactionFlags = getTransactionFlags(mask); 365 if (LIKELY(transactionFlags)) { 366 handleTransaction(transactionFlags); 367 } 368 } 369 370 // post surfaces (if needed) 371 handlePageFlip(); 372 373 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 374 if (LIKELY(hw.canDraw() && !isFrozen())) { 375 // repaint the framebuffer (if needed) 376 377 const int index = hw.getCurrentBufferIndex(); 378 GraphicLog& logger(GraphicLog::getInstance()); 379 380 logger.log(GraphicLog::SF_REPAINT, index); 381 handleRepaint(); 382 383 // inform the h/w that we're done compositing 384 logger.log(GraphicLog::SF_COMPOSITION_COMPLETE, index); 385 hw.compositionComplete(); 386 387 // release the clients before we flip ('cause flip might block) 388 logger.log(GraphicLog::SF_UNLOCK_CLIENTS, index); 389 unlockClients(); 390 391 logger.log(GraphicLog::SF_SWAP_BUFFERS, index); 392 postFramebuffer(); 393 394 logger.log(GraphicLog::SF_REPAINT_DONE, index); 395 } else { 396 // pretend we did the post 397 unlockClients(); 398 usleep(16667); // 60 fps period 399 } 400 return true; 401} 402 403void SurfaceFlinger::postFramebuffer() 404{ 405 if (!mInvalidRegion.isEmpty()) { 406 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 407 const nsecs_t now = systemTime(); 408 mDebugInSwapBuffers = now; 409 hw.flip(mInvalidRegion); 410 mLastSwapBufferTime = systemTime() - now; 411 mDebugInSwapBuffers = 0; 412 mInvalidRegion.clear(); 413 } 414} 415 416void SurfaceFlinger::handleConsoleEvents() 417{ 418 // something to do with the console 419 const DisplayHardware& hw = graphicPlane(0).displayHardware(); 420 421 int what = android_atomic_and(0, &mConsoleSignals); 422 if (what & eConsoleAcquired) { 423 hw.acquireScreen(); 424 } 425 426 if (mDeferReleaseConsole && hw.isScreenAcquired()) { 427 // We got the release signal before the acquire signal 428 mDeferReleaseConsole = false; 429 hw.releaseScreen(); 430 } 431 432 if (what & eConsoleReleased) { 433 if (hw.isScreenAcquired()) { 434 hw.releaseScreen(); 435 } else { 436 mDeferReleaseConsole = true; 437 } 438 } 439 440 mDirtyRegion.set(hw.bounds()); 441} 442 443void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 444{ 445 Vector< sp<LayerBase> > ditchedLayers; 446 447 /* 448 * Perform and commit the transaction 449 */ 450 451 { // scope for the lock 452 Mutex::Autolock _l(mStateLock); 453 const nsecs_t now = systemTime(); 454 mDebugInTransaction = now; 455 handleTransactionLocked(transactionFlags, ditchedLayers); 456 mLastTransactionTime = systemTime() - now; 457 mDebugInTransaction = 0; 458 // here the transaction has been committed 459 } 460 461 /* 462 * Clean-up all layers that went away 463 * (do this without the lock held) 464 */ 465 const size_t count = ditchedLayers.size(); 466 for (size_t i=0 ; i<count ; i++) { 467 if (ditchedLayers[i] != 0) { 468 //LOGD("ditching layer %p", ditchedLayers[i].get()); 469 ditchedLayers[i]->ditch(); 470 } 471 } 472} 473 474void SurfaceFlinger::handleTransactionLocked( 475 uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers) 476{ 477 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 478 const size_t count = currentLayers.size(); 479 480 /* 481 * Traversal of the children 482 * (perform the transaction for each of them if needed) 483 */ 484 485 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded; 486 if (layersNeedTransaction) { 487 for (size_t i=0 ; i<count ; i++) { 488 const sp<LayerBase>& layer = currentLayers[i]; 489 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 490 if (!trFlags) continue; 491 492 const uint32_t flags = layer->doTransaction(0); 493 if (flags & Layer::eVisibleRegion) 494 mVisibleRegionsDirty = true; 495 } 496 } 497 498 /* 499 * Perform our own transaction if needed 500 */ 501 502 if (transactionFlags & eTransactionNeeded) { 503 if (mCurrentState.orientation != mDrawingState.orientation) { 504 // the orientation has changed, recompute all visible regions 505 // and invalidate everything. 506 507 const int dpy = 0; 508 const int orientation = mCurrentState.orientation; 509 const uint32_t type = mCurrentState.orientationType; 510 GraphicPlane& plane(graphicPlane(dpy)); 511 plane.setOrientation(orientation); 512 513 // update the shared control block 514 const DisplayHardware& hw(plane.displayHardware()); 515 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy; 516 dcblk->orientation = orientation; 517 dcblk->w = plane.getWidth(); 518 dcblk->h = plane.getHeight(); 519 520 mVisibleRegionsDirty = true; 521 mDirtyRegion.set(hw.bounds()); 522 } 523 524 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) { 525 // freezing or unfreezing the display -> trigger animation if needed 526 mFreezeDisplay = mCurrentState.freezeDisplay; 527 if (mFreezeDisplay) 528 mFreezeDisplayTime = 0; 529 } 530 531 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) { 532 // layers have been added 533 mVisibleRegionsDirty = true; 534 } 535 536 // some layers might have been removed, so 537 // we need to update the regions they're exposing. 538 if (mLayersRemoved) { 539 mLayersRemoved = false; 540 mVisibleRegionsDirty = true; 541 const LayerVector& previousLayers(mDrawingState.layersSortedByZ); 542 const size_t count = previousLayers.size(); 543 for (size_t i=0 ; i<count ; i++) { 544 const sp<LayerBase>& layer(previousLayers[i]); 545 if (currentLayers.indexOf( layer ) < 0) { 546 // this layer is not visible anymore 547 ditchedLayers.add(layer); 548 mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen); 549 } 550 } 551 } 552 } 553 554 commitTransaction(); 555} 556 557sp<FreezeLock> SurfaceFlinger::getFreezeLock() const 558{ 559 return new FreezeLock(const_cast<SurfaceFlinger *>(this)); 560} 561 562void SurfaceFlinger::computeVisibleRegions( 563 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion) 564{ 565 const GraphicPlane& plane(graphicPlane(0)); 566 const Transform& planeTransform(plane.transform()); 567 const DisplayHardware& hw(plane.displayHardware()); 568 const Region screenRegion(hw.bounds()); 569 570 Region aboveOpaqueLayers; 571 Region aboveCoveredLayers; 572 Region dirty; 573 574 bool secureFrameBuffer = false; 575 576 size_t i = currentLayers.size(); 577 while (i--) { 578 const sp<LayerBase>& layer = currentLayers[i]; 579 layer->validateVisibility(planeTransform); 580 581 // start with the whole surface at its current location 582 const Layer::State& s(layer->drawingState()); 583 584 /* 585 * opaqueRegion: area of a surface that is fully opaque. 586 */ 587 Region opaqueRegion; 588 589 /* 590 * visibleRegion: area of a surface that is visible on screen 591 * and not fully transparent. This is essentially the layer's 592 * footprint minus the opaque regions above it. 593 * Areas covered by a translucent surface are considered visible. 594 */ 595 Region visibleRegion; 596 597 /* 598 * coveredRegion: area of a surface that is covered by all 599 * visible regions above it (which includes the translucent areas). 600 */ 601 Region coveredRegion; 602 603 604 // handle hidden surfaces by setting the visible region to empty 605 if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) { 606 const bool translucent = layer->needsBlending(); 607 const Rect bounds(layer->visibleBounds()); 608 visibleRegion.set(bounds); 609 visibleRegion.andSelf(screenRegion); 610 if (!visibleRegion.isEmpty()) { 611 // Remove the transparent area from the visible region 612 if (translucent) { 613 visibleRegion.subtractSelf(layer->transparentRegionScreen); 614 } 615 616 // compute the opaque region 617 const int32_t layerOrientation = layer->getOrientation(); 618 if (s.alpha==255 && !translucent && 619 ((layerOrientation & Transform::ROT_INVALID) == false)) { 620 // the opaque region is the layer's footprint 621 opaqueRegion = visibleRegion; 622 } 623 } 624 } 625 626 // Clip the covered region to the visible region 627 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 628 629 // Update aboveCoveredLayers for next (lower) layer 630 aboveCoveredLayers.orSelf(visibleRegion); 631 632 // subtract the opaque region covered by the layers above us 633 visibleRegion.subtractSelf(aboveOpaqueLayers); 634 635 // compute this layer's dirty region 636 if (layer->contentDirty) { 637 // we need to invalidate the whole region 638 dirty = visibleRegion; 639 // as well, as the old visible region 640 dirty.orSelf(layer->visibleRegionScreen); 641 layer->contentDirty = false; 642 } else { 643 /* compute the exposed region: 644 * the exposed region consists of two components: 645 * 1) what's VISIBLE now and was COVERED before 646 * 2) what's EXPOSED now less what was EXPOSED before 647 * 648 * note that (1) is conservative, we start with the whole 649 * visible region but only keep what used to be covered by 650 * something -- which mean it may have been exposed. 651 * 652 * (2) handles areas that were not covered by anything but got 653 * exposed because of a resize. 654 */ 655 const Region newExposed = visibleRegion - coveredRegion; 656 const Region oldVisibleRegion = layer->visibleRegionScreen; 657 const Region oldCoveredRegion = layer->coveredRegionScreen; 658 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 659 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 660 } 661 dirty.subtractSelf(aboveOpaqueLayers); 662 663 // accumulate to the screen dirty region 664 dirtyRegion.orSelf(dirty); 665 666 // Update aboveOpaqueLayers for next (lower) layer 667 aboveOpaqueLayers.orSelf(opaqueRegion); 668 669 // Store the visible region is screen space 670 layer->setVisibleRegion(visibleRegion); 671 layer->setCoveredRegion(coveredRegion); 672 673 // If a secure layer is partially visible, lock-down the screen! 674 if (layer->isSecure() && !visibleRegion.isEmpty()) { 675 secureFrameBuffer = true; 676 } 677 } 678 679 // invalidate the areas where a layer was removed 680 dirtyRegion.orSelf(mDirtyRegionRemovedLayer); 681 mDirtyRegionRemovedLayer.clear(); 682 683 mSecureFrameBuffer = secureFrameBuffer; 684 opaqueRegion = aboveOpaqueLayers; 685} 686 687 688void SurfaceFlinger::commitTransaction() 689{ 690 mDrawingState = mCurrentState; 691 mResizeTransationPending = false; 692 mTransactionCV.broadcast(); 693} 694 695void SurfaceFlinger::handlePageFlip() 696{ 697 bool visibleRegions = mVisibleRegionsDirty; 698 LayerVector& currentLayers = const_cast<LayerVector&>( 699 mDrawingState.layersSortedByZ); 700 visibleRegions |= lockPageFlip(currentLayers); 701 702 const DisplayHardware& hw = graphicPlane(0).displayHardware(); 703 const Region screenRegion(hw.bounds()); 704 if (visibleRegions) { 705 Region opaqueRegion; 706 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion); 707 708 /* 709 * rebuild the visible layer list 710 */ 711 mVisibleLayersSortedByZ.clear(); 712 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 713 size_t count = currentLayers.size(); 714 mVisibleLayersSortedByZ.setCapacity(count); 715 for (size_t i=0 ; i<count ; i++) { 716 if (!currentLayers[i]->visibleRegionScreen.isEmpty()) 717 mVisibleLayersSortedByZ.add(currentLayers[i]); 718 } 719 720 mWormholeRegion = screenRegion.subtract(opaqueRegion); 721 mVisibleRegionsDirty = false; 722 } 723 724 unlockPageFlip(currentLayers); 725 mDirtyRegion.andSelf(screenRegion); 726} 727 728bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers) 729{ 730 bool recomputeVisibleRegions = false; 731 size_t count = currentLayers.size(); 732 sp<LayerBase> const* layers = currentLayers.array(); 733 for (size_t i=0 ; i<count ; i++) { 734 const sp<LayerBase>& layer(layers[i]); 735 layer->lockPageFlip(recomputeVisibleRegions); 736 } 737 return recomputeVisibleRegions; 738} 739 740void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers) 741{ 742 const GraphicPlane& plane(graphicPlane(0)); 743 const Transform& planeTransform(plane.transform()); 744 size_t count = currentLayers.size(); 745 sp<LayerBase> const* layers = currentLayers.array(); 746 for (size_t i=0 ; i<count ; i++) { 747 const sp<LayerBase>& layer(layers[i]); 748 layer->unlockPageFlip(planeTransform, mDirtyRegion); 749 } 750} 751 752 753void SurfaceFlinger::handleRepaint() 754{ 755 // compute the invalid region 756 mInvalidRegion.orSelf(mDirtyRegion); 757 if (mInvalidRegion.isEmpty()) { 758 // nothing to do 759 return; 760 } 761 762 if (UNLIKELY(mDebugRegion)) { 763 debugFlashRegions(); 764 } 765 766 // set the frame buffer 767 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 768 glMatrixMode(GL_MODELVIEW); 769 glLoadIdentity(); 770 771 uint32_t flags = hw.getFlags(); 772 if ((flags & DisplayHardware::SWAP_RECTANGLE) || 773 (flags & DisplayHardware::BUFFER_PRESERVED)) 774 { 775 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 776 // takes a rectangle, we must make sure to update that whole 777 // rectangle in that case 778 if (flags & DisplayHardware::SWAP_RECTANGLE) { 779 // TODO: we really should be able to pass a region to 780 // SWAP_RECTANGLE so that we don't have to redraw all this. 781 mDirtyRegion.set(mInvalidRegion.bounds()); 782 } else { 783 // in the BUFFER_PRESERVED case, obviously, we can update only 784 // what's needed and nothing more. 785 // NOTE: this is NOT a common case, as preserving the backbuffer 786 // is costly and usually involves copying the whole update back. 787 } 788 } else { 789 if (flags & DisplayHardware::PARTIAL_UPDATES) { 790 // We need to redraw the rectangle that will be updated 791 // (pushed to the framebuffer). 792 // This is needed because PARTIAL_UPDATES only takes one 793 // rectangle instead of a region (see DisplayHardware::flip()) 794 mDirtyRegion.set(mInvalidRegion.bounds()); 795 } else { 796 // we need to redraw everything (the whole screen) 797 mDirtyRegion.set(hw.bounds()); 798 mInvalidRegion = mDirtyRegion; 799 } 800 } 801 802 // compose all surfaces 803 composeSurfaces(mDirtyRegion); 804 805 // clear the dirty regions 806 mDirtyRegion.clear(); 807} 808 809void SurfaceFlinger::composeSurfaces(const Region& dirty) 810{ 811 if (UNLIKELY(!mWormholeRegion.isEmpty())) { 812 // should never happen unless the window manager has a bug 813 // draw something... 814 drawWormhole(); 815 } 816 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 817 const size_t count = layers.size(); 818 for (size_t i=0 ; i<count ; ++i) { 819 const sp<LayerBase>& layer(layers[i]); 820 const Region clip(dirty.intersect(layer->visibleRegionScreen)); 821 if (!clip.isEmpty()) { 822 layer->draw(clip); 823 } 824 } 825} 826 827void SurfaceFlinger::unlockClients() 828{ 829 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ); 830 const size_t count = drawingLayers.size(); 831 sp<LayerBase> const* const layers = drawingLayers.array(); 832 for (size_t i=0 ; i<count ; ++i) { 833 const sp<LayerBase>& layer = layers[i]; 834 layer->finishPageFlip(); 835 } 836} 837 838void SurfaceFlinger::debugFlashRegions() 839{ 840 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 841 const uint32_t flags = hw.getFlags(); 842 843 if (!((flags & DisplayHardware::SWAP_RECTANGLE) || 844 (flags & DisplayHardware::BUFFER_PRESERVED))) { 845 const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ? 846 mDirtyRegion.bounds() : hw.bounds()); 847 composeSurfaces(repaint); 848 } 849 850 TextureManager::deactivateTextures(); 851 852 glDisable(GL_BLEND); 853 glDisable(GL_DITHER); 854 glDisable(GL_SCISSOR_TEST); 855 856 static int toggle = 0; 857 toggle = 1 - toggle; 858 if (toggle) { 859 glColor4f(1, 0, 1, 1); 860 } else { 861 glColor4f(1, 1, 0, 1); 862 } 863 864 Region::const_iterator it = mDirtyRegion.begin(); 865 Region::const_iterator const end = mDirtyRegion.end(); 866 while (it != end) { 867 const Rect& r = *it++; 868 GLfloat vertices[][2] = { 869 { r.left, r.top }, 870 { r.left, r.bottom }, 871 { r.right, r.bottom }, 872 { r.right, r.top } 873 }; 874 glVertexPointer(2, GL_FLOAT, 0, vertices); 875 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 876 } 877 878 if (mInvalidRegion.isEmpty()) { 879 mDirtyRegion.dump("mDirtyRegion"); 880 mInvalidRegion.dump("mInvalidRegion"); 881 } 882 hw.flip(mInvalidRegion); 883 884 if (mDebugRegion > 1) 885 usleep(mDebugRegion * 1000); 886 887 glEnable(GL_SCISSOR_TEST); 888 //mDirtyRegion.dump("mDirtyRegion"); 889} 890 891void SurfaceFlinger::drawWormhole() const 892{ 893 const Region region(mWormholeRegion.intersect(mDirtyRegion)); 894 if (region.isEmpty()) 895 return; 896 897 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 898 const int32_t width = hw.getWidth(); 899 const int32_t height = hw.getHeight(); 900 901 glDisable(GL_BLEND); 902 glDisable(GL_DITHER); 903 904 if (LIKELY(!mDebugBackground)) { 905 glClearColor(0,0,0,0); 906 Region::const_iterator it = region.begin(); 907 Region::const_iterator const end = region.end(); 908 while (it != end) { 909 const Rect& r = *it++; 910 const GLint sy = height - (r.top + r.height()); 911 glScissor(r.left, sy, r.width(), r.height()); 912 glClear(GL_COLOR_BUFFER_BIT); 913 } 914 } else { 915 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 }, 916 { width, height }, { 0, height } }; 917 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; 918 glVertexPointer(2, GL_SHORT, 0, vertices); 919 glTexCoordPointer(2, GL_SHORT, 0, tcoords); 920 glEnableClientState(GL_TEXTURE_COORD_ARRAY); 921#if defined(GL_OES_EGL_image_external) 922 if (GLExtensions::getInstance().haveTextureExternal()) { 923 glDisable(GL_TEXTURE_EXTERNAL_OES); 924 } 925#endif 926 glEnable(GL_TEXTURE_2D); 927 glBindTexture(GL_TEXTURE_2D, mWormholeTexName); 928 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); 929 glMatrixMode(GL_TEXTURE); 930 glLoadIdentity(); 931 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1); 932 Region::const_iterator it = region.begin(); 933 Region::const_iterator const end = region.end(); 934 while (it != end) { 935 const Rect& r = *it++; 936 const GLint sy = height - (r.top + r.height()); 937 glScissor(r.left, sy, r.width(), r.height()); 938 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 939 } 940 glDisableClientState(GL_TEXTURE_COORD_ARRAY); 941 } 942} 943 944void SurfaceFlinger::debugShowFPS() const 945{ 946 static int mFrameCount; 947 static int mLastFrameCount = 0; 948 static nsecs_t mLastFpsTime = 0; 949 static float mFps = 0; 950 mFrameCount++; 951 nsecs_t now = systemTime(); 952 nsecs_t diff = now - mLastFpsTime; 953 if (diff > ms2ns(250)) { 954 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff; 955 mLastFpsTime = now; 956 mLastFrameCount = mFrameCount; 957 } 958 // XXX: mFPS has the value we want 959 } 960 961status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer) 962{ 963 Mutex::Autolock _l(mStateLock); 964 addLayer_l(layer); 965 setTransactionFlags(eTransactionNeeded|eTraversalNeeded); 966 return NO_ERROR; 967} 968 969status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer) 970{ 971 ssize_t i = mCurrentState.layersSortedByZ.add(layer); 972 return (i < 0) ? status_t(i) : status_t(NO_ERROR); 973} 974 975ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 976 const sp<LayerBaseClient>& lbc) 977{ 978 Mutex::Autolock _l(mStateLock); 979 980 // attach this layer to the client 981 ssize_t name = client->attachLayer(lbc); 982 983 // add this layer to the current state list 984 addLayer_l(lbc); 985 986 return name; 987} 988 989status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) 990{ 991 Mutex::Autolock _l(mStateLock); 992 status_t err = purgatorizeLayer_l(layer); 993 if (err == NO_ERROR) 994 setTransactionFlags(eTransactionNeeded); 995 return err; 996} 997 998status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) 999{ 1000 sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient()); 1001 if (lbc != 0) { 1002 mLayerMap.removeItem( lbc->getSurface()->asBinder() ); 1003 } 1004 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); 1005 if (index >= 0) { 1006 mLayersRemoved = true; 1007 return NO_ERROR; 1008 } 1009 return status_t(index); 1010} 1011 1012status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) 1013{ 1014 // remove the layer from the main list (through a transaction). 1015 ssize_t err = removeLayer_l(layerBase); 1016 1017 layerBase->onRemoved(); 1018 1019 // it's possible that we don't find a layer, because it might 1020 // have been destroyed already -- this is not technically an error 1021 // from the user because there is a race between Client::destroySurface(), 1022 // ~Client() and ~ISurface(). 1023 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; 1024} 1025 1026status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer) 1027{ 1028 layer->forceVisibilityTransaction(); 1029 setTransactionFlags(eTraversalNeeded); 1030 return NO_ERROR; 1031} 1032 1033uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) 1034{ 1035 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1036} 1037 1038uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) 1039{ 1040 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1041 if ((old & flags)==0) { // wake the server up 1042 signalEvent(); 1043 } 1044 return old; 1045} 1046 1047void SurfaceFlinger::openGlobalTransaction() 1048{ 1049 android_atomic_inc(&mTransactionCount); 1050} 1051 1052void SurfaceFlinger::closeGlobalTransaction() 1053{ 1054 if (android_atomic_dec(&mTransactionCount) == 1) { 1055 signalEvent(); 1056 1057 // if there is a transaction with a resize, wait for it to 1058 // take effect before returning. 1059 Mutex::Autolock _l(mStateLock); 1060 while (mResizeTransationPending) { 1061 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1062 if (CC_UNLIKELY(err != NO_ERROR)) { 1063 // just in case something goes wrong in SF, return to the 1064 // called after a few seconds. 1065 LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!"); 1066 mResizeTransationPending = false; 1067 break; 1068 } 1069 } 1070 } 1071} 1072 1073status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags) 1074{ 1075 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1076 return BAD_VALUE; 1077 1078 Mutex::Autolock _l(mStateLock); 1079 mCurrentState.freezeDisplay = 1; 1080 setTransactionFlags(eTransactionNeeded); 1081 1082 // flags is intended to communicate some sort of animation behavior 1083 // (for instance fading) 1084 return NO_ERROR; 1085} 1086 1087status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags) 1088{ 1089 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1090 return BAD_VALUE; 1091 1092 Mutex::Autolock _l(mStateLock); 1093 mCurrentState.freezeDisplay = 0; 1094 setTransactionFlags(eTransactionNeeded); 1095 1096 // flags is intended to communicate some sort of animation behavior 1097 // (for instance fading) 1098 return NO_ERROR; 1099} 1100 1101int SurfaceFlinger::setOrientation(DisplayID dpy, 1102 int orientation, uint32_t flags) 1103{ 1104 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1105 return BAD_VALUE; 1106 1107 Mutex::Autolock _l(mStateLock); 1108 if (mCurrentState.orientation != orientation) { 1109 if (uint32_t(orientation)<=eOrientation270 || orientation==42) { 1110 mCurrentState.orientationType = flags; 1111 mCurrentState.orientation = orientation; 1112 setTransactionFlags(eTransactionNeeded); 1113 mTransactionCV.wait(mStateLock); 1114 } else { 1115 orientation = BAD_VALUE; 1116 } 1117 } 1118 return orientation; 1119} 1120 1121sp<ISurface> SurfaceFlinger::createSurface(const sp<Client>& client, int pid, 1122 const String8& name, ISurfaceComposerClient::surface_data_t* params, 1123 DisplayID d, uint32_t w, uint32_t h, PixelFormat format, 1124 uint32_t flags) 1125{ 1126 sp<LayerBaseClient> layer; 1127 sp<LayerBaseClient::Surface> surfaceHandle; 1128 1129 if (int32_t(w|h) < 0) { 1130 LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)", 1131 int(w), int(h)); 1132 return surfaceHandle; 1133 } 1134 1135 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h); 1136 sp<Layer> normalLayer; 1137 switch (flags & eFXSurfaceMask) { 1138 case eFXSurfaceNormal: 1139 if (UNLIKELY(flags & ePushBuffers)) { 1140 layer = createPushBuffersSurface(client, d, w, h, flags); 1141 } else { 1142 normalLayer = createNormalSurface(client, d, w, h, flags, format); 1143 layer = normalLayer; 1144 } 1145 break; 1146 case eFXSurfaceBlur: 1147 layer = createBlurSurface(client, d, w, h, flags); 1148 break; 1149 case eFXSurfaceDim: 1150 layer = createDimSurface(client, d, w, h, flags); 1151 break; 1152 } 1153 1154 if (layer != 0) { 1155 layer->initStates(w, h, flags); 1156 layer->setName(name); 1157 ssize_t token = addClientLayer(client, layer); 1158 1159 surfaceHandle = layer->getSurface(); 1160 if (surfaceHandle != 0) { 1161 params->token = token; 1162 params->identity = surfaceHandle->getIdentity(); 1163 params->width = w; 1164 params->height = h; 1165 params->format = format; 1166 if (normalLayer != 0) { 1167 Mutex::Autolock _l(mStateLock); 1168 mLayerMap.add(surfaceHandle->asBinder(), normalLayer); 1169 } 1170 } 1171 1172 setTransactionFlags(eTransactionNeeded); 1173 } 1174 1175 return surfaceHandle; 1176} 1177 1178sp<Layer> SurfaceFlinger::createNormalSurface( 1179 const sp<Client>& client, DisplayID display, 1180 uint32_t w, uint32_t h, uint32_t flags, 1181 PixelFormat& format) 1182{ 1183 // initialize the surfaces 1184 switch (format) { // TODO: take h/w into account 1185 case PIXEL_FORMAT_TRANSPARENT: 1186 case PIXEL_FORMAT_TRANSLUCENT: 1187 format = PIXEL_FORMAT_RGBA_8888; 1188 break; 1189 case PIXEL_FORMAT_OPAQUE: 1190#ifdef NO_RGBX_8888 1191 format = PIXEL_FORMAT_RGB_565; 1192#else 1193 format = PIXEL_FORMAT_RGBX_8888; 1194#endif 1195 break; 1196 } 1197 1198#ifdef NO_RGBX_8888 1199 if (format == PIXEL_FORMAT_RGBX_8888) 1200 format = PIXEL_FORMAT_RGBA_8888; 1201#endif 1202 1203 sp<Layer> layer = new Layer(this, display, client); 1204 status_t err = layer->setBuffers(w, h, format, flags); 1205 if (LIKELY(err != NO_ERROR)) { 1206 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err)); 1207 layer.clear(); 1208 } 1209 return layer; 1210} 1211 1212sp<LayerBlur> SurfaceFlinger::createBlurSurface( 1213 const sp<Client>& client, DisplayID display, 1214 uint32_t w, uint32_t h, uint32_t flags) 1215{ 1216 sp<LayerBlur> layer = new LayerBlur(this, display, client); 1217 layer->initStates(w, h, flags); 1218 return layer; 1219} 1220 1221sp<LayerDim> SurfaceFlinger::createDimSurface( 1222 const sp<Client>& client, DisplayID display, 1223 uint32_t w, uint32_t h, uint32_t flags) 1224{ 1225 sp<LayerDim> layer = new LayerDim(this, display, client); 1226 layer->initStates(w, h, flags); 1227 return layer; 1228} 1229 1230sp<LayerBuffer> SurfaceFlinger::createPushBuffersSurface( 1231 const sp<Client>& client, DisplayID display, 1232 uint32_t w, uint32_t h, uint32_t flags) 1233{ 1234 sp<LayerBuffer> layer = new LayerBuffer(this, display, client); 1235 layer->initStates(w, h, flags); 1236 return layer; 1237} 1238 1239status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid) 1240{ 1241 /* 1242 * called by the window manager, when a surface should be marked for 1243 * destruction. 1244 * 1245 * The surface is removed from the current and drawing lists, but placed 1246 * in the purgatory queue, so it's not destroyed right-away (we need 1247 * to wait for all client's references to go away first). 1248 */ 1249 1250 status_t err = NAME_NOT_FOUND; 1251 Mutex::Autolock _l(mStateLock); 1252 sp<LayerBaseClient> layer = client->getLayerUser(sid); 1253 if (layer != 0) { 1254 err = purgatorizeLayer_l(layer); 1255 if (err == NO_ERROR) { 1256 setTransactionFlags(eTransactionNeeded); 1257 } 1258 } 1259 return err; 1260} 1261 1262status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer) 1263{ 1264 // called by ~ISurface() when all references are gone 1265 1266 class MessageDestroySurface : public MessageBase { 1267 SurfaceFlinger* flinger; 1268 sp<LayerBaseClient> layer; 1269 public: 1270 MessageDestroySurface( 1271 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer) 1272 : flinger(flinger), layer(layer) { } 1273 virtual bool handler() { 1274 sp<LayerBaseClient> l(layer); 1275 layer.clear(); // clear it outside of the lock; 1276 Mutex::Autolock _l(flinger->mStateLock); 1277 /* 1278 * remove the layer from the current list -- chances are that it's 1279 * not in the list anyway, because it should have been removed 1280 * already upon request of the client (eg: window manager). 1281 * However, a buggy client could have not done that. 1282 * Since we know we don't have any more clients, we don't need 1283 * to use the purgatory. 1284 */ 1285 status_t err = flinger->removeLayer_l(l); 1286 LOGE_IF(err<0 && err != NAME_NOT_FOUND, 1287 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1288 return true; 1289 } 1290 }; 1291 1292 postMessageAsync( new MessageDestroySurface(this, layer) ); 1293 return NO_ERROR; 1294} 1295 1296status_t SurfaceFlinger::setClientState( 1297 const sp<Client>& client, 1298 int32_t count, 1299 const layer_state_t* states) 1300{ 1301 Mutex::Autolock _l(mStateLock); 1302 uint32_t flags = 0; 1303 for (int i=0 ; i<count ; i++) { 1304 const layer_state_t& s(states[i]); 1305 sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); 1306 if (layer != 0) { 1307 const uint32_t what = s.what; 1308 if (what & ePositionChanged) { 1309 if (layer->setPosition(s.x, s.y)) 1310 flags |= eTraversalNeeded; 1311 } 1312 if (what & eLayerChanged) { 1313 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1314 if (layer->setLayer(s.z)) { 1315 mCurrentState.layersSortedByZ.removeAt(idx); 1316 mCurrentState.layersSortedByZ.add(layer); 1317 // we need traversal (state changed) 1318 // AND transaction (list changed) 1319 flags |= eTransactionNeeded|eTraversalNeeded; 1320 } 1321 } 1322 if (what & eSizeChanged) { 1323 if (layer->setSize(s.w, s.h)) { 1324 flags |= eTraversalNeeded; 1325 mResizeTransationPending = true; 1326 } 1327 } 1328 if (what & eAlphaChanged) { 1329 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1330 flags |= eTraversalNeeded; 1331 } 1332 if (what & eMatrixChanged) { 1333 if (layer->setMatrix(s.matrix)) 1334 flags |= eTraversalNeeded; 1335 } 1336 if (what & eTransparentRegionChanged) { 1337 if (layer->setTransparentRegionHint(s.transparentRegion)) 1338 flags |= eTraversalNeeded; 1339 } 1340 if (what & eVisibilityChanged) { 1341 if (layer->setFlags(s.flags, s.mask)) 1342 flags |= eTraversalNeeded; 1343 } 1344 } 1345 } 1346 if (flags) { 1347 setTransactionFlags(flags); 1348 } 1349 return NO_ERROR; 1350} 1351 1352void SurfaceFlinger::screenReleased(int dpy) 1353{ 1354 // this may be called by a signal handler, we can't do too much in here 1355 android_atomic_or(eConsoleReleased, &mConsoleSignals); 1356 signalEvent(); 1357} 1358 1359void SurfaceFlinger::screenAcquired(int dpy) 1360{ 1361 // this may be called by a signal handler, we can't do too much in here 1362 android_atomic_or(eConsoleAcquired, &mConsoleSignals); 1363 signalEvent(); 1364} 1365 1366status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 1367{ 1368 const size_t SIZE = 1024; 1369 char buffer[SIZE]; 1370 String8 result; 1371 if (!mDump.checkCalling()) { 1372 snprintf(buffer, SIZE, "Permission Denial: " 1373 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 1374 IPCThreadState::self()->getCallingPid(), 1375 IPCThreadState::self()->getCallingUid()); 1376 result.append(buffer); 1377 } else { 1378 1379 // figure out if we're stuck somewhere 1380 const nsecs_t now = systemTime(); 1381 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 1382 const nsecs_t inTransaction(mDebugInTransaction); 1383 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 1384 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 1385 1386 // Try to get the main lock, but don't insist if we can't 1387 // (this would indicate SF is stuck, but we want to be able to 1388 // print something in dumpsys). 1389 int retry = 3; 1390 while (mStateLock.tryLock()<0 && --retry>=0) { 1391 usleep(1000000); 1392 } 1393 const bool locked(retry >= 0); 1394 if (!locked) { 1395 snprintf(buffer, SIZE, 1396 "SurfaceFlinger appears to be unresponsive, " 1397 "dumping anyways (no locks held)\n"); 1398 result.append(buffer); 1399 } 1400 1401 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1402 const size_t count = currentLayers.size(); 1403 for (size_t i=0 ; i<count ; i++) { 1404 const sp<LayerBase>& layer(currentLayers[i]); 1405 layer->dump(result, buffer, SIZE); 1406 const Layer::State& s(layer->drawingState()); 1407 s.transparentRegion.dump(result, "transparentRegion"); 1408 layer->transparentRegionScreen.dump(result, "transparentRegionScreen"); 1409 layer->visibleRegionScreen.dump(result, "visibleRegionScreen"); 1410 } 1411 1412 mWormholeRegion.dump(result, "WormholeRegion"); 1413 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1414 snprintf(buffer, SIZE, 1415 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n", 1416 mFreezeDisplay?"yes":"no", mFreezeCount, 1417 mCurrentState.orientation, hw.canDraw()); 1418 result.append(buffer); 1419 snprintf(buffer, SIZE, 1420 " last eglSwapBuffers() time: %f us\n" 1421 " last transaction time : %f us\n", 1422 mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0); 1423 result.append(buffer); 1424 1425 if (inSwapBuffersDuration || !locked) { 1426 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n", 1427 inSwapBuffersDuration/1000.0); 1428 result.append(buffer); 1429 } 1430 1431 if (inTransactionDuration || !locked) { 1432 snprintf(buffer, SIZE, " transaction time: %f us\n", 1433 inTransactionDuration/1000.0); 1434 result.append(buffer); 1435 } 1436 1437 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 1438 alloc.dump(result); 1439 1440 if (locked) { 1441 mStateLock.unlock(); 1442 } 1443 } 1444 write(fd, result.string(), result.size()); 1445 return NO_ERROR; 1446} 1447 1448status_t SurfaceFlinger::onTransact( 1449 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 1450{ 1451 switch (code) { 1452 case CREATE_CONNECTION: 1453 case OPEN_GLOBAL_TRANSACTION: 1454 case CLOSE_GLOBAL_TRANSACTION: 1455 case SET_ORIENTATION: 1456 case FREEZE_DISPLAY: 1457 case UNFREEZE_DISPLAY: 1458 case BOOT_FINISHED: 1459 case TURN_ELECTRON_BEAM_OFF: 1460 { 1461 // codes that require permission check 1462 IPCThreadState* ipc = IPCThreadState::self(); 1463 const int pid = ipc->getCallingPid(); 1464 const int uid = ipc->getCallingUid(); 1465 if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) { 1466 LOGE("Permission Denial: " 1467 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 1468 return PERMISSION_DENIED; 1469 } 1470 break; 1471 } 1472 case CAPTURE_SCREEN: 1473 { 1474 // codes that require permission check 1475 IPCThreadState* ipc = IPCThreadState::self(); 1476 const int pid = ipc->getCallingPid(); 1477 const int uid = ipc->getCallingUid(); 1478 if ((uid != AID_GRAPHICS) && !mReadFramebuffer.check(pid, uid)) { 1479 LOGE("Permission Denial: " 1480 "can't read framebuffer pid=%d, uid=%d", pid, uid); 1481 return PERMISSION_DENIED; 1482 } 1483 break; 1484 } 1485 } 1486 1487 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 1488 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 1489 CHECK_INTERFACE(ISurfaceComposer, data, reply); 1490 if (UNLIKELY(!mHardwareTest.checkCalling())) { 1491 IPCThreadState* ipc = IPCThreadState::self(); 1492 const int pid = ipc->getCallingPid(); 1493 const int uid = ipc->getCallingUid(); 1494 LOGE("Permission Denial: " 1495 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 1496 return PERMISSION_DENIED; 1497 } 1498 int n; 1499 switch (code) { 1500 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 1501 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 1502 return NO_ERROR; 1503 case 1002: // SHOW_UPDATES 1504 n = data.readInt32(); 1505 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 1506 return NO_ERROR; 1507 case 1003: // SHOW_BACKGROUND 1508 n = data.readInt32(); 1509 mDebugBackground = n ? 1 : 0; 1510 return NO_ERROR; 1511 case 1004:{ // repaint everything 1512 Mutex::Autolock _l(mStateLock); 1513 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1514 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe 1515 signalEvent(); 1516 return NO_ERROR; 1517 } 1518 case 1005:{ // force transaction 1519 setTransactionFlags(eTransactionNeeded|eTraversalNeeded); 1520 return NO_ERROR; 1521 } 1522 case 1006:{ // enable/disable GraphicLog 1523 int enabled = data.readInt32(); 1524 GraphicLog::getInstance().setEnabled(enabled); 1525 return NO_ERROR; 1526 } 1527 case 1007: // set mFreezeCount 1528 mFreezeCount = data.readInt32(); 1529 mFreezeDisplayTime = 0; 1530 return NO_ERROR; 1531 case 1010: // interrogate. 1532 reply->writeInt32(0); 1533 reply->writeInt32(0); 1534 reply->writeInt32(mDebugRegion); 1535 reply->writeInt32(mDebugBackground); 1536 return NO_ERROR; 1537 case 1013: { 1538 Mutex::Autolock _l(mStateLock); 1539 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1540 reply->writeInt32(hw.getPageFlipCount()); 1541 } 1542 return NO_ERROR; 1543 } 1544 } 1545 return err; 1546} 1547 1548 1549// --------------------------------------------------------------------------- 1550 1551status_t SurfaceFlinger::turnElectronBeamOffImplLocked() 1552{ 1553 status_t result = PERMISSION_DENIED; 1554 1555 if (!GLExtensions::getInstance().haveFramebufferObject()) 1556 return INVALID_OPERATION; 1557 1558 // get screen geometry 1559 const int dpy = 0; 1560 const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); 1561 if (!hw.canDraw()) { 1562 // we're already off 1563 return NO_ERROR; 1564 } 1565 1566 const uint32_t hw_w = hw.getWidth(); 1567 const uint32_t hw_h = hw.getHeight(); 1568 const Region screenBounds(hw.bounds()); 1569 GLfloat u = 1; 1570 GLfloat v = 1; 1571 1572 // make sure to clear all GL error flags 1573 while ( glGetError() != GL_NO_ERROR ) ; 1574 1575 // create a FBO 1576 GLuint name, tname; 1577 glGenTextures(1, &tname); 1578 glBindTexture(GL_TEXTURE_2D, tname); 1579 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 1580 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 1581 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 1582 if (glGetError() != GL_NO_ERROR) { 1583 GLint tw = (2 << (31 - clz(hw_w))); 1584 GLint th = (2 << (31 - clz(hw_h))); 1585 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 1586 u = GLfloat(hw_w) / tw; 1587 v = GLfloat(hw_h) / th; 1588 } 1589 glGenFramebuffersOES(1, &name); 1590 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 1591 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0); 1592 1593 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); 1594 if (status == GL_FRAMEBUFFER_COMPLETE_OES) { 1595 // redraw the screen entirely... 1596 glClearColor(0,0,0,1); 1597 glClear(GL_COLOR_BUFFER_BIT); 1598 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 1599 const size_t count = layers.size(); 1600 for (size_t i=0 ; i<count ; ++i) { 1601 const sp<LayerBase>& layer(layers[i]); 1602 layer->drawForSreenShot(); 1603 } 1604 // back to main framebuffer 1605 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 1606 glDisable(GL_SCISSOR_TEST); 1607 1608 GLfloat vtx[8]; 1609 const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} }; 1610 glEnable(GL_TEXTURE_2D); 1611 glBindTexture(GL_TEXTURE_2D, tname); 1612 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); 1613 glTexCoordPointer(2, GL_FLOAT, 0, texCoords); 1614 glEnableClientState(GL_TEXTURE_COORD_ARRAY); 1615 glVertexPointer(2, GL_FLOAT, 0, vtx); 1616 1617 class s_curve_interpolator { 1618 const float nbFrames, s, v; 1619 public: 1620 s_curve_interpolator(int nbFrames, float s) 1621 : nbFrames(1.0f / (nbFrames-1)), s(s), 1622 v(1.0f + expf(-s + 0.5f*s)) { 1623 } 1624 float operator()(int f) { 1625 const float x = f * nbFrames; 1626 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f; 1627 } 1628 }; 1629 1630 class v_stretch { 1631 const GLfloat hw_w, hw_h; 1632 public: 1633 v_stretch(uint32_t hw_w, uint32_t hw_h) 1634 : hw_w(hw_w), hw_h(hw_h) { 1635 } 1636 void operator()(GLfloat* vtx, float v) { 1637 const GLfloat w = hw_w + (hw_w * v); 1638 const GLfloat h = hw_h - (hw_h * v); 1639 const GLfloat x = (hw_w - w) * 0.5f; 1640 const GLfloat y = (hw_h - h) * 0.5f; 1641 vtx[0] = x; vtx[1] = y; 1642 vtx[2] = x; vtx[3] = y + h; 1643 vtx[4] = x + w; vtx[5] = y + h; 1644 vtx[6] = x + w; vtx[7] = y; 1645 } 1646 }; 1647 1648 class h_stretch { 1649 const GLfloat hw_w, hw_h; 1650 public: 1651 h_stretch(uint32_t hw_w, uint32_t hw_h) 1652 : hw_w(hw_w), hw_h(hw_h) { 1653 } 1654 void operator()(GLfloat* vtx, float v) { 1655 const GLfloat w = hw_w - (hw_w * v); 1656 const GLfloat h = 1.0f; 1657 const GLfloat x = (hw_w - w) * 0.5f; 1658 const GLfloat y = (hw_h - h) * 0.5f; 1659 vtx[0] = x; vtx[1] = y; 1660 vtx[2] = x; vtx[3] = y + h; 1661 vtx[4] = x + w; vtx[5] = y + h; 1662 vtx[6] = x + w; vtx[7] = y; 1663 } 1664 }; 1665 1666 // the full animation is 24 frames 1667 const int nbFrames = 12; 1668 1669 v_stretch vverts(hw_w, hw_h); 1670 s_curve_interpolator itr(nbFrames, 7.5f); 1671 s_curve_interpolator itg(nbFrames, 8.0f); 1672 s_curve_interpolator itb(nbFrames, 8.5f); 1673 glEnable(GL_BLEND); 1674 glBlendFunc(GL_ONE, GL_ONE); 1675 for (int i=0 ; i<nbFrames ; i++) { 1676 float x, y, w, h; 1677 const float vr = itr(i); 1678 const float vg = itg(i); 1679 const float vb = itb(i); 1680 1681 // clear screen 1682 glColorMask(1,1,1,1); 1683 glClear(GL_COLOR_BUFFER_BIT); 1684 glEnable(GL_TEXTURE_2D); 1685 1686 // draw the red plane 1687 vverts(vtx, vr); 1688 glColorMask(1,0,0,1); 1689 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1690 1691 // draw the green plane 1692 vverts(vtx, vg); 1693 glColorMask(0,1,0,1); 1694 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1695 1696 // draw the blue plane 1697 vverts(vtx, vb); 1698 glColorMask(0,0,1,1); 1699 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1700 1701 // draw the white highlight (we use the last vertices) 1702 glDisable(GL_TEXTURE_2D); 1703 glColorMask(1,1,1,1); 1704 glColor4f(vg, vg, vg, 1); 1705 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1706 hw.flip(screenBounds); 1707 } 1708 1709 h_stretch hverts(hw_w, hw_h); 1710 glDisable(GL_BLEND); 1711 glDisable(GL_TEXTURE_2D); 1712 glColorMask(1,1,1,1); 1713 for (int i=0 ; i<nbFrames ; i++) { 1714 const float v = itg(i); 1715 hverts(vtx, v); 1716 glClear(GL_COLOR_BUFFER_BIT); 1717 glColor4f(1-v, 1-v, 1-v, 1); 1718 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1719 hw.flip(screenBounds); 1720 } 1721 1722 glColorMask(1,1,1,1); 1723 glEnable(GL_SCISSOR_TEST); 1724 glDisableClientState(GL_TEXTURE_COORD_ARRAY); 1725 result = NO_ERROR; 1726 } else { 1727 // release FBO resources 1728 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 1729 result = BAD_VALUE; 1730 } 1731 1732 glDeleteFramebuffersOES(1, &name); 1733 glDeleteTextures(1, &tname); 1734 1735 if (result == NO_ERROR) { 1736 DisplayHardware& hw(graphicPlane(dpy).editDisplayHardware()); 1737 hw.setCanDraw(false); 1738 } 1739 1740 return result; 1741} 1742 1743status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode) 1744{ 1745 if (!GLExtensions::getInstance().haveFramebufferObject()) 1746 return INVALID_OPERATION; 1747 1748 class MessageTurnElectronBeamOff : public MessageBase { 1749 SurfaceFlinger* flinger; 1750 status_t result; 1751 public: 1752 MessageTurnElectronBeamOff(SurfaceFlinger* flinger) 1753 : flinger(flinger), result(PERMISSION_DENIED) { 1754 } 1755 status_t getResult() const { 1756 return result; 1757 } 1758 virtual bool handler() { 1759 Mutex::Autolock _l(flinger->mStateLock); 1760 result = flinger->turnElectronBeamOffImplLocked(); 1761 return true; 1762 } 1763 }; 1764 1765 sp<MessageBase> msg = new MessageTurnElectronBeamOff(this); 1766 status_t res = postMessageSync(msg); 1767 if (res == NO_ERROR) { 1768 res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult(); 1769 } 1770 return res; 1771} 1772 1773// --------------------------------------------------------------------------- 1774 1775status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, 1776 sp<IMemoryHeap>* heap, 1777 uint32_t* w, uint32_t* h, PixelFormat* f, 1778 uint32_t sw, uint32_t sh) 1779{ 1780 status_t result = PERMISSION_DENIED; 1781 1782 // only one display supported for now 1783 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1784 return BAD_VALUE; 1785 1786 if (!GLExtensions::getInstance().haveFramebufferObject()) 1787 return INVALID_OPERATION; 1788 1789 // get screen geometry 1790 const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); 1791 const uint32_t hw_w = hw.getWidth(); 1792 const uint32_t hw_h = hw.getHeight(); 1793 1794 if ((sw > hw_w) || (sh > hw_h)) 1795 return BAD_VALUE; 1796 1797 sw = (!sw) ? hw_w : sw; 1798 sh = (!sh) ? hw_h : sh; 1799 const size_t size = sw * sh * 4; 1800 1801 // make sure to clear all GL error flags 1802 while ( glGetError() != GL_NO_ERROR ) ; 1803 1804 // create a FBO 1805 GLuint name, tname; 1806 glGenRenderbuffersOES(1, &tname); 1807 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname); 1808 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh); 1809 glGenFramebuffersOES(1, &name); 1810 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 1811 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, 1812 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname); 1813 1814 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); 1815 if (status == GL_FRAMEBUFFER_COMPLETE_OES) { 1816 1817 // invert everything, b/c glReadPixel() below will invert the FB 1818 glViewport(0, 0, sw, sh); 1819 glMatrixMode(GL_PROJECTION); 1820 glPushMatrix(); 1821 glLoadIdentity(); 1822 glOrthof(0, hw_w, 0, hw_h, 0, 1); 1823 glMatrixMode(GL_MODELVIEW); 1824 1825 // redraw the screen entirely... 1826 glClearColor(0,0,0,1); 1827 glClear(GL_COLOR_BUFFER_BIT); 1828 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 1829 const size_t count = layers.size(); 1830 for (size_t i=0 ; i<count ; ++i) { 1831 const sp<LayerBase>& layer(layers[i]); 1832 layer->drawForSreenShot(); 1833 } 1834 1835 // XXX: this is needed on tegra 1836 glScissor(0, 0, sw, sh); 1837 1838 // check for errors and return screen capture 1839 if (glGetError() != GL_NO_ERROR) { 1840 // error while rendering 1841 result = INVALID_OPERATION; 1842 } else { 1843 // allocate shared memory large enough to hold the 1844 // screen capture 1845 sp<MemoryHeapBase> base( 1846 new MemoryHeapBase(size, 0, "screen-capture") ); 1847 void* const ptr = base->getBase(); 1848 if (ptr) { 1849 // capture the screen with glReadPixels() 1850 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr); 1851 if (glGetError() == GL_NO_ERROR) { 1852 *heap = base; 1853 *w = sw; 1854 *h = sh; 1855 *f = PIXEL_FORMAT_RGBA_8888; 1856 result = NO_ERROR; 1857 } 1858 } else { 1859 result = NO_MEMORY; 1860 } 1861 } 1862 1863 glEnable(GL_SCISSOR_TEST); 1864 glViewport(0, 0, hw_w, hw_h); 1865 glMatrixMode(GL_PROJECTION); 1866 glPopMatrix(); 1867 glMatrixMode(GL_MODELVIEW); 1868 1869 1870 } else { 1871 result = BAD_VALUE; 1872 } 1873 1874 // release FBO resources 1875 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 1876 glDeleteRenderbuffersOES(1, &tname); 1877 glDeleteFramebuffersOES(1, &name); 1878 return result; 1879} 1880 1881 1882status_t SurfaceFlinger::captureScreen(DisplayID dpy, 1883 sp<IMemoryHeap>* heap, 1884 uint32_t* width, uint32_t* height, PixelFormat* format, 1885 uint32_t sw, uint32_t sh) 1886{ 1887 // only one display supported for now 1888 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1889 return BAD_VALUE; 1890 1891 if (!GLExtensions::getInstance().haveFramebufferObject()) 1892 return INVALID_OPERATION; 1893 1894 class MessageCaptureScreen : public MessageBase { 1895 SurfaceFlinger* flinger; 1896 DisplayID dpy; 1897 sp<IMemoryHeap>* heap; 1898 uint32_t* w; 1899 uint32_t* h; 1900 PixelFormat* f; 1901 uint32_t sw; 1902 uint32_t sh; 1903 status_t result; 1904 public: 1905 MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy, 1906 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, 1907 uint32_t sw, uint32_t sh) 1908 : flinger(flinger), dpy(dpy), 1909 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh), result(PERMISSION_DENIED) 1910 { 1911 } 1912 status_t getResult() const { 1913 return result; 1914 } 1915 virtual bool handler() { 1916 Mutex::Autolock _l(flinger->mStateLock); 1917 1918 // if we have secure windows, never allow the screen capture 1919 if (flinger->mSecureFrameBuffer) 1920 return true; 1921 1922 result = flinger->captureScreenImplLocked(dpy, 1923 heap, w, h, f, sw, sh); 1924 1925 return true; 1926 } 1927 }; 1928 1929 sp<MessageBase> msg = new MessageCaptureScreen(this, 1930 dpy, heap, width, height, format, sw, sh); 1931 status_t res = postMessageSync(msg); 1932 if (res == NO_ERROR) { 1933 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult(); 1934 } 1935 return res; 1936} 1937 1938// --------------------------------------------------------------------------- 1939 1940sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const 1941{ 1942 sp<Layer> result; 1943 Mutex::Autolock _l(mStateLock); 1944 result = mLayerMap.valueFor( sur->asBinder() ).promote(); 1945 return result; 1946} 1947 1948// --------------------------------------------------------------------------- 1949 1950Client::Client(const sp<SurfaceFlinger>& flinger) 1951 : mFlinger(flinger), mNameGenerator(1) 1952{ 1953} 1954 1955Client::~Client() 1956{ 1957 const size_t count = mLayers.size(); 1958 for (size_t i=0 ; i<count ; i++) { 1959 sp<LayerBaseClient> layer(mLayers.valueAt(i).promote()); 1960 if (layer != 0) { 1961 mFlinger->removeLayer(layer); 1962 } 1963 } 1964} 1965 1966status_t Client::initCheck() const { 1967 return NO_ERROR; 1968} 1969 1970ssize_t Client::attachLayer(const sp<LayerBaseClient>& layer) 1971{ 1972 int32_t name = android_atomic_inc(&mNameGenerator); 1973 mLayers.add(name, layer); 1974 return name; 1975} 1976 1977void Client::detachLayer(const LayerBaseClient* layer) 1978{ 1979 // we do a linear search here, because this doesn't happen often 1980 const size_t count = mLayers.size(); 1981 for (size_t i=0 ; i<count ; i++) { 1982 if (mLayers.valueAt(i) == layer) { 1983 mLayers.removeItemsAt(i, 1); 1984 break; 1985 } 1986 } 1987} 1988sp<LayerBaseClient> Client::getLayerUser(int32_t i) const { 1989 sp<LayerBaseClient> lbc; 1990 const wp<LayerBaseClient>& layer(mLayers.valueFor(i)); 1991 if (layer != 0) { 1992 lbc = layer.promote(); 1993 LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i)); 1994 } 1995 return lbc; 1996} 1997 1998sp<IMemoryHeap> Client::getControlBlock() const { 1999 return 0; 2000} 2001ssize_t Client::getTokenForSurface(const sp<ISurface>& sur) const { 2002 return -1; 2003} 2004sp<ISurface> Client::createSurface( 2005 ISurfaceComposerClient::surface_data_t* params, int pid, 2006 const String8& name, 2007 DisplayID display, uint32_t w, uint32_t h, PixelFormat format, 2008 uint32_t flags) 2009{ 2010 return mFlinger->createSurface(this, pid, name, params, 2011 display, w, h, format, flags); 2012} 2013status_t Client::destroySurface(SurfaceID sid) { 2014 return mFlinger->removeSurface(this, sid); 2015} 2016status_t Client::setState(int32_t count, const layer_state_t* states) { 2017 return mFlinger->setClientState(this, count, states); 2018} 2019 2020// --------------------------------------------------------------------------- 2021 2022UserClient::UserClient(const sp<SurfaceFlinger>& flinger) 2023 : ctrlblk(0), mBitmap(0), mFlinger(flinger) 2024{ 2025 const int pgsize = getpagesize(); 2026 const int cblksize = ((sizeof(SharedClient)+(pgsize-1))&~(pgsize-1)); 2027 2028 mCblkHeap = new MemoryHeapBase(cblksize, 0, 2029 "SurfaceFlinger Client control-block"); 2030 2031 ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase()); 2032 if (ctrlblk) { // construct the shared structure in-place. 2033 new(ctrlblk) SharedClient; 2034 } 2035} 2036 2037UserClient::~UserClient() 2038{ 2039 if (ctrlblk) { 2040 ctrlblk->~SharedClient(); // destroy our shared-structure. 2041 } 2042 2043 /* 2044 * When a UserClient dies, it's unclear what to do exactly. 2045 * We could go ahead and destroy all surfaces linked to that client 2046 * however, it wouldn't be fair to the main Client 2047 * (usually the the window-manager), which might want to re-target 2048 * the layer to another UserClient. 2049 * I think the best is to do nothing, or not much; in most cases the 2050 * WM itself will go ahead and clean things up when it detects a client of 2051 * his has died. 2052 * The remaining question is what to display? currently we keep 2053 * just keep the current buffer. 2054 */ 2055} 2056 2057status_t UserClient::initCheck() const { 2058 return ctrlblk == 0 ? NO_INIT : NO_ERROR; 2059} 2060 2061void UserClient::detachLayer(const Layer* layer) 2062{ 2063 int32_t name = layer->getToken(); 2064 if (name >= 0) { 2065 int32_t mask = 1LU<<name; 2066 if ((android_atomic_and(~mask, &mBitmap) & mask) == 0) { 2067 LOGW("token %d wasn't marked as used %08x", name, int(mBitmap)); 2068 } 2069 } 2070} 2071 2072sp<IMemoryHeap> UserClient::getControlBlock() const { 2073 return mCblkHeap; 2074} 2075 2076ssize_t UserClient::getTokenForSurface(const sp<ISurface>& sur) const 2077{ 2078 int32_t name = NAME_NOT_FOUND; 2079 sp<Layer> layer(mFlinger->getLayer(sur)); 2080 if (layer == 0) return name; 2081 2082 // if this layer already has a token, just return it 2083 name = layer->getToken(); 2084 if ((name >= 0) && (layer->getClient() == this)) 2085 return name; 2086 2087 name = 0; 2088 do { 2089 int32_t mask = 1LU<<name; 2090 if ((android_atomic_or(mask, &mBitmap) & mask) == 0) { 2091 // we found and locked that name 2092 status_t err = layer->setToken( 2093 const_cast<UserClient*>(this), ctrlblk, name); 2094 if (err != NO_ERROR) { 2095 // free the name 2096 android_atomic_and(~mask, &mBitmap); 2097 name = err; 2098 } 2099 break; 2100 } 2101 if (++name > 31) 2102 name = NO_MEMORY; 2103 } while(name >= 0); 2104 2105 //LOGD("getTokenForSurface(%p) => %d (client=%p, bitmap=%08lx)", 2106 // sur->asBinder().get(), name, this, mBitmap); 2107 return name; 2108} 2109 2110sp<ISurface> UserClient::createSurface( 2111 ISurfaceComposerClient::surface_data_t* params, int pid, 2112 const String8& name, 2113 DisplayID display, uint32_t w, uint32_t h, PixelFormat format, 2114 uint32_t flags) { 2115 return 0; 2116} 2117status_t UserClient::destroySurface(SurfaceID sid) { 2118 return INVALID_OPERATION; 2119} 2120status_t UserClient::setState(int32_t count, const layer_state_t* states) { 2121 return INVALID_OPERATION; 2122} 2123 2124// --------------------------------------------------------------------------- 2125 2126GraphicPlane::GraphicPlane() 2127 : mHw(0) 2128{ 2129} 2130 2131GraphicPlane::~GraphicPlane() { 2132 delete mHw; 2133} 2134 2135bool GraphicPlane::initialized() const { 2136 return mHw ? true : false; 2137} 2138 2139int GraphicPlane::getWidth() const { 2140 return mWidth; 2141} 2142 2143int GraphicPlane::getHeight() const { 2144 return mHeight; 2145} 2146 2147void GraphicPlane::setDisplayHardware(DisplayHardware *hw) 2148{ 2149 mHw = hw; 2150 2151 // initialize the display orientation transform. 2152 // it's a constant that should come from the display driver. 2153 int displayOrientation = ISurfaceComposer::eOrientationDefault; 2154 char property[PROPERTY_VALUE_MAX]; 2155 if (property_get("ro.sf.hwrotation", property, NULL) > 0) { 2156 //displayOrientation 2157 switch (atoi(property)) { 2158 case 90: 2159 displayOrientation = ISurfaceComposer::eOrientation90; 2160 break; 2161 case 270: 2162 displayOrientation = ISurfaceComposer::eOrientation270; 2163 break; 2164 } 2165 } 2166 2167 const float w = hw->getWidth(); 2168 const float h = hw->getHeight(); 2169 GraphicPlane::orientationToTransfrom(displayOrientation, w, h, 2170 &mDisplayTransform); 2171 if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) { 2172 mDisplayWidth = h; 2173 mDisplayHeight = w; 2174 } else { 2175 mDisplayWidth = w; 2176 mDisplayHeight = h; 2177 } 2178 2179 setOrientation(ISurfaceComposer::eOrientationDefault); 2180} 2181 2182status_t GraphicPlane::orientationToTransfrom( 2183 int orientation, int w, int h, Transform* tr) 2184{ 2185 uint32_t flags = 0; 2186 switch (orientation) { 2187 case ISurfaceComposer::eOrientationDefault: 2188 flags = Transform::ROT_0; 2189 break; 2190 case ISurfaceComposer::eOrientation90: 2191 flags = Transform::ROT_90; 2192 break; 2193 case ISurfaceComposer::eOrientation180: 2194 flags = Transform::ROT_180; 2195 break; 2196 case ISurfaceComposer::eOrientation270: 2197 flags = Transform::ROT_270; 2198 break; 2199 default: 2200 return BAD_VALUE; 2201 } 2202 tr->set(flags, w, h); 2203 return NO_ERROR; 2204} 2205 2206status_t GraphicPlane::setOrientation(int orientation) 2207{ 2208 // If the rotation can be handled in hardware, this is where 2209 // the magic should happen. 2210 2211 const DisplayHardware& hw(displayHardware()); 2212 const float w = mDisplayWidth; 2213 const float h = mDisplayHeight; 2214 mWidth = int(w); 2215 mHeight = int(h); 2216 2217 Transform orientationTransform; 2218 GraphicPlane::orientationToTransfrom(orientation, w, h, 2219 &orientationTransform); 2220 if (orientation & ISurfaceComposer::eOrientationSwapMask) { 2221 mWidth = int(h); 2222 mHeight = int(w); 2223 } 2224 2225 mOrientation = orientation; 2226 mGlobalTransform = mDisplayTransform * orientationTransform; 2227 return NO_ERROR; 2228} 2229 2230const DisplayHardware& GraphicPlane::displayHardware() const { 2231 return *mHw; 2232} 2233 2234DisplayHardware& GraphicPlane::editDisplayHardware() { 2235 return *mHw; 2236} 2237 2238const Transform& GraphicPlane::transform() const { 2239 return mGlobalTransform; 2240} 2241 2242EGLDisplay GraphicPlane::getEGLDisplay() const { 2243 return mHw->getEGLDisplay(); 2244} 2245 2246// --------------------------------------------------------------------------- 2247 2248}; // namespace android 2249