Layer.cpp 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162
  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. //#define LOG_NDEBUG 0
  17. #undef LOG_TAG
  18. #define LOG_TAG "Layer"
  19. #define ATRACE_TAG ATRACE_TAG_GRAPHICS
  20. #include "Layer.h"
  21. #include <android-base/stringprintf.h>
  22. #include <compositionengine/Display.h>
  23. #include <compositionengine/Layer.h>
  24. #include <compositionengine/LayerFECompositionState.h>
  25. #include <compositionengine/OutputLayer.h>
  26. #include <compositionengine/impl/LayerCompositionState.h>
  27. #include <compositionengine/impl/OutputLayerCompositionState.h>
  28. #include <cutils/compiler.h>
  29. #include <cutils/native_handle.h>
  30. #include <cutils/properties.h>
  31. #include <gui/BufferItem.h>
  32. #include <gui/LayerDebugInfo.h>
  33. #include <gui/Surface.h>
  34. #include <math.h>
  35. #include <renderengine/RenderEngine.h>
  36. #include <stdint.h>
  37. #include <stdlib.h>
  38. #include <sys/types.h>
  39. #include <ui/DebugUtils.h>
  40. #include <ui/GraphicBuffer.h>
  41. #include <ui/PixelFormat.h>
  42. #include <utils/Errors.h>
  43. #include <utils/Log.h>
  44. #include <utils/NativeHandle.h>
  45. #include <utils/StopWatch.h>
  46. #include <utils/Trace.h>
  47. #include <algorithm>
  48. #include <mutex>
  49. #include <sstream>
  50. #include "BufferLayer.h"
  51. #include "ColorLayer.h"
  52. #include "Colorizer.h"
  53. #include "DisplayDevice.h"
  54. #include "DisplayHardware/HWComposer.h"
  55. #include "LayerProtoHelper.h"
  56. #include "LayerRejecter.h"
  57. #include "MonitoredProducer.h"
  58. #include "SurfaceFlinger.h"
  59. #include "TimeStats/TimeStats.h"
  60. #define DEBUG_RESIZE 0
  61. namespace android {
  62. using base::StringAppendF;
  63. std::atomic<int32_t> Layer::sSequence{1};
  64. Layer::Layer(const LayerCreationArgs& args)
  65. : mFlinger(args.flinger),
  66. mName(args.name),
  67. mSystemName(args.systemname),
  68. mClientRef(args.client),
  69. mWindowType(args.metadata.getInt32(METADATA_WINDOW_TYPE, 0)) {
  70. mCurrentCrop.makeInvalid();
  71. uint32_t layerFlags = 0;
  72. if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
  73. if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
  74. if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
  75. mTransactionName = String8("TX - ") + mName;
  76. mCurrentState.active_legacy.w = args.w;
  77. mCurrentState.active_legacy.h = args.h;
  78. mCurrentState.flags = layerFlags;
  79. mCurrentState.active_legacy.transform.set(0, 0);
  80. mCurrentState.crop_legacy.makeInvalid();
  81. mCurrentState.requestedCrop_legacy = mCurrentState.crop_legacy;
  82. mCurrentState.z = 0;
  83. mCurrentState.color.a = 1.0f;
  84. mCurrentState.layerStack = 0;
  85. mCurrentState.sequence = 0;
  86. mCurrentState.requested_legacy = mCurrentState.active_legacy;
  87. mCurrentState.active.w = UINT32_MAX;
  88. mCurrentState.active.h = UINT32_MAX;
  89. mCurrentState.active.transform.set(0, 0);
  90. mCurrentState.transform = 0;
  91. mCurrentState.transformToDisplayInverse = false;
  92. mCurrentState.crop.makeInvalid();
  93. mCurrentState.acquireFence = new Fence(-1);
  94. mCurrentState.dataspace = ui::Dataspace::UNKNOWN;
  95. mCurrentState.hdrMetadata.validTypes = 0;
  96. mCurrentState.surfaceDamageRegion.clear();
  97. mCurrentState.cornerRadius = 0.0f;
  98. mCurrentState.api = -1;
  99. mCurrentState.hasColorTransform = false;
  100. mCurrentState.colorSpaceAgnostic = false;
  101. mCurrentState.metadata = args.metadata;
  102. // drawing state & current state are identical
  103. mDrawingState = mCurrentState;
  104. CompositorTiming compositorTiming;
  105. args.flinger->getCompositorTiming(&compositorTiming);
  106. mFrameEventHistory.initializeCompositorTiming(compositorTiming);
  107. mFrameTracker.setDisplayRefreshPeriod(compositorTiming.interval);
  108. mSchedulerLayerHandle = mFlinger->mScheduler->registerLayer(mName.c_str(), mWindowType);
  109. mFlinger->onLayerCreated();
  110. }
  111. Layer::~Layer() {
  112. sp<Client> c(mClientRef.promote());
  113. if (c != 0) {
  114. c->detachLayer(this);
  115. }
  116. mFrameTracker.logAndResetStats(mName);
  117. mFlinger->onLayerDestroyed(this);
  118. }
  119. // ---------------------------------------------------------------------------
  120. // callbacks
  121. // ---------------------------------------------------------------------------
  122. /*
  123. * onLayerDisplayed is only meaningful for BufferLayer, but, is called through
  124. * Layer. So, the implementation is done in BufferLayer. When called on a
  125. * ColorLayer object, it's essentially a NOP.
  126. */
  127. void Layer::onLayerDisplayed(const sp<Fence>& /*releaseFence*/) {}
  128. void Layer::removeRemoteSyncPoints() {
  129. for (auto& point : mRemoteSyncPoints) {
  130. point->setTransactionApplied();
  131. }
  132. mRemoteSyncPoints.clear();
  133. {
  134. Mutex::Autolock pendingStateLock(mPendingStateMutex);
  135. for (State pendingState : mPendingStates) {
  136. pendingState.barrierLayer_legacy = nullptr;
  137. }
  138. }
  139. }
  140. void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
  141. if (mCurrentState.zOrderRelativeOf == nullptr) {
  142. return;
  143. }
  144. sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
  145. if (strongRelative == nullptr) {
  146. setZOrderRelativeOf(nullptr);
  147. return;
  148. }
  149. if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
  150. strongRelative->removeZOrderRelative(this);
  151. mFlinger->setTransactionFlags(eTraversalNeeded);
  152. setZOrderRelativeOf(nullptr);
  153. }
  154. }
  155. void Layer::removeFromCurrentState() {
  156. mRemovedFromCurrentState = true;
  157. // Since we are no longer reachable from CurrentState SurfaceFlinger
  158. // will no longer invoke doTransaction for us, and so we will
  159. // never finish applying transactions. We signal the sync point
  160. // now so that another layer will not become indefinitely
  161. // blocked.
  162. removeRemoteSyncPoints();
  163. {
  164. Mutex::Autolock syncLock(mLocalSyncPointMutex);
  165. for (auto& point : mLocalSyncPoints) {
  166. point->setFrameAvailable();
  167. }
  168. mLocalSyncPoints.clear();
  169. }
  170. mFlinger->markLayerPendingRemovalLocked(this);
  171. }
  172. void Layer::onRemovedFromCurrentState() {
  173. auto layersInTree = getLayersInTree(LayerVector::StateSet::Current);
  174. std::sort(layersInTree.begin(), layersInTree.end());
  175. for (const auto& layer : layersInTree) {
  176. layer->removeFromCurrentState();
  177. layer->removeRelativeZ(layersInTree);
  178. }
  179. }
  180. void Layer::addToCurrentState() {
  181. mRemovedFromCurrentState = false;
  182. for (const auto& child : mCurrentChildren) {
  183. child->addToCurrentState();
  184. }
  185. }
  186. // ---------------------------------------------------------------------------
  187. // set-up
  188. // ---------------------------------------------------------------------------
  189. const String8& Layer::getName() const {
  190. return mName;
  191. }
  192. bool Layer::getPremultipledAlpha() const {
  193. return mPremultipliedAlpha;
  194. }
  195. sp<IBinder> Layer::getHandle() {
  196. Mutex::Autolock _l(mLock);
  197. if (mGetHandleCalled) {
  198. ALOGE("Get handle called twice" );
  199. return nullptr;
  200. }
  201. mGetHandleCalled = true;
  202. return new Handle(mFlinger, this);
  203. }
  204. // ---------------------------------------------------------------------------
  205. // h/w composer set-up
  206. // ---------------------------------------------------------------------------
  207. bool Layer::hasHwcLayer(const sp<const DisplayDevice>& displayDevice) {
  208. auto outputLayer = findOutputLayerForDisplay(displayDevice);
  209. LOG_FATAL_IF(!outputLayer);
  210. return outputLayer->getState().hwc && (*outputLayer->getState().hwc).hwcLayer != nullptr;
  211. }
  212. HWC2::Layer* Layer::getHwcLayer(const sp<const DisplayDevice>& displayDevice) {
  213. auto outputLayer = findOutputLayerForDisplay(displayDevice);
  214. if (!outputLayer || !outputLayer->getState().hwc) {
  215. return nullptr;
  216. }
  217. return (*outputLayer->getState().hwc).hwcLayer.get();
  218. }
  219. Rect Layer::getContentCrop() const {
  220. // this is the crop rectangle that applies to the buffer
  221. // itself (as opposed to the window)
  222. Rect crop;
  223. if (!mCurrentCrop.isEmpty()) {
  224. // if the buffer crop is defined, we use that
  225. crop = mCurrentCrop;
  226. } else if (mActiveBuffer != nullptr) {
  227. // otherwise we use the whole buffer
  228. crop = mActiveBuffer->getBounds();
  229. } else {
  230. // if we don't have a buffer yet, we use an empty/invalid crop
  231. crop.makeInvalid();
  232. }
  233. return crop;
  234. }
  235. static Rect reduce(const Rect& win, const Region& exclude) {
  236. if (CC_LIKELY(exclude.isEmpty())) {
  237. return win;
  238. }
  239. if (exclude.isRect()) {
  240. return win.reduce(exclude.getBounds());
  241. }
  242. return Region(win).subtract(exclude).getBounds();
  243. }
  244. static FloatRect reduce(const FloatRect& win, const Region& exclude) {
  245. if (CC_LIKELY(exclude.isEmpty())) {
  246. return win;
  247. }
  248. // Convert through Rect (by rounding) for lack of FloatRegion
  249. return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
  250. }
  251. Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
  252. if (!reduceTransparentRegion) {
  253. return Rect{mScreenBounds};
  254. }
  255. FloatRect bounds = getBounds();
  256. ui::Transform t = getTransform();
  257. // Transform to screen space.
  258. bounds = t.transform(bounds);
  259. return Rect{bounds};
  260. }
  261. FloatRect Layer::getBounds() const {
  262. const State& s(getDrawingState());
  263. return getBounds(getActiveTransparentRegion(s));
  264. }
  265. FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
  266. // Subtract the transparent region and snap to the bounds.
  267. return reduce(mBounds, activeTransparentRegion);
  268. }
  269. ui::Transform Layer::getBufferScaleTransform() const {
  270. // If the layer is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
  271. // it isFixedSize) then there may be additional scaling not accounted
  272. // for in the layer transform.
  273. if (!isFixedSize() || !mActiveBuffer) {
  274. return {};
  275. }
  276. // If the layer is a buffer state layer, the active width and height
  277. // could be infinite. In that case, return the effective transform.
  278. const uint32_t activeWidth = getActiveWidth(getDrawingState());
  279. const uint32_t activeHeight = getActiveHeight(getDrawingState());
  280. if (activeWidth >= UINT32_MAX && activeHeight >= UINT32_MAX) {
  281. return {};
  282. }
  283. int bufferWidth = mActiveBuffer->getWidth();
  284. int bufferHeight = mActiveBuffer->getHeight();
  285. if (mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
  286. std::swap(bufferWidth, bufferHeight);
  287. }
  288. float sx = activeWidth / static_cast<float>(bufferWidth);
  289. float sy = activeHeight / static_cast<float>(bufferHeight);
  290. ui::Transform extraParentScaling;
  291. extraParentScaling.set(sx, 0, 0, sy);
  292. return extraParentScaling;
  293. }
  294. ui::Transform Layer::getTransformWithScale(const ui::Transform& bufferScaleTransform) const {
  295. // We need to mirror this scaling to child surfaces or we will break the contract where WM can
  296. // treat child surfaces as pixels in the parent surface.
  297. if (!isFixedSize() || !mActiveBuffer) {
  298. return mEffectiveTransform;
  299. }
  300. return mEffectiveTransform * bufferScaleTransform;
  301. }
  302. FloatRect Layer::getBoundsPreScaling(const ui::Transform& bufferScaleTransform) const {
  303. // We need the pre scaled layer bounds when computing child bounds to make sure the child is
  304. // cropped to its parent layer after any buffer transform scaling is applied.
  305. if (!isFixedSize() || !mActiveBuffer) {
  306. return mBounds;
  307. }
  308. return bufferScaleTransform.inverse().transform(mBounds);
  309. }
  310. void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform) {
  311. const State& s(getDrawingState());
  312. // Calculate effective layer transform
  313. mEffectiveTransform = parentTransform * getActiveTransform(s);
  314. // Transform parent bounds to layer space
  315. parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
  316. // Calculate source bounds
  317. mSourceBounds = computeSourceBounds(parentBounds);
  318. // Calculate bounds by croping diplay frame with layer crop and parent bounds
  319. FloatRect bounds = mSourceBounds;
  320. const Rect layerCrop = getCrop(s);
  321. if (!layerCrop.isEmpty()) {
  322. bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
  323. }
  324. bounds = bounds.intersect(parentBounds);
  325. mBounds = bounds;
  326. mScreenBounds = mEffectiveTransform.transform(mBounds);
  327. // Add any buffer scaling to the layer's children.
  328. ui::Transform bufferScaleTransform = getBufferScaleTransform();
  329. for (const sp<Layer>& child : mDrawingChildren) {
  330. child->computeBounds(getBoundsPreScaling(bufferScaleTransform),
  331. getTransformWithScale(bufferScaleTransform));
  332. }
  333. }
  334. Rect Layer::getCroppedBufferSize(const State& s) const {
  335. Rect size = getBufferSize(s);
  336. Rect crop = getCrop(s);
  337. if (!crop.isEmpty() && size.isValid()) {
  338. size.intersect(crop, &size);
  339. } else if (!crop.isEmpty()) {
  340. size = crop;
  341. }
  342. return size;
  343. }
  344. void Layer::setupRoundedCornersCropCoordinates(Rect win,
  345. const FloatRect& roundedCornersCrop) const {
  346. // Translate win by the rounded corners rect coordinates, to have all values in
  347. // layer coordinate space.
  348. win.left -= roundedCornersCrop.left;
  349. win.right -= roundedCornersCrop.left;
  350. win.top -= roundedCornersCrop.top;
  351. win.bottom -= roundedCornersCrop.top;
  352. }
  353. void Layer::latchGeometry(compositionengine::LayerFECompositionState& compositionState) const {
  354. const auto& drawingState{getDrawingState()};
  355. auto alpha = static_cast<float>(getAlpha());
  356. auto blendMode = HWC2::BlendMode::None;
  357. if (!isOpaque(drawingState) || alpha != 1.0f) {
  358. blendMode =
  359. mPremultipliedAlpha ? HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
  360. }
  361. int type = drawingState.metadata.getInt32(METADATA_WINDOW_TYPE, 0);
  362. int appId = drawingState.metadata.getInt32(METADATA_OWNER_UID, 0);
  363. sp<Layer> parent = mDrawingParent.promote();
  364. if (parent.get()) {
  365. auto& parentState = parent->getDrawingState();
  366. const int parentType = parentState.metadata.getInt32(METADATA_WINDOW_TYPE, 0);
  367. const int parentAppId = parentState.metadata.getInt32(METADATA_OWNER_UID, 0);
  368. if (parentType >= 0 || parentAppId >= 0) {
  369. type = parentType;
  370. appId = parentAppId;
  371. }
  372. }
  373. compositionState.geomLayerTransform = getTransform();
  374. compositionState.geomInverseLayerTransform = compositionState.geomLayerTransform.inverse();
  375. compositionState.geomBufferSize = getBufferSize(drawingState);
  376. compositionState.geomContentCrop = getContentCrop();
  377. compositionState.geomCrop = getCrop(drawingState);
  378. compositionState.geomBufferTransform = mCurrentTransform;
  379. compositionState.geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
  380. compositionState.geomActiveTransparentRegion = getActiveTransparentRegion(drawingState);
  381. compositionState.geomLayerBounds = mBounds;
  382. compositionState.geomUsesSourceCrop = usesSourceCrop();
  383. compositionState.isSecure = isSecure();
  384. compositionState.blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
  385. compositionState.alpha = alpha;
  386. compositionState.type = type;
  387. compositionState.appId = appId;
  388. }
  389. void Layer::latchCompositionState(compositionengine::LayerFECompositionState& compositionState,
  390. bool includeGeometry) const {
  391. if (includeGeometry) {
  392. latchGeometry(compositionState);
  393. }
  394. }
  395. const char* Layer::getDebugName() const {
  396. return mName.string();
  397. }
  398. void Layer::forceClientComposition(const sp<DisplayDevice>& display) {
  399. const auto outputLayer = findOutputLayerForDisplay(display);
  400. LOG_FATAL_IF(!outputLayer);
  401. outputLayer->editState().forceClientComposition = true;
  402. }
  403. bool Layer::getForceClientComposition(const sp<DisplayDevice>& display) {
  404. const auto outputLayer = findOutputLayerForDisplay(display);
  405. LOG_FATAL_IF(!outputLayer);
  406. return outputLayer->getState().forceClientComposition;
  407. }
  408. void Layer::updateCursorPosition(const sp<const DisplayDevice>& display) {
  409. const auto outputLayer = findOutputLayerForDisplay(display);
  410. LOG_FATAL_IF(!outputLayer);
  411. if (!outputLayer->getState().hwc ||
  412. (*outputLayer->getState().hwc).hwcCompositionType !=
  413. Hwc2::IComposerClient::Composition::CURSOR) {
  414. return;
  415. }
  416. // This gives us only the "orientation" component of the transform
  417. const State& s(getDrawingState());
  418. // Apply the layer's transform, followed by the display's global transform
  419. // Here we're guaranteed that the layer's transform preserves rects
  420. Rect win = getCroppedBufferSize(s);
  421. // Subtract the transparent region and snap to the bounds
  422. Rect bounds = reduce(win, getActiveTransparentRegion(s));
  423. Rect frame(getTransform().transform(bounds));
  424. frame.intersect(display->getViewport(), &frame);
  425. auto& displayTransform = display->getTransform();
  426. auto position = displayTransform.transform(frame);
  427. auto error =
  428. (*outputLayer->getState().hwc).hwcLayer->setCursorPosition(position.left, position.top);
  429. ALOGE_IF(error != HWC2::Error::None,
  430. "[%s] Failed to set cursor position "
  431. "to (%d, %d): %s (%d)",
  432. mName.string(), position.left, position.top, to_string(error).c_str(),
  433. static_cast<int32_t>(error));
  434. }
  435. // ---------------------------------------------------------------------------
  436. // drawing...
  437. // ---------------------------------------------------------------------------
  438. bool Layer::prepareClientLayer(const RenderArea& renderArea, const Region& clip,
  439. Region& clearRegion, const bool supportProtectedContent,
  440. renderengine::LayerSettings& layer) {
  441. return prepareClientLayer(renderArea, clip, false, clearRegion, supportProtectedContent, layer);
  442. }
  443. bool Layer::prepareClientLayer(const RenderArea& renderArea, bool useIdentityTransform,
  444. Region& clearRegion, const bool supportProtectedContent,
  445. renderengine::LayerSettings& layer) {
  446. return prepareClientLayer(renderArea, Region(renderArea.getBounds()), useIdentityTransform,
  447. clearRegion, supportProtectedContent, layer);
  448. }
  449. bool Layer::prepareClientLayer(const RenderArea& /*renderArea*/, const Region& /*clip*/,
  450. bool useIdentityTransform, Region& /*clearRegion*/,
  451. const bool /*supportProtectedContent*/,
  452. renderengine::LayerSettings& layer) {
  453. FloatRect bounds = getBounds();
  454. half alpha = getAlpha();
  455. layer.geometry.boundaries = bounds;
  456. if (useIdentityTransform) {
  457. layer.geometry.positionTransform = mat4();
  458. } else {
  459. const ui::Transform transform = getTransform();
  460. mat4 m;
  461. m[0][0] = transform[0][0];
  462. m[0][1] = transform[0][1];
  463. m[0][3] = transform[0][2];
  464. m[1][0] = transform[1][0];
  465. m[1][1] = transform[1][1];
  466. m[1][3] = transform[1][2];
  467. m[3][0] = transform[2][0];
  468. m[3][1] = transform[2][1];
  469. m[3][3] = transform[2][2];
  470. layer.geometry.positionTransform = m;
  471. }
  472. if (hasColorTransform()) {
  473. layer.colorTransform = getColorTransform();
  474. }
  475. const auto roundedCornerState = getRoundedCornerState();
  476. layer.geometry.roundedCornersRadius = roundedCornerState.radius;
  477. layer.geometry.roundedCornersCrop = roundedCornerState.cropRect;
  478. layer.alpha = alpha;
  479. layer.sourceDataspace = mCurrentDataSpace;
  480. return true;
  481. }
  482. void Layer::setCompositionType(const sp<const DisplayDevice>& display,
  483. Hwc2::IComposerClient::Composition type) {
  484. const auto outputLayer = findOutputLayerForDisplay(display);
  485. LOG_FATAL_IF(!outputLayer);
  486. LOG_FATAL_IF(!outputLayer->getState().hwc);
  487. auto& compositionState = outputLayer->editState();
  488. ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", ((*compositionState.hwc).hwcLayer)->getId(),
  489. toString(type).c_str(), 1);
  490. if ((*compositionState.hwc).hwcCompositionType != type) {
  491. ALOGV(" actually setting");
  492. (*compositionState.hwc).hwcCompositionType = type;
  493. auto error = (*compositionState.hwc)
  494. .hwcLayer->setCompositionType(static_cast<HWC2::Composition>(type));
  495. ALOGE_IF(error != HWC2::Error::None,
  496. "[%s] Failed to set "
  497. "composition type %s: %s (%d)",
  498. mName.string(), toString(type).c_str(), to_string(error).c_str(),
  499. static_cast<int32_t>(error));
  500. }
  501. }
  502. Hwc2::IComposerClient::Composition Layer::getCompositionType(
  503. const sp<const DisplayDevice>& display) const {
  504. const auto outputLayer = findOutputLayerForDisplay(display);
  505. LOG_FATAL_IF(!outputLayer);
  506. return outputLayer->getState().hwc ? (*outputLayer->getState().hwc).hwcCompositionType
  507. : Hwc2::IComposerClient::Composition::CLIENT;
  508. }
  509. bool Layer::getClearClientTarget(const sp<const DisplayDevice>& display) const {
  510. const auto outputLayer = findOutputLayerForDisplay(display);
  511. LOG_FATAL_IF(!outputLayer);
  512. return outputLayer->getState().clearClientTarget;
  513. }
  514. bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
  515. if (point->getFrameNumber() <= mCurrentFrameNumber) {
  516. // Don't bother with a SyncPoint, since we've already latched the
  517. // relevant frame
  518. return false;
  519. }
  520. if (isRemovedFromCurrentState()) {
  521. return false;
  522. }
  523. Mutex::Autolock lock(mLocalSyncPointMutex);
  524. mLocalSyncPoints.push_back(point);
  525. return true;
  526. }
  527. // ----------------------------------------------------------------------------
  528. // local state
  529. // ----------------------------------------------------------------------------
  530. void Layer::computeGeometry(const RenderArea& renderArea,
  531. renderengine::Mesh& mesh,
  532. bool useIdentityTransform) const {
  533. const ui::Transform renderAreaTransform(renderArea.getTransform());
  534. FloatRect win = getBounds();
  535. vec2 lt = vec2(win.left, win.top);
  536. vec2 lb = vec2(win.left, win.bottom);
  537. vec2 rb = vec2(win.right, win.bottom);
  538. vec2 rt = vec2(win.right, win.top);
  539. ui::Transform layerTransform = getTransform();
  540. if (!useIdentityTransform) {
  541. lt = layerTransform.transform(lt);
  542. lb = layerTransform.transform(lb);
  543. rb = layerTransform.transform(rb);
  544. rt = layerTransform.transform(rt);
  545. }
  546. renderengine::Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
  547. position[0] = renderAreaTransform.transform(lt);
  548. position[1] = renderAreaTransform.transform(lb);
  549. position[2] = renderAreaTransform.transform(rb);
  550. position[3] = renderAreaTransform.transform(rt);
  551. }
  552. bool Layer::isSecure() const {
  553. const State& s(mDrawingState);
  554. return (s.flags & layer_state_t::eLayerSecure);
  555. }
  556. void Layer::setVisibleRegion(const Region& visibleRegion) {
  557. // always called from main thread
  558. this->visibleRegion = visibleRegion;
  559. }
  560. void Layer::setCoveredRegion(const Region& coveredRegion) {
  561. // always called from main thread
  562. this->coveredRegion = coveredRegion;
  563. }
  564. void Layer::setVisibleNonTransparentRegion(const Region& setVisibleNonTransparentRegion) {
  565. // always called from main thread
  566. this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
  567. }
  568. void Layer::clearVisibilityRegions() {
  569. visibleRegion.clear();
  570. visibleNonTransparentRegion.clear();
  571. coveredRegion.clear();
  572. }
  573. // ----------------------------------------------------------------------------
  574. // transaction
  575. // ----------------------------------------------------------------------------
  576. void Layer::pushPendingState() {
  577. if (!mCurrentState.modified) {
  578. return;
  579. }
  580. ATRACE_CALL();
  581. // If this transaction is waiting on the receipt of a frame, generate a sync
  582. // point and send it to the remote layer.
  583. // We don't allow installing sync points after we are removed from the current state
  584. // as we won't be able to signal our end.
  585. if (mCurrentState.barrierLayer_legacy != nullptr && !isRemovedFromCurrentState()) {
  586. sp<Layer> barrierLayer = mCurrentState.barrierLayer_legacy.promote();
  587. if (barrierLayer == nullptr) {
  588. ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
  589. // If we can't promote the layer we are intended to wait on,
  590. // then it is expired or otherwise invalid. Allow this transaction
  591. // to be applied as per normal (no synchronization).
  592. mCurrentState.barrierLayer_legacy = nullptr;
  593. } else {
  594. auto syncPoint = std::make_shared<SyncPoint>(mCurrentState.frameNumber_legacy, this);
  595. if (barrierLayer->addSyncPoint(syncPoint)) {
  596. std::stringstream ss;
  597. ss << "Adding sync point " << mCurrentState.frameNumber_legacy;
  598. ATRACE_NAME(ss.str().c_str());
  599. mRemoteSyncPoints.push_back(std::move(syncPoint));
  600. } else {
  601. // We already missed the frame we're supposed to synchronize
  602. // on, so go ahead and apply the state update
  603. mCurrentState.barrierLayer_legacy = nullptr;
  604. }
  605. }
  606. // Wake us up to check if the frame has been received
  607. setTransactionFlags(eTransactionNeeded);
  608. mFlinger->setTransactionFlags(eTraversalNeeded);
  609. }
  610. mPendingStates.push_back(mCurrentState);
  611. ATRACE_INT(mTransactionName.string(), mPendingStates.size());
  612. }
  613. void Layer::popPendingState(State* stateToCommit) {
  614. ATRACE_CALL();
  615. *stateToCommit = mPendingStates[0];
  616. mPendingStates.removeAt(0);
  617. ATRACE_INT(mTransactionName.string(), mPendingStates.size());
  618. }
  619. bool Layer::applyPendingStates(State* stateToCommit) {
  620. bool stateUpdateAvailable = false;
  621. while (!mPendingStates.empty()) {
  622. if (mPendingStates[0].barrierLayer_legacy != nullptr) {
  623. if (mRemoteSyncPoints.empty()) {
  624. // If we don't have a sync point for this, apply it anyway. It
  625. // will be visually wrong, but it should keep us from getting
  626. // into too much trouble.
  627. ALOGE("[%s] No local sync point found", mName.string());
  628. popPendingState(stateToCommit);
  629. stateUpdateAvailable = true;
  630. continue;
  631. }
  632. if (mRemoteSyncPoints.front()->getFrameNumber() !=
  633. mPendingStates[0].frameNumber_legacy) {
  634. ALOGE("[%s] Unexpected sync point frame number found", mName.string());
  635. // Signal our end of the sync point and then dispose of it
  636. mRemoteSyncPoints.front()->setTransactionApplied();
  637. mRemoteSyncPoints.pop_front();
  638. continue;
  639. }
  640. if (mRemoteSyncPoints.front()->frameIsAvailable()) {
  641. ATRACE_NAME("frameIsAvailable");
  642. // Apply the state update
  643. popPendingState(stateToCommit);
  644. stateUpdateAvailable = true;
  645. // Signal our end of the sync point and then dispose of it
  646. mRemoteSyncPoints.front()->setTransactionApplied();
  647. mRemoteSyncPoints.pop_front();
  648. } else {
  649. ATRACE_NAME("!frameIsAvailable");
  650. break;
  651. }
  652. } else {
  653. popPendingState(stateToCommit);
  654. stateUpdateAvailable = true;
  655. }
  656. }
  657. // If we still have pending updates, wake SurfaceFlinger back up and point
  658. // it at this layer so we can process them
  659. if (!mPendingStates.empty()) {
  660. setTransactionFlags(eTransactionNeeded);
  661. mFlinger->setTransactionFlags(eTraversalNeeded);
  662. }
  663. mCurrentState.modified = false;
  664. return stateUpdateAvailable;
  665. }
  666. uint32_t Layer::doTransactionResize(uint32_t flags, State* stateToCommit) {
  667. const State& s(getDrawingState());
  668. const bool sizeChanged = (stateToCommit->requested_legacy.w != s.requested_legacy.w) ||
  669. (stateToCommit->requested_legacy.h != s.requested_legacy.h);
  670. if (sizeChanged) {
  671. // the size changed, we need to ask our client to request a new buffer
  672. ALOGD_IF(DEBUG_RESIZE,
  673. "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
  674. " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
  675. " requested={ wh={%4u,%4u} }}\n"
  676. " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
  677. " requested={ wh={%4u,%4u} }}\n",
  678. this, getName().string(), mCurrentTransform, getEffectiveScalingMode(),
  679. stateToCommit->active_legacy.w, stateToCommit->active_legacy.h,
  680. stateToCommit->crop_legacy.left, stateToCommit->crop_legacy.top,
  681. stateToCommit->crop_legacy.right, stateToCommit->crop_legacy.bottom,
  682. stateToCommit->crop_legacy.getWidth(), stateToCommit->crop_legacy.getHeight(),
  683. stateToCommit->requested_legacy.w, stateToCommit->requested_legacy.h,
  684. s.active_legacy.w, s.active_legacy.h, s.crop_legacy.left, s.crop_legacy.top,
  685. s.crop_legacy.right, s.crop_legacy.bottom, s.crop_legacy.getWidth(),
  686. s.crop_legacy.getHeight(), s.requested_legacy.w, s.requested_legacy.h);
  687. }
  688. // Don't let Layer::doTransaction update the drawing state
  689. // if we have a pending resize, unless we are in fixed-size mode.
  690. // the drawing state will be updated only once we receive a buffer
  691. // with the correct size.
  692. //
  693. // In particular, we want to make sure the clip (which is part
  694. // of the geometry state) is latched together with the size but is
  695. // latched immediately when no resizing is involved.
  696. //
  697. // If a sideband stream is attached, however, we want to skip this
  698. // optimization so that transactions aren't missed when a buffer
  699. // never arrives
  700. //
  701. // In the case that we don't have a buffer we ignore other factors
  702. // and avoid entering the resizePending state. At a high level the
  703. // resizePending state is to avoid applying the state of the new buffer
  704. // to the old buffer. However in the state where we don't have an old buffer
  705. // there is no such concern but we may still be being used as a parent layer.
  706. const bool resizePending =
  707. ((stateToCommit->requested_legacy.w != stateToCommit->active_legacy.w) ||
  708. (stateToCommit->requested_legacy.h != stateToCommit->active_legacy.h)) &&
  709. (mActiveBuffer != nullptr);
  710. if (!isFixedSize()) {
  711. if (resizePending && mSidebandStream == nullptr) {
  712. flags |= eDontUpdateGeometryState;
  713. }
  714. }
  715. // Here we apply various requested geometry states, depending on our
  716. // latching configuration. See Layer.h for a detailed discussion of
  717. // how geometry latching is controlled.
  718. if (!(flags & eDontUpdateGeometryState)) {
  719. State& editCurrentState(getCurrentState());
  720. // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
  721. // mode, which causes attributes which normally latch regardless of scaling mode,
  722. // to be delayed. We copy the requested state to the active state making sure
  723. // to respect these rules (again see Layer.h for a detailed discussion).
  724. //
  725. // There is an awkward asymmetry in the handling of the crop states in the position
  726. // states, as can be seen below. Largely this arises from position and transform
  727. // being stored in the same data structure while having different latching rules.
  728. // b/38182305
  729. //
  730. // Careful that "stateToCommit" and editCurrentState may not begin as equivalent due to
  731. // applyPendingStates in the presence of deferred transactions.
  732. if (mFreezeGeometryUpdates) {
  733. float tx = stateToCommit->active_legacy.transform.tx();
  734. float ty = stateToCommit->active_legacy.transform.ty();
  735. stateToCommit->active_legacy = stateToCommit->requested_legacy;
  736. stateToCommit->active_legacy.transform.set(tx, ty);
  737. editCurrentState.active_legacy = stateToCommit->active_legacy;
  738. } else {
  739. editCurrentState.active_legacy = editCurrentState.requested_legacy;
  740. stateToCommit->active_legacy = stateToCommit->requested_legacy;
  741. }
  742. }
  743. return flags;
  744. }
  745. uint32_t Layer::doTransaction(uint32_t flags) {
  746. ATRACE_CALL();
  747. if (mLayerDetached) {
  748. return flags;
  749. }
  750. if (mChildrenChanged) {
  751. flags |= eVisibleRegion;
  752. mChildrenChanged = false;
  753. }
  754. pushPendingState();
  755. State c = getCurrentState();
  756. if (!applyPendingStates(&c)) {
  757. return flags;
  758. }
  759. flags = doTransactionResize(flags, &c);
  760. const State& s(getDrawingState());
  761. if (getActiveGeometry(c) != getActiveGeometry(s)) {
  762. // invalidate and recompute the visible regions if needed
  763. flags |= Layer::eVisibleRegion;
  764. }
  765. if (c.sequence != s.sequence) {
  766. // invalidate and recompute the visible regions if needed
  767. flags |= eVisibleRegion;
  768. this->contentDirty = true;
  769. // we may use linear filtering, if the matrix scales us
  770. const uint8_t type = getActiveTransform(c).getType();
  771. mNeedsFiltering = (!getActiveTransform(c).preserveRects() || type >= ui::Transform::SCALE);
  772. }
  773. if (mCurrentState.inputInfoChanged) {
  774. flags |= eInputInfoChanged;
  775. mCurrentState.inputInfoChanged = false;
  776. }
  777. // Commit the transaction
  778. commitTransaction(c);
  779. mCurrentState.callbackHandles = {};
  780. return flags;
  781. }
  782. void Layer::commitTransaction(const State& stateToCommit) {
  783. mDrawingState = stateToCommit;
  784. }
  785. uint32_t Layer::getTransactionFlags(uint32_t flags) {
  786. return mTransactionFlags.fetch_and(~flags) & flags;
  787. }
  788. uint32_t Layer::setTransactionFlags(uint32_t flags) {
  789. return mTransactionFlags.fetch_or(flags);
  790. }
  791. bool Layer::setPosition(float x, float y, bool immediate) {
  792. if (mCurrentState.requested_legacy.transform.tx() == x &&
  793. mCurrentState.requested_legacy.transform.ty() == y)
  794. return false;
  795. mCurrentState.sequence++;
  796. // We update the requested and active position simultaneously because
  797. // we want to apply the position portion of the transform matrix immediately,
  798. // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
  799. mCurrentState.requested_legacy.transform.set(x, y);
  800. if (immediate && !mFreezeGeometryUpdates) {
  801. // Here we directly update the active state
  802. // unlike other setters, because we store it within
  803. // the transform, but use different latching rules.
  804. // b/38182305
  805. mCurrentState.active_legacy.transform.set(x, y);
  806. }
  807. mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
  808. mCurrentState.modified = true;
  809. setTransactionFlags(eTransactionNeeded);
  810. return true;
  811. }
  812. bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
  813. ssize_t idx = mCurrentChildren.indexOf(childLayer);
  814. if (idx < 0) {
  815. return false;
  816. }
  817. if (childLayer->setLayer(z)) {
  818. mCurrentChildren.removeAt(idx);
  819. mCurrentChildren.add(childLayer);
  820. return true;
  821. }
  822. return false;
  823. }
  824. bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
  825. const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
  826. ssize_t idx = mCurrentChildren.indexOf(childLayer);
  827. if (idx < 0) {
  828. return false;
  829. }
  830. if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
  831. mCurrentChildren.removeAt(idx);
  832. mCurrentChildren.add(childLayer);
  833. return true;
  834. }
  835. return false;
  836. }
  837. bool Layer::setLayer(int32_t z) {
  838. if (mCurrentState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
  839. mCurrentState.sequence++;
  840. mCurrentState.z = z;
  841. mCurrentState.modified = true;
  842. // Discard all relative layering.
  843. if (mCurrentState.zOrderRelativeOf != nullptr) {
  844. sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
  845. if (strongRelative != nullptr) {
  846. strongRelative->removeZOrderRelative(this);
  847. }
  848. setZOrderRelativeOf(nullptr);
  849. }
  850. setTransactionFlags(eTransactionNeeded);
  851. return true;
  852. }
  853. void Layer::removeZOrderRelative(const wp<Layer>& relative) {
  854. mCurrentState.zOrderRelatives.remove(relative);
  855. mCurrentState.sequence++;
  856. mCurrentState.modified = true;
  857. setTransactionFlags(eTransactionNeeded);
  858. }
  859. void Layer::addZOrderRelative(const wp<Layer>& relative) {
  860. mCurrentState.zOrderRelatives.add(relative);
  861. mCurrentState.modified = true;
  862. mCurrentState.sequence++;
  863. setTransactionFlags(eTransactionNeeded);
  864. }
  865. void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
  866. mCurrentState.zOrderRelativeOf = relativeOf;
  867. mCurrentState.sequence++;
  868. mCurrentState.modified = true;
  869. setTransactionFlags(eTransactionNeeded);
  870. }
  871. bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
  872. sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
  873. if (handle == nullptr) {
  874. return false;
  875. }
  876. sp<Layer> relative = handle->owner.promote();
  877. if (relative == nullptr) {
  878. return false;
  879. }
  880. if (mCurrentState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
  881. mCurrentState.zOrderRelativeOf == relative) {
  882. return false;
  883. }
  884. mCurrentState.sequence++;
  885. mCurrentState.modified = true;
  886. mCurrentState.z = relativeZ;
  887. auto oldZOrderRelativeOf = mCurrentState.zOrderRelativeOf.promote();
  888. if (oldZOrderRelativeOf != nullptr) {
  889. oldZOrderRelativeOf->removeZOrderRelative(this);
  890. }
  891. setZOrderRelativeOf(relative);
  892. relative->addZOrderRelative(this);
  893. setTransactionFlags(eTransactionNeeded);
  894. return true;
  895. }
  896. bool Layer::setSize(uint32_t w, uint32_t h) {
  897. if (mCurrentState.requested_legacy.w == w && mCurrentState.requested_legacy.h == h)
  898. return false;
  899. mCurrentState.requested_legacy.w = w;
  900. mCurrentState.requested_legacy.h = h;
  901. mCurrentState.modified = true;
  902. setTransactionFlags(eTransactionNeeded);
  903. // record the new size, from this point on, when the client request
  904. // a buffer, it'll get the new size.
  905. setDefaultBufferSize(mCurrentState.requested_legacy.w, mCurrentState.requested_legacy.h);
  906. return true;
  907. }
  908. bool Layer::setAlpha(float alpha) {
  909. if (mCurrentState.color.a == alpha) return false;
  910. mCurrentState.sequence++;
  911. mCurrentState.color.a = alpha;
  912. mCurrentState.modified = true;
  913. setTransactionFlags(eTransactionNeeded);
  914. return true;
  915. }
  916. bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
  917. if (!mCurrentState.bgColorLayer && alpha == 0) {
  918. return false;
  919. }
  920. mCurrentState.sequence++;
  921. mCurrentState.modified = true;
  922. setTransactionFlags(eTransactionNeeded);
  923. if (!mCurrentState.bgColorLayer && alpha != 0) {
  924. // create background color layer if one does not yet exist
  925. uint32_t flags = ISurfaceComposerClient::eFXSurfaceColor;
  926. const String8& name = mName + "BackgroundColorLayer";
  927. mCurrentState.bgColorLayer = new ColorLayer(
  928. LayerCreationArgs(mFlinger.get(), nullptr, name, mSystemName, 0, 0, flags, LayerMetadata()));
  929. // add to child list
  930. addChild(mCurrentState.bgColorLayer);
  931. mFlinger->mLayersAdded = true;
  932. // set up SF to handle added color layer
  933. if (isRemovedFromCurrentState()) {
  934. mCurrentState.bgColorLayer->onRemovedFromCurrentState();
  935. }
  936. mFlinger->setTransactionFlags(eTransactionNeeded);
  937. } else if (mCurrentState.bgColorLayer && alpha == 0) {
  938. mCurrentState.bgColorLayer->reparent(nullptr);
  939. mCurrentState.bgColorLayer = nullptr;
  940. return true;
  941. }
  942. mCurrentState.bgColorLayer->setColor(color);
  943. mCurrentState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
  944. mCurrentState.bgColorLayer->setAlpha(alpha);
  945. mCurrentState.bgColorLayer->setDataspace(dataspace);
  946. return true;
  947. }
  948. bool Layer::setCornerRadius(float cornerRadius) {
  949. if (mCurrentState.cornerRadius == cornerRadius) return false;
  950. mCurrentState.sequence++;
  951. mCurrentState.cornerRadius = cornerRadius;
  952. mCurrentState.modified = true;
  953. setTransactionFlags(eTransactionNeeded);
  954. return true;
  955. }
  956. bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix,
  957. bool allowNonRectPreservingTransforms) {
  958. ui::Transform t;
  959. t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
  960. if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
  961. ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER ignored");
  962. return false;
  963. }
  964. mCurrentState.sequence++;
  965. mCurrentState.requested_legacy.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx,
  966. matrix.dsdy);
  967. mCurrentState.modified = true;
  968. setTransactionFlags(eTransactionNeeded);
  969. return true;
  970. }
  971. bool Layer::setTransparentRegionHint(const Region& transparent) {
  972. mCurrentState.requestedTransparentRegion_legacy = transparent;
  973. mCurrentState.modified = true;
  974. setTransactionFlags(eTransactionNeeded);
  975. return true;
  976. }
  977. bool Layer::setFlags(uint8_t flags, uint8_t mask) {
  978. const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
  979. if (mCurrentState.flags == newFlags) return false;
  980. mCurrentState.sequence++;
  981. mCurrentState.flags = newFlags;
  982. mCurrentState.modified = true;
  983. setTransactionFlags(eTransactionNeeded);
  984. return true;
  985. }
  986. bool Layer::setCrop_legacy(const Rect& crop, bool immediate) {
  987. if (mCurrentState.requestedCrop_legacy == crop) return false;
  988. mCurrentState.sequence++;
  989. mCurrentState.requestedCrop_legacy = crop;
  990. if (immediate && !mFreezeGeometryUpdates) {
  991. mCurrentState.crop_legacy = crop;
  992. }
  993. mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
  994. mCurrentState.modified = true;
  995. setTransactionFlags(eTransactionNeeded);
  996. return true;
  997. }
  998. bool Layer::setOverrideScalingMode(int32_t scalingMode) {
  999. if (scalingMode == mOverrideScalingMode) return false;
  1000. mOverrideScalingMode = scalingMode;
  1001. setTransactionFlags(eTransactionNeeded);
  1002. return true;
  1003. }
  1004. bool Layer::setMetadata(const LayerMetadata& data) {
  1005. if (!mCurrentState.metadata.merge(data, true /* eraseEmpty */)) return false;
  1006. mCurrentState.sequence++;
  1007. mCurrentState.modified = true;
  1008. setTransactionFlags(eTransactionNeeded);
  1009. return true;
  1010. }
  1011. bool Layer::setLayerStack(uint32_t layerStack) {
  1012. if (mCurrentState.layerStack == layerStack) return false;
  1013. mCurrentState.sequence++;
  1014. mCurrentState.layerStack = layerStack;
  1015. mCurrentState.modified = true;
  1016. setTransactionFlags(eTransactionNeeded);
  1017. return true;
  1018. }
  1019. bool Layer::setColorSpaceAgnostic(const bool agnostic) {
  1020. if (mCurrentState.colorSpaceAgnostic == agnostic) {
  1021. return false;
  1022. }
  1023. mCurrentState.sequence++;
  1024. mCurrentState.colorSpaceAgnostic = agnostic;
  1025. mCurrentState.modified = true;
  1026. setTransactionFlags(eTransactionNeeded);
  1027. return true;
  1028. }
  1029. uint32_t Layer::getLayerStack() const {
  1030. auto p = mDrawingParent.promote();
  1031. if (p == nullptr) {
  1032. return getDrawingState().layerStack;
  1033. }
  1034. return p->getLayerStack();
  1035. }
  1036. void Layer::deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber) {
  1037. ATRACE_CALL();
  1038. mCurrentState.barrierLayer_legacy = barrierLayer;
  1039. mCurrentState.frameNumber_legacy = frameNumber;
  1040. // We don't set eTransactionNeeded, because just receiving a deferral
  1041. // request without any other state updates shouldn't actually induce a delay
  1042. mCurrentState.modified = true;
  1043. pushPendingState();
  1044. mCurrentState.barrierLayer_legacy = nullptr;
  1045. mCurrentState.frameNumber_legacy = 0;
  1046. mCurrentState.modified = false;
  1047. }
  1048. void Layer::deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle, uint64_t frameNumber) {
  1049. sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
  1050. deferTransactionUntil_legacy(handle->owner.promote(), frameNumber);
  1051. }
  1052. // ----------------------------------------------------------------------------
  1053. // pageflip handling...
  1054. // ----------------------------------------------------------------------------
  1055. bool Layer::isHiddenByPolicy() const {
  1056. const State& s(mDrawingState);
  1057. const auto& parent = mDrawingParent.promote();
  1058. if (parent != nullptr && parent->isHiddenByPolicy()) {
  1059. return true;
  1060. }
  1061. if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
  1062. auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
  1063. if (zOrderRelativeOf != nullptr) {
  1064. if (zOrderRelativeOf->isHiddenByPolicy()) {
  1065. return true;
  1066. }
  1067. }
  1068. }
  1069. return s.flags & layer_state_t::eLayerHidden;
  1070. }
  1071. uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
  1072. // TODO: should we do something special if mSecure is set?
  1073. if (mProtectedByApp) {
  1074. // need a hardware-protected path to external video sink
  1075. usage |= GraphicBuffer::USAGE_PROTECTED;
  1076. }
  1077. if (mPotentialCursor) {
  1078. usage |= GraphicBuffer::USAGE_CURSOR;
  1079. }
  1080. usage |= GraphicBuffer::USAGE_HW_COMPOSER;
  1081. return usage;
  1082. }
  1083. void Layer::updateTransformHint(const sp<const DisplayDevice>& display) const {
  1084. uint32_t orientation = 0;
  1085. // Disable setting transform hint if the debug flag is set.
  1086. if (!mFlinger->mDebugDisableTransformHint) {
  1087. // The transform hint is used to improve performance, but we can
  1088. // only have a single transform hint, it cannot
  1089. // apply to all displays.
  1090. const ui::Transform& planeTransform = display->getTransform();
  1091. orientation = planeTransform.getOrientation();
  1092. if (orientation & ui::Transform::ROT_INVALID) {
  1093. orientation = 0;
  1094. }
  1095. }
  1096. setTransformHint(orientation);
  1097. }
  1098. // ----------------------------------------------------------------------------
  1099. // debugging
  1100. // ----------------------------------------------------------------------------
  1101. // TODO(marissaw): add new layer state info to layer debugging
  1102. LayerDebugInfo Layer::getLayerDebugInfo() const {
  1103. LayerDebugInfo info;
  1104. const State& ds = getDrawingState();
  1105. info.mName = getName();
  1106. sp<Layer> parent = getParent();
  1107. info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
  1108. info.mType = std::string(getTypeId());
  1109. info.mTransparentRegion = ds.activeTransparentRegion_legacy;
  1110. info.mVisibleRegion = visibleRegion;
  1111. info.mSurfaceDamageRegion = surfaceDamageRegion;
  1112. info.mLayerStack = getLayerStack();
  1113. info.mX = ds.active_legacy.transform.tx();
  1114. info.mY = ds.active_legacy.transform.ty();
  1115. info.mZ = ds.z;
  1116. info.mWidth = ds.active_legacy.w;
  1117. info.mHeight = ds.active_legacy.h;
  1118. info.mCrop = ds.crop_legacy;
  1119. info.mColor = ds.color;
  1120. info.mFlags = ds.flags;
  1121. info.mPixelFormat = getPixelFormat();
  1122. info.mDataSpace = static_cast<android_dataspace>(mCurrentDataSpace);
  1123. info.mMatrix[0][0] = ds.active_legacy.transform[0][0];
  1124. info.mMatrix[0][1] = ds.active_legacy.transform[0][1];
  1125. info.mMatrix[1][0] = ds.active_legacy.transform[1][0];
  1126. info.mMatrix[1][1] = ds.active_legacy.transform[1][1];
  1127. {
  1128. sp<const GraphicBuffer> buffer = mActiveBuffer;
  1129. if (buffer != 0) {
  1130. info.mActiveBufferWidth = buffer->getWidth();
  1131. info.mActiveBufferHeight = buffer->getHeight();
  1132. info.mActiveBufferStride = buffer->getStride();
  1133. info.mActiveBufferFormat = buffer->format;
  1134. } else {
  1135. info.mActiveBufferWidth = 0;
  1136. info.mActiveBufferHeight = 0;
  1137. info.mActiveBufferStride = 0;
  1138. info.mActiveBufferFormat = 0;
  1139. }
  1140. }
  1141. info.mNumQueuedFrames = getQueuedFrameCount();
  1142. info.mRefreshPending = isBufferLatched();
  1143. info.mIsOpaque = isOpaque(ds);
  1144. info.mContentDirty = contentDirty;
  1145. return info;
  1146. }
  1147. void Layer::miniDumpHeader(std::string& result) {
  1148. result.append("-------------------------------");
  1149. result.append("-------------------------------");
  1150. result.append("-----------------------------\n");
  1151. result.append(" Layer name\n");
  1152. result.append(" System name\n");
  1153. result.append(" Z | ");
  1154. result.append(" Window Type | ");
  1155. result.append(" Comp Type | ");
  1156. result.append(" Transform | ");
  1157. result.append(" Disp Frame (LTRB) | ");
  1158. result.append(" Source Crop (LTRB)\n");
  1159. result.append("-------------------------------");
  1160. result.append("-------------------------------");
  1161. result.append("-----------------------------\n");
  1162. }
  1163. void Layer::miniDump(std::string& result, const sp<DisplayDevice>& displayDevice) const {
  1164. auto outputLayer = findOutputLayerForDisplay(displayDevice);
  1165. if (!outputLayer) {
  1166. return;
  1167. }
  1168. std::string name;
  1169. if (mName.length() > 77) {
  1170. std::string shortened;
  1171. shortened.append(mName.string(), 36);
  1172. shortened.append("[...]");
  1173. shortened.append(mName.string() + (mName.length() - 36), 36);
  1174. name = shortened;
  1175. } else {
  1176. name = std::string(mName.string(), mName.size());
  1177. }
  1178. StringAppendF(&result, " %s\n", name.c_str());
  1179. StringAppendF(&result, " %s\n", mSystemName.c_str());
  1180. const State& layerState(getDrawingState());
  1181. const auto& compositionState = outputLayer->getState();
  1182. if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
  1183. StringAppendF(&result, " rel %6d | ", layerState.z);
  1184. } else {
  1185. StringAppendF(&result, " %10d | ", layerState.z);
  1186. }
  1187. StringAppendF(&result, " %10d | ", mWindowType);
  1188. StringAppendF(&result, "%10s | ", toString(getCompositionType(displayDevice)).c_str());
  1189. StringAppendF(&result, "%10s | ",
  1190. toString(getCompositionLayer() ? compositionState.bufferTransform
  1191. : static_cast<Hwc2::Transform>(0))
  1192. .c_str());
  1193. const Rect& frame = compositionState.displayFrame;
  1194. StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
  1195. const FloatRect& crop = compositionState.sourceCrop;
  1196. StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, crop.right,
  1197. crop.bottom);
  1198. result.append("- - - - - - - - - - - - - - - -");
  1199. result.append("- - - - - - - - - - - - - - - -");
  1200. result.append("- - - - - - - - - - - - - - -\n");
  1201. }
  1202. void Layer::dumpFrameStats(std::string& result) const {
  1203. mFrameTracker.dumpStats(result);
  1204. }
  1205. void Layer::clearFrameStats() {
  1206. mFrameTracker.clearStats();
  1207. }
  1208. void Layer::logFrameStats() {
  1209. mFrameTracker.logAndResetStats(mName);
  1210. }
  1211. void Layer::getFrameStats(FrameStats* outStats) const {
  1212. mFrameTracker.getStats(outStats);
  1213. }
  1214. const char* Layer::systemName() const{
  1215. return mSystemName.string();
  1216. }
  1217. const String8& Layer::getSystemName() const{
  1218. return mSystemName;
  1219. }
  1220. void Layer::dumpFrameEvents(std::string& result) {
  1221. StringAppendF(&result, "- Layer %s (%s, %p)\n", getName().string(), getTypeId(), this);
  1222. Mutex::Autolock lock(mFrameEventHistoryMutex);
  1223. mFrameEventHistory.checkFencesForCompletion();
  1224. mFrameEventHistory.dump(result);
  1225. }
  1226. void Layer::onDisconnect() {
  1227. Mutex::Autolock lock(mFrameEventHistoryMutex);
  1228. mFrameEventHistory.onDisconnect();
  1229. mFlinger->mTimeStats->onDestroy(getSequence());
  1230. }
  1231. void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
  1232. FrameEventHistoryDelta* outDelta) {
  1233. if (newTimestamps) {
  1234. mFlinger->mTimeStats->setPostTime(getSequence(), newTimestamps->frameNumber,
  1235. getName().c_str(), newTimestamps->postedTime);
  1236. }
  1237. Mutex::Autolock lock(mFrameEventHistoryMutex);
  1238. if (newTimestamps) {
  1239. // If there are any unsignaled fences in the aquire timeline at this
  1240. // point, the previously queued frame hasn't been latched yet. Go ahead
  1241. // and try to get the signal time here so the syscall is taken out of
  1242. // the main thread's critical path.
  1243. mAcquireTimeline.updateSignalTimes();
  1244. // Push the new fence after updating since it's likely still pending.
  1245. mAcquireTimeline.push(newTimestamps->acquireFence);
  1246. mFrameEventHistory.addQueue(*newTimestamps);
  1247. }
  1248. if (outDelta) {
  1249. mFrameEventHistory.getAndResetDelta(outDelta);
  1250. }
  1251. }
  1252. size_t Layer::getChildrenCount() const {
  1253. size_t count = 0;
  1254. for (const sp<Layer>& child : mCurrentChildren) {
  1255. count += 1 + child->getChildrenCount();
  1256. }
  1257. return count;
  1258. }
  1259. void Layer::addChild(const sp<Layer>& layer) {
  1260. mChildrenChanged = true;
  1261. setTransactionFlags(eTransactionNeeded);
  1262. mCurrentChildren.add(layer);
  1263. layer->setParent(this);
  1264. }
  1265. ssize_t Layer::removeChild(const sp<Layer>& layer) {
  1266. mChildrenChanged = true;
  1267. setTransactionFlags(eTransactionNeeded);
  1268. layer->setParent(nullptr);
  1269. return mCurrentChildren.remove(layer);
  1270. }
  1271. bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
  1272. sp<Handle> handle = nullptr;
  1273. sp<Layer> newParent = nullptr;
  1274. if (newParentHandle == nullptr) {
  1275. return false;
  1276. }
  1277. handle = static_cast<Handle*>(newParentHandle.get());
  1278. newParent = handle->owner.promote();
  1279. if (newParent == nullptr) {
  1280. ALOGE("Unable to promote Layer handle");
  1281. return false;
  1282. }
  1283. if (attachChildren()) {
  1284. setTransactionFlags(eTransactionNeeded);
  1285. }
  1286. for (const sp<Layer>& child : mCurrentChildren) {
  1287. newParent->addChild(child);
  1288. }
  1289. mCurrentChildren.clear();
  1290. return true;
  1291. }
  1292. void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
  1293. for (const sp<Layer>& child : mDrawingChildren) {
  1294. child->mDrawingParent = newParent;
  1295. child->computeBounds(newParent->mBounds,
  1296. newParent->getTransformWithScale(
  1297. newParent->getBufferScaleTransform()));
  1298. }
  1299. }
  1300. bool Layer::reparent(const sp<IBinder>& newParentHandle) {
  1301. bool callSetTransactionFlags = false;
  1302. // While layers are detached, we allow most operations
  1303. // and simply halt performing the actual transaction. However
  1304. // for reparent != null we would enter the mRemovedFromCurrentState
  1305. // state, regardless of whether doTransaction was called, and
  1306. // so we need to prevent the update here.
  1307. if (mLayerDetached && newParentHandle == nullptr) {
  1308. return false;
  1309. }
  1310. sp<Layer> newParent;
  1311. if (newParentHandle != nullptr) {
  1312. auto handle = static_cast<Handle*>(newParentHandle.get());
  1313. newParent = handle->owner.promote();
  1314. if (newParent == nullptr) {
  1315. ALOGE("Unable to promote Layer handle");
  1316. return false;
  1317. }
  1318. if (newParent == this) {
  1319. ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
  1320. return false;
  1321. }
  1322. }
  1323. sp<Layer> parent = getParent();
  1324. if (parent != nullptr) {
  1325. parent->removeChild(this);
  1326. }
  1327. if (newParentHandle != nullptr) {
  1328. newParent->addChild(this);
  1329. if (!newParent->isRemovedFromCurrentState()) {
  1330. addToCurrentState();
  1331. } else {
  1332. onRemovedFromCurrentState();
  1333. }
  1334. if (mLayerDetached) {
  1335. mLayerDetached = false;
  1336. callSetTransactionFlags = true;
  1337. }
  1338. } else {
  1339. onRemovedFromCurrentState();
  1340. }
  1341. if (callSetTransactionFlags || attachChildren()) {
  1342. setTransactionFlags(eTransactionNeeded);
  1343. }
  1344. return true;
  1345. }
  1346. bool Layer::detachChildren() {
  1347. for (const sp<Layer>& child : mCurrentChildren) {
  1348. sp<Client> parentClient = mClientRef.promote();
  1349. sp<Client> client(child->mClientRef.promote());
  1350. if (client != nullptr && parentClient != client) {
  1351. child->mLayerDetached = true;
  1352. child->detachChildren();
  1353. child->removeRemoteSyncPoints();
  1354. }
  1355. }
  1356. return true;
  1357. }
  1358. bool Layer::attachChildren() {
  1359. bool changed = false;
  1360. for (const sp<Layer>& child : mCurrentChildren) {
  1361. sp<Client> parentClient = mClientRef.promote();
  1362. sp<Client> client(child->mClientRef.promote());
  1363. if (client != nullptr && parentClient != client) {
  1364. if (child->mLayerDetached) {
  1365. child->mLayerDetached = false;
  1366. changed = true;
  1367. }
  1368. changed |= child->attachChildren();
  1369. }
  1370. }
  1371. return changed;
  1372. }
  1373. bool Layer::setColorTransform(const mat4& matrix) {
  1374. static const mat4 identityMatrix = mat4();
  1375. if (mCurrentState.colorTransform == matrix) {
  1376. return false;
  1377. }
  1378. ++mCurrentState.sequence;
  1379. mCurrentState.colorTransform = matrix;
  1380. mCurrentState.hasColorTransform = matrix != identityMatrix;
  1381. mCurrentState.modified = true;
  1382. setTransactionFlags(eTransactionNeeded);
  1383. return true;
  1384. }
  1385. mat4 Layer::getColorTransform() const {
  1386. mat4 colorTransform = mat4(getDrawingState().colorTransform);
  1387. if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
  1388. colorTransform = parent->getColorTransform() * colorTransform;
  1389. }
  1390. return colorTransform;
  1391. }
  1392. bool Layer::hasColorTransform() const {
  1393. bool hasColorTransform = getDrawingState().hasColorTransform;
  1394. if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
  1395. hasColorTransform = hasColorTransform || parent->hasColorTransform();
  1396. }
  1397. return hasColorTransform;
  1398. }
  1399. bool Layer::isLegacyDataSpace() const {
  1400. // return true when no higher bits are set
  1401. return !(mCurrentDataSpace & (ui::Dataspace::STANDARD_MASK |
  1402. ui::Dataspace::TRANSFER_MASK | ui::Dataspace::RANGE_MASK));
  1403. }
  1404. void Layer::setParent(const sp<Layer>& layer) {
  1405. mCurrentParent = layer;
  1406. }
  1407. int32_t Layer::getZ() const {
  1408. return mDrawingState.z;
  1409. }
  1410. bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
  1411. const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
  1412. const State& state = useDrawing ? mDrawingState : mCurrentState;
  1413. return state.zOrderRelativeOf != nullptr;
  1414. }
  1415. __attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
  1416. LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
  1417. LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
  1418. "makeTraversalList received invalid stateSet");
  1419. const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
  1420. const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
  1421. const State& state = useDrawing ? mDrawingState : mCurrentState;
  1422. if (state.zOrderRelatives.size() == 0) {
  1423. *outSkipRelativeZUsers = true;
  1424. return children;
  1425. }
  1426. LayerVector traverse(stateSet);
  1427. for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
  1428. sp<Layer> strongRelative = weakRelative.promote();
  1429. if (strongRelative != nullptr) {
  1430. traverse.add(strongRelative);
  1431. }
  1432. }
  1433. for (const sp<Layer>& child : children) {
  1434. const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
  1435. if (childState.zOrderRelativeOf != nullptr) {
  1436. continue;
  1437. }
  1438. traverse.add(child);
  1439. }
  1440. return traverse;
  1441. }
  1442. /**
  1443. * Negatively signed relatives are before 'this' in Z-order.
  1444. */
  1445. void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
  1446. // In the case we have other layers who are using a relative Z to us, makeTraversalList will
  1447. // produce a new list for traversing, including our relatives, and not including our children
  1448. // who are relatives of another surface. In the case that there are no relative Z,
  1449. // makeTraversalList returns our children directly to avoid significant overhead.
  1450. // However in this case we need to take the responsibility for filtering children which
  1451. // are relatives of another surface here.
  1452. bool skipRelativeZUsers = false;
  1453. const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
  1454. size_t i = 0;
  1455. for (; i < list.size(); i++) {
  1456. const auto& relative = list[i];
  1457. if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
  1458. continue;
  1459. }
  1460. if (relative->getZ() >= 0) {
  1461. break;
  1462. }
  1463. relative->traverseInZOrder(stateSet, visitor);
  1464. }
  1465. visitor(this);
  1466. for (; i < list.size(); i++) {
  1467. const auto& relative = list[i];
  1468. if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
  1469. continue;
  1470. }
  1471. relative->traverseInZOrder(stateSet, visitor);
  1472. }
  1473. }
  1474. /**
  1475. * Positively signed relatives are before 'this' in reverse Z-order.
  1476. */
  1477. void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
  1478. const LayerVector::Visitor& visitor) {
  1479. // See traverseInZOrder for documentation.
  1480. bool skipRelativeZUsers = false;
  1481. LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
  1482. int32_t i = 0;
  1483. for (i = int32_t(list.size()) - 1; i >= 0; i--) {
  1484. const auto& relative = list[i];
  1485. if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
  1486. continue;
  1487. }
  1488. if (relative->getZ() < 0) {
  1489. break;
  1490. }
  1491. relative->traverseInReverseZOrder(stateSet, visitor);
  1492. }
  1493. visitor(this);
  1494. for (; i >= 0; i--) {
  1495. const auto& relative = list[i];
  1496. if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
  1497. continue;
  1498. }
  1499. relative->traverseInReverseZOrder(stateSet, visitor);
  1500. }
  1501. }
  1502. LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
  1503. const std::vector<Layer*>& layersInTree) {
  1504. LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
  1505. "makeTraversalList received invalid stateSet");
  1506. const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
  1507. const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
  1508. const State& state = useDrawing ? mDrawingState : mCurrentState;
  1509. LayerVector traverse(stateSet);
  1510. for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
  1511. sp<Layer> strongRelative = weakRelative.promote();
  1512. // Only add relative layers that are also descendents of the top most parent of the tree.
  1513. // If a relative layer is not a descendent, then it should be ignored.
  1514. if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
  1515. traverse.add(strongRelative);
  1516. }
  1517. }
  1518. for (const sp<Layer>& child : children) {
  1519. const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
  1520. // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
  1521. // descendent of the top most parent of the tree. If it's not a descendent, then just add
  1522. // the child here since it won't be added later as a relative.
  1523. if (std::binary_search(layersInTree.begin(), layersInTree.end(),
  1524. childState.zOrderRelativeOf.promote().get())) {
  1525. continue;
  1526. }
  1527. traverse.add(child);
  1528. }
  1529. return traverse;
  1530. }
  1531. void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
  1532. LayerVector::StateSet stateSet,
  1533. const LayerVector::Visitor& visitor) {
  1534. const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
  1535. size_t i = 0;
  1536. for (; i < list.size(); i++) {
  1537. const auto& relative = list[i];
  1538. if (relative->getZ() >= 0) {
  1539. break;
  1540. }
  1541. relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
  1542. }
  1543. visitor(this);
  1544. for (; i < list.size(); i++) {
  1545. const auto& relative = list[i];
  1546. relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
  1547. }
  1548. }
  1549. std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
  1550. const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
  1551. const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
  1552. std::vector<Layer*> layersInTree = {this};
  1553. for (size_t i = 0; i < children.size(); i++) {
  1554. const auto& child = children[i];
  1555. std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
  1556. layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
  1557. }
  1558. return layersInTree;
  1559. }
  1560. void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
  1561. const LayerVector::Visitor& visitor) {
  1562. std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
  1563. std::sort(layersInTree.begin(), layersInTree.end());
  1564. traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
  1565. }
  1566. ui::Transform Layer::getTransform() const {
  1567. return mEffectiveTransform;
  1568. }
  1569. half Layer::getAlpha() const {
  1570. const auto& p = mDrawingParent.promote();
  1571. half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
  1572. return parentAlpha * getDrawingState().color.a;
  1573. }
  1574. half4 Layer::getColor() const {
  1575. const half4 color(getDrawingState().color);
  1576. return half4(color.r, color.g, color.b, getAlpha());
  1577. }
  1578. Layer::RoundedCornerState Layer::getRoundedCornerState() const {
  1579. const auto& p = mDrawingParent.promote();
  1580. if (p != nullptr) {
  1581. RoundedCornerState parentState = p->getRoundedCornerState();
  1582. if (parentState.radius > 0) {
  1583. ui::Transform t = getActiveTransform(getDrawingState());
  1584. t = t.inverse();
  1585. parentState.cropRect = t.transform(parentState.cropRect);
  1586. // The rounded corners shader only accepts 1 corner radius for performance reasons,
  1587. // but a transform matrix can define horizontal and vertical scales.
  1588. // Let's take the average between both of them and pass into the shader, practically we
  1589. // never do this type of transformation on windows anyway.
  1590. parentState.radius *= (t[0][0] + t[1][1]) / 2.0f;
  1591. return parentState;
  1592. }
  1593. }
  1594. const float radius = getDrawingState().cornerRadius;
  1595. return radius > 0 && getCrop(getDrawingState()).isValid()
  1596. ? RoundedCornerState(getCrop(getDrawingState()).toFloatRect(), radius)
  1597. : RoundedCornerState();
  1598. }
  1599. void Layer::commitChildList() {
  1600. for (size_t i = 0; i < mCurrentChildren.size(); i++) {
  1601. const auto& child = mCurrentChildren[i];
  1602. child->commitChildList();
  1603. }
  1604. mDrawingChildren = mCurrentChildren;
  1605. mDrawingParent = mCurrentParent;
  1606. }
  1607. static wp<Layer> extractLayerFromBinder(const wp<IBinder>& weakBinderHandle) {
  1608. if (weakBinderHandle == nullptr) {
  1609. return nullptr;
  1610. }
  1611. sp<IBinder> binderHandle = weakBinderHandle.promote();
  1612. if (binderHandle == nullptr) {
  1613. return nullptr;
  1614. }
  1615. sp<Layer::Handle> handle = static_cast<Layer::Handle*>(binderHandle.get());
  1616. if (handle == nullptr) {
  1617. return nullptr;
  1618. }
  1619. return handle->owner;
  1620. }
  1621. void Layer::setInputInfo(const InputWindowInfo& info) {
  1622. mCurrentState.inputInfo = info;
  1623. mCurrentState.touchableRegionCrop = extractLayerFromBinder(info.touchableRegionCropHandle);
  1624. mCurrentState.modified = true;
  1625. mCurrentState.inputInfoChanged = true;
  1626. setTransactionFlags(eTransactionNeeded);
  1627. }
  1628. void Layer::writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet,
  1629. uint32_t traceFlags) {
  1630. const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
  1631. const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
  1632. const State& state = useDrawing ? mDrawingState : mCurrentState;
  1633. ui::Transform requestedTransform = state.active_legacy.transform;
  1634. ui::Transform transform = getTransform();
  1635. if (traceFlags & SurfaceTracing::TRACE_CRITICAL) {
  1636. layerInfo->set_id(sequence);
  1637. layerInfo->set_name(getName().c_str());
  1638. layerInfo->set_type(String8(getTypeId()));
  1639. for (const auto& child : children) {
  1640. layerInfo->add_children(child->sequence);
  1641. }
  1642. for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
  1643. sp<Layer> strongRelative = weakRelative.promote();
  1644. if (strongRelative != nullptr) {
  1645. layerInfo->add_relatives(strongRelative->sequence);
  1646. }
  1647. }
  1648. LayerProtoHelper::writeToProto(state.activeTransparentRegion_legacy,
  1649. [&]() { return layerInfo->mutable_transparent_region(); });
  1650. LayerProtoHelper::writeToProto(visibleRegion,
  1651. [&]() { return layerInfo->mutable_visible_region(); });
  1652. LayerProtoHelper::writeToProto(surfaceDamageRegion,
  1653. [&]() { return layerInfo->mutable_damage_region(); });
  1654. layerInfo->set_layer_stack(getLayerStack());
  1655. layerInfo->set_z(state.z);
  1656. LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
  1657. [&]() { return layerInfo->mutable_position(); });
  1658. LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(),
  1659. [&]() {
  1660. return layerInfo->mutable_requested_position();
  1661. });
  1662. LayerProtoHelper::writeSizeToProto(state.active_legacy.w, state.active_legacy.h,
  1663. [&]() { return layerInfo->mutable_size(); });
  1664. LayerProtoHelper::writeToProto(state.crop_legacy,
  1665. [&]() { return layerInfo->mutable_crop(); });
  1666. layerInfo->set_corner_radius(getRoundedCornerState().radius);
  1667. layerInfo->set_is_opaque(isOpaque(state));
  1668. layerInfo->set_invalidate(contentDirty);
  1669. layerInfo->set_is_protected(isProtected());
  1670. // XXX (b/79210409) mCurrentDataSpace is not protected
  1671. layerInfo->set_dataspace(
  1672. dataspaceDetails(static_cast<android_dataspace>(mCurrentDataSpace)));
  1673. layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
  1674. LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
  1675. LayerProtoHelper::writeToProto(state.color,
  1676. [&]() { return layerInfo->mutable_requested_color(); });
  1677. layerInfo->set_flags(state.flags);
  1678. LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
  1679. LayerProtoHelper::writeToProto(requestedTransform,
  1680. layerInfo->mutable_requested_transform());
  1681. auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
  1682. if (parent != nullptr) {
  1683. layerInfo->set_parent(parent->sequence);
  1684. } else {
  1685. layerInfo->set_parent(-1);
  1686. }
  1687. auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
  1688. if (zOrderRelativeOf != nullptr) {
  1689. layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
  1690. } else {
  1691. layerInfo->set_z_order_relative_of(-1);
  1692. }
  1693. auto buffer = mActiveBuffer;
  1694. if (buffer != nullptr) {
  1695. LayerProtoHelper::writeToProto(buffer,
  1696. [&]() { return layerInfo->mutable_active_buffer(); });
  1697. LayerProtoHelper::writeToProto(ui::Transform(mCurrentTransform),
  1698. layerInfo->mutable_buffer_transform());
  1699. }
  1700. layerInfo->set_queued_frames(getQueuedFrameCount());
  1701. layerInfo->set_refresh_pending(isBufferLatched());
  1702. layerInfo->set_curr_frame(mCurrentFrameNumber);
  1703. layerInfo->set_effective_scaling_mode(getEffectiveScalingMode());
  1704. for (const auto& pendingState : mPendingStates) {
  1705. auto barrierLayer = pendingState.barrierLayer_legacy.promote();
  1706. if (barrierLayer != nullptr) {
  1707. BarrierLayerProto* barrierLayerProto = layerInfo->add_barrier_layer();
  1708. barrierLayerProto->set_id(barrierLayer->sequence);
  1709. barrierLayerProto->set_frame_number(pendingState.frameNumber_legacy);
  1710. }
  1711. }
  1712. LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
  1713. }
  1714. if (traceFlags & SurfaceTracing::TRACE_INPUT) {
  1715. LayerProtoHelper::writeToProto(state.inputInfo, state.touchableRegionCrop,
  1716. [&]() { return layerInfo->mutable_input_window_info(); });
  1717. }
  1718. if (traceFlags & SurfaceTracing::TRACE_EXTRA) {
  1719. auto protoMap = layerInfo->mutable_metadata();
  1720. for (const auto& entry : state.metadata.mMap) {
  1721. (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
  1722. }
  1723. LayerProtoHelper::writeToProto(mEffectiveTransform,
  1724. layerInfo->mutable_effective_transform());
  1725. LayerProtoHelper::writeToProto(mSourceBounds,
  1726. [&]() { return layerInfo->mutable_source_bounds(); });
  1727. LayerProtoHelper::writeToProto(mScreenBounds,
  1728. [&]() { return layerInfo->mutable_screen_bounds(); });
  1729. }
  1730. }
  1731. void Layer::writeToProto(LayerProto* layerInfo, const sp<DisplayDevice>& displayDevice,
  1732. uint32_t traceFlags) {
  1733. auto outputLayer = findOutputLayerForDisplay(displayDevice);
  1734. if (!outputLayer) {
  1735. return;
  1736. }
  1737. writeToProto(layerInfo, LayerVector::StateSet::Drawing, traceFlags);
  1738. const auto& compositionState = outputLayer->getState();
  1739. const Rect& frame = compositionState.displayFrame;
  1740. LayerProtoHelper::writeToProto(frame, [&]() { return layerInfo->mutable_hwc_frame(); });
  1741. const FloatRect& crop = compositionState.sourceCrop;
  1742. LayerProtoHelper::writeToProto(crop, [&]() { return layerInfo->mutable_hwc_crop(); });
  1743. const int32_t transform =
  1744. getCompositionLayer() ? static_cast<int32_t>(compositionState.bufferTransform) : 0;
  1745. layerInfo->set_hwc_transform(transform);
  1746. const int32_t compositionType =
  1747. static_cast<int32_t>(compositionState.hwc ? (*compositionState.hwc).hwcCompositionType
  1748. : Hwc2::IComposerClient::Composition::CLIENT);
  1749. layerInfo->set_hwc_composition_type(compositionType);
  1750. if (std::strcmp(getTypeId(), "BufferLayer") == 0 &&
  1751. static_cast<BufferLayer*>(this)->isProtected()) {
  1752. layerInfo->set_is_protected(true);
  1753. } else {
  1754. layerInfo->set_is_protected(false);
  1755. }
  1756. }
  1757. bool Layer::isRemovedFromCurrentState() const {
  1758. return mRemovedFromCurrentState;
  1759. }
  1760. // Debug helper for b/137560795
  1761. #define INT32_MIGHT_OVERFLOW(n) (((n) >= INT32_MAX / 2) || ((n) <= INT32_MIN / 2))
  1762. #define RECT_BOUNDS_INVALID(rect) \
  1763. (INT32_MIGHT_OVERFLOW((rect).left) || INT32_MIGHT_OVERFLOW((rect).right) || \
  1764. INT32_MIGHT_OVERFLOW((rect).bottom) || INT32_MIGHT_OVERFLOW((rect).top))
  1765. InputWindowInfo Layer::fillInputInfo() {
  1766. InputWindowInfo info = mDrawingState.inputInfo;
  1767. if (info.displayId == ADISPLAY_ID_NONE) {
  1768. info.displayId = getLayerStack();
  1769. }
  1770. ui::Transform t = getTransform();
  1771. const float xScale = t.sx();
  1772. const float yScale = t.sy();
  1773. float xSurfaceInset = info.surfaceInset;
  1774. float ySurfaceInset = info.surfaceInset;
  1775. if (xScale != 1.0f || yScale != 1.0f) {
  1776. info.windowXScale *= 1.0f / xScale;
  1777. info.windowYScale *= 1.0f / yScale;
  1778. info.touchableRegion.scaleSelf(xScale, yScale);
  1779. xSurfaceInset *= xScale;
  1780. ySurfaceInset *= yScale;
  1781. }
  1782. // Transform layer size to screen space and inset it by surface insets.
  1783. // If this is a portal window, set the touchableRegion to the layerBounds.
  1784. Rect layerBounds = info.portalToDisplayId == ADISPLAY_ID_NONE
  1785. ? getBufferSize(getDrawingState())
  1786. : info.touchableRegion.getBounds();
  1787. if (!layerBounds.isValid()) {
  1788. layerBounds = getCroppedBufferSize(getDrawingState());
  1789. }
  1790. layerBounds = t.transform(layerBounds);
  1791. // debug check for b/137560795
  1792. {
  1793. if (RECT_BOUNDS_INVALID(layerBounds)) {
  1794. ALOGE("layer %s bounds are invalid (%" PRIi32 ", %" PRIi32 ", %" PRIi32 ", %" PRIi32
  1795. ")",
  1796. mName.c_str(), layerBounds.left, layerBounds.top, layerBounds.right,
  1797. layerBounds.bottom);
  1798. std::string out;
  1799. getTransform().dump(out, "Transform");
  1800. ALOGE("%s", out.c_str());
  1801. layerBounds.left = layerBounds.top = layerBounds.right = layerBounds.bottom = 0;
  1802. }
  1803. if (INT32_MIGHT_OVERFLOW(xSurfaceInset) || INT32_MIGHT_OVERFLOW(ySurfaceInset)) {
  1804. ALOGE("layer %s surface inset are invalid (%" PRIi32 ", %" PRIi32 ")", mName.c_str(),
  1805. int32_t(xSurfaceInset), int32_t(ySurfaceInset));
  1806. xSurfaceInset = ySurfaceInset = 0;
  1807. }
  1808. }
  1809. layerBounds.inset(xSurfaceInset, ySurfaceInset, xSurfaceInset, ySurfaceInset);
  1810. // Input coordinate should match the layer bounds.
  1811. info.frameLeft = layerBounds.left;
  1812. info.frameTop = layerBounds.top;
  1813. info.frameRight = layerBounds.right;
  1814. info.frameBottom = layerBounds.bottom;
  1815. // Position the touchable region relative to frame screen location and restrict it to frame
  1816. // bounds.
  1817. info.touchableRegion = info.touchableRegion.translate(info.frameLeft, info.frameTop);
  1818. info.visible = canReceiveInput();
  1819. auto cropLayer = mDrawingState.touchableRegionCrop.promote();
  1820. if (info.replaceTouchableRegionWithCrop) {
  1821. if (cropLayer == nullptr) {
  1822. info.touchableRegion = Region(Rect{mScreenBounds});
  1823. } else {
  1824. info.touchableRegion = Region(Rect{cropLayer->mScreenBounds});
  1825. }
  1826. } else if (cropLayer != nullptr) {
  1827. info.touchableRegion = info.touchableRegion.intersect(Rect{cropLayer->mScreenBounds});
  1828. }
  1829. return info;
  1830. }
  1831. bool Layer::hasInput() const {
  1832. return mDrawingState.inputInfo.token != nullptr;
  1833. }
  1834. std::shared_ptr<compositionengine::Layer> Layer::getCompositionLayer() const {
  1835. return nullptr;
  1836. }
  1837. bool Layer::canReceiveInput() const {
  1838. return !isHiddenByPolicy();
  1839. }
  1840. compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
  1841. const sp<const DisplayDevice>& display) const {
  1842. return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionLayer().get());
  1843. }
  1844. // ---------------------------------------------------------------------------
  1845. }; // namespace android
  1846. #if defined(__gl_h_)
  1847. #error "don't include gl/gl.h in this file"
  1848. #endif
  1849. #if defined(__gl2_h_)
  1850. #error "don't include gl2/gl2.h in this file"
  1851. #endif