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