CanvasContext.cpp revision afbd0f1fef46ef0ddf633dfde0de724db3da1405
1/*
2 * Copyright (C) 2014 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 <GpuMemoryTracker.h>
18#include "CanvasContext.h"
19
20#include "AnimationContext.h"
21#include "Caches.h"
22#include "Canvas.h"
23#include "DeferredLayerUpdater.h"
24#include "EglManager.h"
25#include "LayerUpdateQueue.h"
26#include "LayerRenderer.h"
27#include "OpenGLRenderer.h"
28#include "Properties.h"
29#include "RenderThread.h"
30#include "renderstate/RenderState.h"
31#include "renderstate/Stencil.h"
32#include "protos/hwui.pb.h"
33#include "utils/GLUtils.h"
34#include "utils/TimeUtils.h"
35
36#include <cutils/properties.h>
37#include <google/protobuf/io/zero_copy_stream_impl.h>
38#include <private/hwui/DrawGlInfo.h>
39#include <strings.h>
40
41#include <algorithm>
42#include <fcntl.h>
43#include <sys/stat.h>
44
45#include <cstdlib>
46
47#define TRIM_MEMORY_COMPLETE 80
48#define TRIM_MEMORY_UI_HIDDEN 20
49
50#define ENABLE_RENDERNODE_SERIALIZATION false
51
52#define LOG_FRAMETIME_MMA 0
53
54#if LOG_FRAMETIME_MMA
55static float sBenchMma = 0;
56static int sFrameCount = 0;
57static const float NANOS_PER_MILLIS_F = 1000000.0f;
58#endif
59
60namespace android {
61namespace uirenderer {
62namespace renderthread {
63
64CanvasContext::CanvasContext(RenderThread& thread, bool translucent,
65        RenderNode* rootRenderNode, IContextFactory* contextFactory)
66        : mRenderThread(thread)
67        , mEglManager(thread.eglManager())
68        , mOpaque(!translucent)
69        , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord()))
70        , mJankTracker(thread.timeLord().frameIntervalNanos())
71        , mProfiler(mFrames)
72        , mContentDrawBounds(0, 0, 0, 0) {
73    mRenderNodes.emplace_back(rootRenderNode);
74    mRenderThread.renderState().registerCanvasContext(this);
75    mProfiler.setDensity(mRenderThread.mainDisplayInfo().density);
76}
77
78CanvasContext::~CanvasContext() {
79    destroy();
80    mRenderThread.renderState().unregisterCanvasContext(this);
81}
82
83void CanvasContext::destroy() {
84    stopDrawing();
85    setSurface(nullptr);
86    freePrefetechedLayers();
87    destroyHardwareResources();
88    mAnimationContext->destroy();
89    if (mCanvas) {
90        delete mCanvas;
91        mCanvas = nullptr;
92    }
93}
94
95void CanvasContext::setSurface(Surface* surface) {
96    ATRACE_CALL();
97
98    mNativeSurface = surface;
99
100    if (mEglSurface != EGL_NO_SURFACE) {
101        mEglManager.destroySurface(mEglSurface);
102        mEglSurface = EGL_NO_SURFACE;
103    }
104
105    if (surface) {
106        mEglSurface = mEglManager.createSurface(surface);
107    }
108
109    if (mEglSurface != EGL_NO_SURFACE) {
110        const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer);
111        mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
112        mHaveNewSurface = true;
113        mSwapHistory.clear();
114        makeCurrent();
115    } else {
116        mRenderThread.removeFrameCallback(this);
117    }
118}
119
120void CanvasContext::requireSurface() {
121    LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
122            "requireSurface() called but no surface set!");
123    makeCurrent();
124}
125
126void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
127    mSwapBehavior = swapBehavior;
128}
129
130void CanvasContext::initialize(Surface* surface) {
131    setSurface(surface);
132#if !HWUI_NEW_OPS
133    if (mCanvas) return;
134    mCanvas = new OpenGLRenderer(mRenderThread.renderState());
135    mCanvas->initProperties();
136#endif
137}
138
139void CanvasContext::updateSurface(Surface* surface) {
140    setSurface(surface);
141}
142
143bool CanvasContext::pauseSurface(Surface* surface) {
144    return mRenderThread.removeFrameCallback(this);
145}
146
147// TODO: don't pass viewport size, it's automatic via EGL
148void CanvasContext::setup(int width, int height, float lightRadius,
149        uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
150#if HWUI_NEW_OPS
151    mLightGeometry.radius = lightRadius;
152    mLightInfo.ambientShadowAlpha = ambientShadowAlpha;
153    mLightInfo.spotShadowAlpha = spotShadowAlpha;
154#else
155    if (!mCanvas) return;
156    mCanvas->initLight(lightRadius, ambientShadowAlpha, spotShadowAlpha);
157#endif
158}
159
160void CanvasContext::setLightCenter(const Vector3& lightCenter) {
161#if HWUI_NEW_OPS
162    mLightGeometry.center = lightCenter;
163#else
164    if (!mCanvas) return;
165    mCanvas->setLightCenter(lightCenter);
166#endif
167}
168
169void CanvasContext::setOpaque(bool opaque) {
170    mOpaque = opaque;
171}
172
173void CanvasContext::makeCurrent() {
174    // TODO: Figure out why this workaround is needed, see b/13913604
175    // In the meantime this matches the behavior of GLRenderer, so it is not a regression
176    EGLint error = 0;
177    mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface, &error);
178    if (error) {
179        setSurface(nullptr);
180    }
181}
182
183static bool wasSkipped(FrameInfo* info) {
184    return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame);
185}
186
187void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo,
188        int64_t syncQueued, RenderNode* target) {
189    mRenderThread.removeFrameCallback(this);
190
191    // If the previous frame was dropped we don't need to hold onto it, so
192    // just keep using the previous frame's structure instead
193    if (!wasSkipped(mCurrentFrameInfo)) {
194        mCurrentFrameInfo = &mFrames.next();
195    }
196    mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo);
197    mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued;
198    mCurrentFrameInfo->markSyncStart();
199
200    info.damageAccumulator = &mDamageAccumulator;
201#if HWUI_NEW_OPS
202    info.layerUpdateQueue = &mLayerUpdateQueue;
203#else
204    info.renderer = mCanvas;
205#endif
206
207    if (CC_LIKELY(mNativeSurface.get())) {
208        info.frameNumber = static_cast<int64_t>(mNativeSurface->getNextFrameNumber());
209    }
210
211    mAnimationContext->startFrame(info.mode);
212    for (const sp<RenderNode>& node : mRenderNodes) {
213        // Only the primary target node will be drawn full - all other nodes would get drawn in
214        // real time mode. In case of a window, the primary node is the window content and the other
215        // node(s) are non client / filler nodes.
216        info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY);
217        node->prepareTree(info);
218        GL_CHECKPOINT(MODERATE);
219    }
220    mAnimationContext->runRemainingAnimations(info);
221    GL_CHECKPOINT(MODERATE);
222
223    freePrefetechedLayers();
224    GL_CHECKPOINT(MODERATE);
225
226    if (CC_UNLIKELY(!mNativeSurface.get())) {
227        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
228        info.out.canDrawThisFrame = false;
229        return;
230    }
231
232    if (CC_LIKELY(mSwapHistory.size())) {
233        nsecs_t latestVsync = mRenderThread.timeLord().latestVsync();
234        const SwapHistory& lastSwap = mSwapHistory.back();
235        nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync);
236        // The slight fudge-factor is to deal with cases where
237        // the vsync was estimated due to being slow handling the signal.
238        // See the logic in TimeLord#computeFrameTimeNanos or in
239        // Choreographer.java for details on when this happens
240        if (vsyncDelta < 2_ms) {
241            // Already drew for this vsync pulse, UI draw request missed
242            // the deadline for RT animations
243            info.out.canDrawThisFrame = false;
244        } else if (lastSwap.swapTime < latestVsync) {
245            info.out.canDrawThisFrame = true;
246        } else {
247            // We're maybe behind? Find out for sure
248            int runningBehind = 0;
249            // TODO: Have this method be on Surface, too, not just ANativeWindow...
250            ANativeWindow* window = mNativeSurface.get();
251            window->query(window, NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind);
252            info.out.canDrawThisFrame = !runningBehind;
253        }
254    } else {
255        info.out.canDrawThisFrame = true;
256    }
257
258    if (!info.out.canDrawThisFrame) {
259        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
260    }
261
262    if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
263        if (!info.out.requiresUiRedraw) {
264            // If animationsNeedsRedraw is set don't bother posting for an RT anim
265            // as we will just end up fighting the UI thread.
266            mRenderThread.postFrameCallback(this);
267        }
268    }
269}
270
271void CanvasContext::stopDrawing() {
272    mRenderThread.removeFrameCallback(this);
273}
274
275void CanvasContext::notifyFramePending() {
276    ATRACE_CALL();
277    mRenderThread.pushBackFrameCallback(this);
278}
279
280void CanvasContext::draw() {
281#if !HWUI_NEW_OPS
282    LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE,
283            "drawRenderNode called on a context with no canvas or surface!");
284#endif
285
286    SkRect dirty;
287    mDamageAccumulator.finish(&dirty);
288
289    // TODO: Re-enable after figuring out cause of b/22592975
290//    if (dirty.isEmpty() && Properties::skipEmptyFrames) {
291//        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
292//        return;
293//    }
294
295    mCurrentFrameInfo->markIssueDrawCommandsStart();
296
297    Frame frame = mEglManager.beginFrame(mEglSurface);
298
299    if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) {
300        // can't rely on prior content of window if viewport size changes
301        dirty.setEmpty();
302        mLastFrameWidth = frame.width();
303        mLastFrameHeight = frame.height();
304    } else if (mHaveNewSurface || frame.bufferAge() == 0) {
305        // New surface needs a full draw
306        dirty.setEmpty();
307    } else {
308        if (!dirty.isEmpty() && !dirty.intersect(0, 0, frame.width(), frame.height())) {
309            ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?",
310                    SK_RECT_ARGS(dirty), frame.width(), frame.height());
311            dirty.setEmpty();
312        }
313        profiler().unionDirty(&dirty);
314    }
315
316    if (dirty.isEmpty()) {
317        dirty.set(0, 0, frame.width(), frame.height());
318    }
319
320    // At this point dirty is the area of the screen to update. However,
321    // the area of the frame we need to repaint is potentially different, so
322    // stash the screen area for later
323    SkRect screenDirty(dirty);
324
325    // If the buffer age is 0 we do a full-screen repaint (handled above)
326    // If the buffer age is 1 the buffer contents are the same as they were
327    // last frame so there's nothing to union() against
328    // Therefore we only care about the > 1 case.
329    if (frame.bufferAge() > 1) {
330        if (frame.bufferAge() > (int) mSwapHistory.size()) {
331            // We don't have enough history to handle this old of a buffer
332            // Just do a full-draw
333            dirty.set(0, 0, frame.width(), frame.height());
334        } else {
335            // At this point we haven't yet added the latest frame
336            // to the damage history (happens below)
337            // So we need to damage
338            for (int i = mSwapHistory.size() - 1;
339                    i > ((int) mSwapHistory.size()) - frame.bufferAge(); i--) {
340                dirty.join(mSwapHistory[i].damage);
341            }
342        }
343    }
344
345    mEglManager.damageFrame(frame, dirty);
346
347#if HWUI_NEW_OPS
348    FrameBuilder frameBuilder(mLayerUpdateQueue, dirty, frame.width(), frame.height(),
349            mRenderNodes, mLightGeometry, mContentDrawBounds, &Caches::getInstance());
350    mLayerUpdateQueue.clear();
351    auto&& caches = Caches::getInstance();
352    BakedOpRenderer renderer(caches, mRenderThread.renderState(),
353            mOpaque, mLightInfo);
354    frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer);
355    profiler().draw(&renderer);
356    bool drew = renderer.didDraw();
357
358    // post frame cleanup
359    caches.clearGarbage();
360    caches.pathCache.trim();
361    caches.tessellationCache.trim();
362
363#if DEBUG_MEMORY_USAGE
364    mCaches.dumpMemoryUsage();
365#else
366    if (CC_UNLIKELY(Properties::debugLevel & kDebugMemory)) {
367        caches.dumpMemoryUsage();
368    }
369#endif
370
371#else
372    mCanvas->prepareDirty(frame.width(), frame.height(),
373            dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom, mOpaque);
374
375    Rect outBounds;
376    // It there are multiple render nodes, they are laid out as follows:
377    // #0 - backdrop (content + caption)
378    // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds)
379    // #2 - additional overlay nodes
380    // Usually the backdrop cannot be seen since it will be entirely covered by the content. While
381    // resizing however it might become partially visible. The following render loop will crop the
382    // backdrop against the content and draw the remaining part of it. It will then draw the content
383    // cropped to the backdrop (since that indicates a shrinking of the window).
384    //
385    // Additional nodes will be drawn on top with no particular clipping semantics.
386
387    // The bounds of the backdrop against which the content should be clipped.
388    Rect backdropBounds = mContentDrawBounds;
389    // Usually the contents bounds should be mContentDrawBounds - however - we will
390    // move it towards the fixed edge to give it a more stable appearance (for the moment).
391    Rect contentBounds;
392    // If there is no content bounds we ignore the layering as stated above and start with 2.
393    int layer = (mContentDrawBounds.isEmpty() || mRenderNodes.size() == 1) ? 2 : 0;
394    // Draw all render nodes. Note that
395    for (const sp<RenderNode>& node : mRenderNodes) {
396        if (layer == 0) { // Backdrop.
397            // Draw the backdrop clipped to the inverse content bounds, but assume that the content
398            // was moved to the upper left corner.
399            const RenderProperties& properties = node->properties();
400            Rect targetBounds(properties.getLeft(), properties.getTop(),
401                              properties.getRight(), properties.getBottom());
402            // Move the content bounds towards the fixed corner of the backdrop.
403            const int x = targetBounds.left;
404            const int y = targetBounds.top;
405            contentBounds.set(x, y, x + mContentDrawBounds.getWidth(),
406                                    y + mContentDrawBounds.getHeight());
407            // Remember the intersection of the target bounds and the intersection bounds against
408            // which we have to crop the content.
409            backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight());
410            backdropBounds.doIntersect(targetBounds);
411            // Check if we have to draw something on the left side ...
412            if (targetBounds.left < contentBounds.left) {
413                mCanvas->save(SaveFlags::Clip);
414                if (mCanvas->clipRect(targetBounds.left, targetBounds.top,
415                                      contentBounds.left, targetBounds.bottom,
416                                      SkRegion::kIntersect_Op)) {
417                    mCanvas->drawRenderNode(node.get(), outBounds);
418                }
419                // Reduce the target area by the area we have just painted.
420                targetBounds.left = std::min(contentBounds.left, targetBounds.right);
421                mCanvas->restore();
422            }
423            // ... or on the right side ...
424            if (targetBounds.right > contentBounds.right &&
425                !targetBounds.isEmpty()) {
426                mCanvas->save(SaveFlags::Clip);
427                if (mCanvas->clipRect(contentBounds.right, targetBounds.top,
428                                      targetBounds.right, targetBounds.bottom,
429                                      SkRegion::kIntersect_Op)) {
430                    mCanvas->drawRenderNode(node.get(), outBounds);
431                }
432                // Reduce the target area by the area we have just painted.
433                targetBounds.right = std::max(targetBounds.left, contentBounds.right);
434                mCanvas->restore();
435            }
436            // ... or at the top ...
437            if (targetBounds.top < contentBounds.top &&
438                !targetBounds.isEmpty()) {
439                mCanvas->save(SaveFlags::Clip);
440                if (mCanvas->clipRect(targetBounds.left, targetBounds.top, targetBounds.right,
441                                      contentBounds.top,
442                                      SkRegion::kIntersect_Op)) {
443                    mCanvas->drawRenderNode(node.get(), outBounds);
444                }
445                // Reduce the target area by the area we have just painted.
446                targetBounds.top = std::min(contentBounds.top, targetBounds.bottom);
447                mCanvas->restore();
448            }
449            // ... or at the bottom.
450            if (targetBounds.bottom > contentBounds.bottom &&
451                !targetBounds.isEmpty()) {
452                mCanvas->save(SaveFlags::Clip);
453                if (mCanvas->clipRect(targetBounds.left, contentBounds.bottom, targetBounds.right,
454                                      targetBounds.bottom, SkRegion::kIntersect_Op)) {
455                    mCanvas->drawRenderNode(node.get(), outBounds);
456                }
457                mCanvas->restore();
458            }
459        } else if (layer == 1) { // Content
460            // It gets cropped against the bounds of the backdrop to stay inside.
461            mCanvas->save(SaveFlags::MatrixClip);
462
463            // We shift and clip the content to match its final location in the window.
464            const float left = mContentDrawBounds.left;
465            const float top = mContentDrawBounds.top;
466            const float dx = backdropBounds.left - left;
467            const float dy = backdropBounds.top - top;
468            const float width = backdropBounds.getWidth();
469            const float height = backdropBounds.getHeight();
470
471            mCanvas->translate(dx, dy);
472            if (mCanvas->clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op)) {
473                mCanvas->drawRenderNode(node.get(), outBounds);
474            }
475            mCanvas->restore();
476        } else { // draw the rest on top at will!
477            mCanvas->drawRenderNode(node.get(), outBounds);
478        }
479        layer++;
480    }
481
482    profiler().draw(mCanvas);
483
484    bool drew = mCanvas->finish();
485#endif
486
487    GL_CHECKPOINT(LOW);
488
489    // Even if we decided to cancel the frame, from the perspective of jank
490    // metrics the frame was swapped at this point
491    mCurrentFrameInfo->markSwapBuffers();
492
493    if (drew || mEglManager.damageRequiresSwap()) {
494        if (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty))) {
495            setSurface(nullptr);
496        }
497        SwapHistory& swap = mSwapHistory.next();
498        swap.damage = screenDirty;
499        swap.swapTime = systemTime(CLOCK_MONOTONIC);
500        swap.vsyncTime = mRenderThread.timeLord().latestVsync();
501        mHaveNewSurface = false;
502    }
503
504    // TODO: Use a fence for real completion?
505    mCurrentFrameInfo->markFrameCompleted();
506
507#if LOG_FRAMETIME_MMA
508    float thisFrame = mCurrentFrameInfo->duration(
509            FrameInfoIndex::IssueDrawCommandsStart,
510            FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F;
511    if (sFrameCount) {
512        sBenchMma = ((9 * sBenchMma) + thisFrame) / 10;
513    } else {
514        sBenchMma = thisFrame;
515    }
516    if (++sFrameCount == 10) {
517        sFrameCount = 1;
518        ALOGD("Average frame time: %.4f", sBenchMma);
519    }
520#endif
521
522    mJankTracker.addFrame(*mCurrentFrameInfo);
523    mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo);
524    if (CC_UNLIKELY(mFrameMetricsReporter.get() != nullptr)) {
525        mFrameMetricsReporter->reportFrameMetrics(mCurrentFrameInfo->data());
526    }
527
528    GpuMemoryTracker::onFrameCompleted();
529}
530
531// Called by choreographer to do an RT-driven animation
532void CanvasContext::doFrame() {
533#if HWUI_NEW_OPS
534    if (CC_UNLIKELY(mEglSurface == EGL_NO_SURFACE)) return;
535#else
536    if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) return;
537#endif
538    prepareAndDraw(nullptr);
539}
540
541void CanvasContext::prepareAndDraw(RenderNode* node) {
542    ATRACE_CALL();
543
544    nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos();
545    int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE];
546    UiFrameInfoBuilder(frameInfo)
547        .addFlag(FrameInfoFlags::RTAnimation)
548        .setVsync(vsync, vsync);
549
550    TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
551    prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node);
552    if (info.out.canDrawThisFrame) {
553        draw();
554    }
555}
556
557void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
558    ATRACE_CALL();
559    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
560    if (thread.eglManager().hasEglContext()) {
561        mode = DrawGlInfo::kModeProcess;
562    }
563
564    thread.renderState().invokeFunctor(functor, mode, nullptr);
565}
566
567void CanvasContext::markLayerInUse(RenderNode* node) {
568    if (mPrefetechedLayers.erase(node)) {
569        node->decStrong(nullptr);
570    }
571}
572
573static void destroyPrefetechedNode(RenderNode* node) {
574    ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName());
575    node->destroyHardwareResources();
576    node->decStrong(nullptr);
577}
578
579void CanvasContext::freePrefetechedLayers() {
580    if (mPrefetechedLayers.size()) {
581        std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode);
582        mPrefetechedLayers.clear();
583    }
584}
585
586void CanvasContext::buildLayer(RenderNode* node) {
587    ATRACE_CALL();
588    if (!mEglManager.hasEglContext() || !mCanvas) {
589        return;
590    }
591    // buildLayer() will leave the tree in an unknown state, so we must stop drawing
592    stopDrawing();
593
594    TreeInfo info(TreeInfo::MODE_FULL, *this);
595    info.damageAccumulator = &mDamageAccumulator;
596#if HWUI_NEW_OPS
597    info.layerUpdateQueue = &mLayerUpdateQueue;
598#else
599    info.renderer = mCanvas;
600#endif
601    info.runAnimations = false;
602    node->prepareTree(info);
603    SkRect ignore;
604    mDamageAccumulator.finish(&ignore);
605    // Tickle the GENERIC property on node to mark it as dirty for damaging
606    // purposes when the frame is actually drawn
607    node->setPropertyFieldsDirty(RenderNode::GENERIC);
608
609#if HWUI_NEW_OPS
610    // TODO: support buildLayer
611#else
612    mCanvas->markLayersAsBuildLayers();
613    mCanvas->flushLayerUpdates();
614#endif
615
616    node->incStrong(nullptr);
617    mPrefetechedLayers.insert(node);
618}
619
620bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
621    layer->apply();
622    return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap);
623}
624
625void CanvasContext::destroyHardwareResources() {
626    stopDrawing();
627    if (mEglManager.hasEglContext()) {
628        freePrefetechedLayers();
629        for (const sp<RenderNode>& node : mRenderNodes) {
630            node->destroyHardwareResources();
631        }
632        Caches& caches = Caches::getInstance();
633        // Make sure to release all the textures we were owning as there won't
634        // be another draw
635        caches.textureCache.resetMarkInUse(this);
636        mRenderThread.renderState().flush(Caches::FlushMode::Layers);
637    }
638}
639
640void CanvasContext::trimMemory(RenderThread& thread, int level) {
641    // No context means nothing to free
642    if (!thread.eglManager().hasEglContext()) return;
643
644    ATRACE_CALL();
645    if (level >= TRIM_MEMORY_COMPLETE) {
646        thread.renderState().flush(Caches::FlushMode::Full);
647        thread.eglManager().destroy();
648    } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
649        thread.renderState().flush(Caches::FlushMode::Moderate);
650    }
651}
652
653void CanvasContext::runWithGlContext(RenderTask* task) {
654    LOG_ALWAYS_FATAL_IF(!mEglManager.hasEglContext(),
655            "GL context not initialized!");
656    task->run();
657}
658
659Layer* CanvasContext::createTextureLayer() {
660    requireSurface();
661    return LayerRenderer::createTextureLayer(mRenderThread.renderState());
662}
663
664void CanvasContext::setTextureAtlas(RenderThread& thread,
665        const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
666    thread.eglManager().setTextureAtlas(buffer, map, mapSize);
667}
668
669void CanvasContext::dumpFrames(int fd) {
670    FILE* file = fdopen(fd, "a");
671    fprintf(file, "\n\n---PROFILEDATA---\n");
672    for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) {
673        fprintf(file, "%s", FrameInfoNames[i].c_str());
674        fprintf(file, ",");
675    }
676    for (size_t i = 0; i < mFrames.size(); i++) {
677        FrameInfo& frame = mFrames[i];
678        if (frame[FrameInfoIndex::SyncStart] == 0) {
679            continue;
680        }
681        fprintf(file, "\n");
682        for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) {
683            fprintf(file, "%" PRId64 ",", frame[i]);
684        }
685    }
686    fprintf(file, "\n---PROFILEDATA---\n\n");
687    fflush(file);
688}
689
690void CanvasContext::resetFrameStats() {
691    mFrames.clear();
692    mRenderThread.jankTracker().reset();
693}
694
695void CanvasContext::serializeDisplayListTree() {
696#if ENABLE_RENDERNODE_SERIALIZATION
697    using namespace google::protobuf::io;
698    char package[128];
699    // Check whether tracing is enabled for this process.
700    FILE * file = fopen("/proc/self/cmdline", "r");
701    if (file) {
702        if (!fgets(package, 128, file)) {
703            ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno);
704            fclose(file);
705            return;
706        }
707        fclose(file);
708    } else {
709        ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno),
710                errno);
711        return;
712    }
713    char path[1024];
714    snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package);
715    int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH);
716    if (fd == -1) {
717        ALOGD("Failed to open '%s'", path);
718        return;
719    }
720    proto::RenderNode tree;
721    // TODO: Streaming writes?
722    mRootRenderNode->copyTo(&tree);
723    std::string data = tree.SerializeAsString();
724    write(fd, data.c_str(), data.length());
725    close(fd);
726#endif
727}
728
729} /* namespace renderthread */
730} /* namespace uirenderer */
731} /* namespace android */
732