summaryrefslogtreecommitdiff
path: root/libs/hwui/canvas/CanvasFrontend.h
blob: 9f22b900e4ab1cc185ded5823a0e642f100d1386 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

// TODO: Can we get the dependencies scoped down more?
#include "CanvasOps.h"
#include "CanvasOpBuffer.h"
#include <SaveFlags.h>

#include <ui/FatVector.h>

#include <optional>

namespace android::uirenderer {

// Exists to avoid forcing all this common logic into the templated class
class CanvasStateHelper {
protected:
    CanvasStateHelper(int width, int height);
    ~CanvasStateHelper() = default;

    struct SaveEntry {
        bool clip : 1 = false;
        bool matrix : 1 = false;
        bool layer : 1 = false;
    };

    template <typename T>
    struct DeferredEntry {
        T entry;
        int deferredSaveCount = 0;

        DeferredEntry() = default;
        DeferredEntry(const T& t) : entry(t) {}
    };

    struct ConservativeClip {
        SkIRect bounds = SkIRect::MakeEmpty();
        bool rect = true;
        bool aa = false;

        bool quickReject(const SkMatrix& matrix, const SkRect& bounds) const;

        void apply(SkClipOp op, const SkMatrix& matrix, const SkRect& bounds, bool aa,
                   bool fillsBounds);
    };

    constexpr SaveEntry saveEntryForLayer() {
        return {
            .clip = true,
            .matrix = true,
            .layer = true,
        };
    }

    constexpr SaveEntry flagsToSaveEntry(SaveFlags::Flags flags) {
        return SaveEntry {
            .clip = static_cast<bool>(flags & SaveFlags::Clip),
            .matrix = static_cast<bool>(flags & SaveFlags::Matrix),
            .layer = false
        };
    }

    bool internalSave(SaveEntry saveEntry);

    void internalSaveLayer(const SkCanvas::SaveLayerRec& layerRec) {
        internalSave({
            .clip = true,
            .matrix = true,
            .layer = true
        });
        internalClipRect(*layerRec.fBounds, SkClipOp::kIntersect);
    }

    bool internalRestore();

    void internalClipRect(const SkRect& rect, SkClipOp op);
    void internalClipPath(const SkPath& path, SkClipOp op);

    // The canvas' clip will never expand beyond these bounds since intersect
    // and difference operations only subtract pixels.
    SkIRect mInitialBounds;
    // Every save() gets a SaveEntry to track what needs to be restored.
    FatVector<SaveEntry, 6> mSaveStack;
    // Transform and clip entries record a deferred save count and do not
    // make a new entry until that particular state is modified.
    FatVector<DeferredEntry<SkMatrix>, 6> mTransformStack;
    FatVector<DeferredEntry<ConservativeClip>, 6> mClipStack;

    const ConservativeClip& clip() const { return mClipStack.back().entry; }

    ConservativeClip& clip();

    void resetState(int width, int height);

    // Stack manipulation for transform and clip stacks
    template <typename T, size_t N>
    void pushEntry(FatVector<DeferredEntry<T>, N>* stack) {
        stack->back().deferredSaveCount += 1;
    }

    template <typename T, size_t N>
    void popEntry(FatVector<DeferredEntry<T>, N>* stack) {
        if (!(stack->back().deferredSaveCount--)) {
            stack->pop_back();
        }
    }

    template <typename T, size_t N>
    T& writableEntry(FatVector<DeferredEntry<T>, N>* stack) {
        DeferredEntry<T>& back = stack->back();
        if (back.deferredSaveCount == 0) {
            return back.entry;
        } else {
            back.deferredSaveCount -= 1;
            // saved in case references move when re-allocating vector storage
            T state = back.entry;
            return stack->emplace_back(state).entry;
        }
    }

public:
    int saveCount() const { return mSaveStack.size(); }

    SkRect getClipBounds() const;
    bool quickRejectRect(float left, float top, float right, float bottom) const;
    bool quickRejectPath(const SkPath& path) const;

    bool isClipAA() const { return clip().aa; }
    bool isClipEmpty() const { return clip().bounds.isEmpty(); }
    bool isClipRect() const { return clip().rect; }
    bool isClipComplex() const { return !isClipEmpty() && (isClipAA() || !isClipRect()); }

    const SkMatrix& transform() const { return mTransformStack.back().entry; }

    SkMatrix& transform();

    // For compat with existing HWUI Canvas interface
    void getMatrix(SkMatrix* outMatrix) const {
        *outMatrix = transform();
    }

    void setMatrix(const SkMatrix& matrix) {
        transform() = matrix;
    }

    void concat(const SkMatrix& matrix) {
        transform().preConcat(matrix);
    }

    void rotate(float degrees) {
        SkMatrix m;
        m.setRotate(degrees);
        concat(m);
    }

    void scale(float sx, float sy) {
        SkMatrix m;
        m.setScale(sx, sy);
        concat(m);
    }

    void skew(float sx, float sy) {
        SkMatrix m;
        m.setSkew(sx, sy);
        concat(m);
    }

    void translate(float dx, float dy) {
        transform().preTranslate(dx, dy);
    }
};

// Front-end canvas that handles queries, up-front state, and produces CanvasOp<> output downstream
template <typename CanvasOpReceiver>
class CanvasFrontend final : public CanvasStateHelper {
public:
    template<class... Args>
    CanvasFrontend(int width, int height, Args&&... args) : CanvasStateHelper(width, height),
            mReceiver(std::in_place, std::forward<Args>(args)...) { }

    void save(SaveFlags::Flags flags = SaveFlags::MatrixClip) {
        if (internalSave(flagsToSaveEntry(flags))) {
            submit<CanvasOpType::Save>({});
        }
    }

    void restore() {
        if (internalRestore()) {
            submit<CanvasOpType::Restore>({});
        }
    }

    template <CanvasOpType T>
    void draw(CanvasOp<T>&& op) {
        // The front-end requires going through certain front-doors, which these aren't.
        static_assert(T != CanvasOpType::Save, "Must use CanvasFrontend::save() call instead");
        static_assert(T != CanvasOpType::Restore, "Must use CanvasFrontend::restore() call instead");

        if constexpr (T == CanvasOpType::SaveLayer) {
            internalSaveLayer(op.saveLayerRec);
        }
        if constexpr (T == CanvasOpType::SaveBehind) {
            // Don't use internalSaveLayer as this doesn't apply clipping, it's a "regular" save
            // But we do want to flag it as a layer, such that restore is Definitely Required
            internalSave(saveEntryForLayer());
        }
        if constexpr (T == CanvasOpType::ClipRect) {
            internalClipRect(op.rect, op.op);
        }
        if constexpr (T == CanvasOpType::ClipPath) {
            internalClipPath(op.path, op.op);
        }

        submit(std::move(op));
    }

    const CanvasOpReceiver& receiver() const {
        LOG_ALWAYS_FATAL_IF(!mReceiver.has_value());
        return *mReceiver;
    }

    CanvasOpReceiver finish() {
        auto ret = std::move(mReceiver.value());
        mReceiver.reset();
        return std::move(ret);
    }

    template<class... Args>
    void reset(int newWidth, int newHeight, Args&&... args) {
        resetState(newWidth, newHeight);
        mReceiver.emplace(std::forward<Args>(args)...);
    }

private:
    std::optional<CanvasOpReceiver> mReceiver;

    template <CanvasOpType T>
    void submit(CanvasOp<T>&& op) {
        LOG_ALWAYS_FATAL_IF(!mReceiver.has_value());
        mReceiver->push_container(CanvasOpContainer(std::move(op), transform()));
    }
};

} // namespace android::uirenderer