1 /*
2  * Copyright (c) 2022-2023 Huawei Device Co., Ltd.. All rights reserved.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef CORE_CANVAS_H
17 #define CORE_CANVAS_H
18 
19 #include <memory>
20 
21 #include "common/rs_macros.h"
22 #include "drawing/engine_adapter/impl_interface/core_canvas_impl.h"
23 #include "utils/drawing_macros.h"
24 #include "utils/rect.h"
25 
26 namespace OHOS {
27 namespace Rosen {
28 namespace Drawing {
29 enum class SrcRectConstraint {
30     STRICT_SRC_RECT_CONSTRAINT,
31     FAST_SRC_RECT_CONSTRAINT,
32 };
33 
34 struct HpsBlurParameter {
35     Rect src;
36     Rect dst;
37     scalar sigma { 1E-6 };
38     float saturation { 1.0 };
39     float brightness { 1.0 };
HpsBlurParameterHpsBlurParameter40     HpsBlurParameter(const Rect& s, const Rect& d, const scalar& sgm,
41         float satura, float bright)
42         : src(s), dst(d), sigma(sgm), saturation(satura), brightness(bright) {}
43 };
44 
45 /**
46  * @brief PointMode: Selects if an array of points are drawn as discrete points, as lines, or as
47  * an open polygon.
48  */
49 enum class PointMode {
50     POINTS_POINTMODE,  // draw each point separately
51     LINES_POINTMODE,   // draw each pair of points as a line segment
52     POLYGON_POINTMODE, // draw the array of points as a open polygon
53 };
54 
55 #undef TRANSPARENT
56 struct Lattice {
57     enum RectType : uint8_t {
58         DEFAULT = 0,
59         TRANSPARENT,
60         FIXEDCOLOR,
61     };
62     std::vector<int> fXDivs;
63     std::vector<int> fYDivs;
64     std::vector<RectType> fRectTypes;
65     int fXCount;
66     int fYCount;
67     std::vector<RectI> fBounds;
68     std::vector<Color> fColors;
69 };
70 
71 enum CacheType : uint8_t {
72     UNDEFINED, // do not change current cache status
73     ENABLED,   // explicitly enable cache
74     DISABLED,  // explicitly disable cache
75     OFFSCREEN, // offscreen rendering
76 };
77 
78 class Surface;
79 
80 /**
81  * @brief Contains the option used to create the layer.
82  */
83 class DRAWING_API SaveLayerOps {
84 public:
85     // How to allocate layer
86     enum Flags {
87         INIT_WITH_PREVIOUS = 1 << 1,    // create with previous contents
88     };
89 
SaveLayerOps()90     SaveLayerOps() : bounds_(nullptr), brush_(nullptr), saveLayerFlags_(0) {}
91 
92     /**
93      * @param bounds         The bounds of layer, may be nullptr.
94      * @param brush          When restoring the current layer, attach this brush, may be nullptr.
95      * @param saveLayerFlags How to allocate layer.
96      */
97     SaveLayerOps(const Rect* bounds, const Brush* brush, uint32_t saveLayerFlags = 0)
98         : bounds_(bounds), brush_(brush), saveLayerFlags_(saveLayerFlags) {}
~SaveLayerOps()99     ~SaveLayerOps() {}
100 
101     /**
102      * @brief Gets the bounds of layer, may be nullptr.
103      * @return Returns the bounds of layer.
104      */
GetBounds()105     const Rect* GetBounds() const
106     {
107         return bounds_;
108     }
109 
110     /**
111      * @brief Gets the brush of layer, may be nullptr.
112      * @return Returns the brush of layer.
113      */
GetBrush()114     const Brush* GetBrush() const
115     {
116         return brush_;
117     }
118 
119     /**
120      * @brief Gets the options to modify layer.
121      * @return Returns the options to modify layer.
122      */
GetSaveLayerFlags()123     uint32_t GetSaveLayerFlags() const
124     {
125         return saveLayerFlags_;
126     }
127 
128 private:
129     const Rect* bounds_;
130     const Brush* brush_;
131     uint32_t saveLayerFlags_;
132 };
133 
134 class DRAWING_API CoreCanvas {
135 public:
136     CoreCanvas();
137     explicit CoreCanvas(void* rawCanvas);
~CoreCanvas()138     virtual ~CoreCanvas() {}
139     void Bind(const Bitmap& bitmap);
140 
141     void BuildOverDraw(std::shared_ptr<Canvas> canvas);
142 
GetDrawingType()143     virtual DrawingType GetDrawingType() const
144     {
145         return DrawingType::COMMON;
146     }
147 
148     /**
149      * @brief Gets the total matrix of Canvas to device.
150      * @return Returns the total matrix of Canvas to device.
151      */
152     virtual Matrix GetTotalMatrix() const;
153 
154     /**
155      * @brief Gets bounds of clip in local coordinates.
156      * @return Returns bounds of clip in local coordinates.
157      */
158     virtual Rect GetLocalClipBounds() const;
159 
160     /**
161      * @brief Gets bounds of clip in device coordinates.
162      * @return Returns bounds of clip in device coordinates.
163      */
164     virtual RectI GetDeviceClipBounds() const;
165 
166     /**
167      * @brief Gets bounds of clip in device coordinates with round in.
168      * @return Returns bounds of clip in device coordinates.
169      */
170     virtual RectI GetRoundInDeviceClipBounds() const;
171 
172 #ifdef RS_ENABLE_GPU
173     /**
174      * @brief Gets GPU context of the GPU surface associated with Canvas.
175      * @return Returns GPU context of the GPU surface associated with Canvas.
176      */
177     virtual std::shared_ptr<GPUContext> GetGPUContext();
178 #endif
179 
180     /**
181      * @brief Gets width of Canvas.
182      * @return Returns width of Canvas.
183      */
184     int32_t GetWidth() const;
185 
186     /**
187      * @brief Gets height of Canvas.
188      * @return Returns height of Canvas.
189      */
190     int32_t GetHeight() const;
191 
192     /**
193      * @brief Gets ImageInfo of Canvas.
194      * @return Returns ImageInfo of Canvas.
195      */
196     ImageInfo GetImageInfo();
197 
198     bool ReadPixels(const ImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
199         int srcX, int srcY);
200 
201     bool ReadPixels(const Bitmap& dstBitmap, int srcX, int srcY);
202 
203     // shapes
204     /**
205      * @brief The shape of point drawn depends on pen. If pen is set to Pen::CapStyle::ROUND_CAP,
206      * draw a circle of diameter pen stroke width. If pen is set to Pen::CapStyle::SQUAER_CAP,
207      * draw a square of width and height pen stroke width.
208      * @param point top-left edge of circle or square
209      */
210     virtual void DrawPoint(const Point& point);
211 
212     /**
213      * @brief Describing a graph by combining directed vector fields.
214      * @param shape describes the combination of a group of sdf entities.
215      */
216     virtual void DrawSdf(const SDFShapeBase& shape);
217 
218     /**
219      * @brief If mode is LINES_POINTMODE, each pair of points draws a line segment. One line
220      * is drawn for every two points; each point is used once. If count is odd, the final point is ignored.
221      * If mode is POLYGON_POINTMODE, each adjacent pair of points draws a line segment. count minus one lines
222      * are drawn; the first and last point are used once.
223      * @param mode  whether pts draws points or lines
224      * @param count number of points in the array
225      * @param pts   array of points to draw
226      */
227     virtual void DrawPoints(PointMode mode, size_t count, const Point pts[]);
228 
229     /**
230      * @brief Draws line segment from startPt to endPt.
231      * @param startPt start of line segment
232      * @param endPt   end of line segment
233      */
234     virtual void DrawLine(const Point& startPt, const Point& endPt);
235 
236     /**
237      * @brief If rectangle is stroked, use pen to stroke width describes the line thickness,
238      * else use brush to fill the rectangle.
239      * @param rect rectangle to draw
240      */
241     virtual void DrawRect(const Rect& rect);
242 
243     /**
244      * @brief If round rectangle is stroked, use pen to stroke width describes the line thickness,
245      * else use brush to fill the round rectangle. Round rect may represent a rectangle, circle,
246      * oval, uniformly rounded rectangle, or may have any combination of positive non-square radii
247      * for the four corners.
248      * @param roundRect RRect with up to eight corner radii to draw
249      */
250     virtual void DrawRoundRect(const RoundRect& roundRect);
251 
252     /**
253      * @brief Outer must contain inner or the drawing is undefined. If RRect is stroked, use pen to stroke
254      * width describes the line thickness. If stroked and RRect corner has zero length radii,
255      * Pen::JoinStyle can draw corners rounded or square.
256      * @param outer RRect outer bounds to draw
257      * @param inner RRect inner bounds to draw
258      */
259     virtual void DrawNestedRoundRect(const RoundRect& outer, const RoundRect& inner);
260 
261     /**
262      * @brief Arc is part of oval bounded by oval, sweeping from startAngle to startAngle plus sweepAngle.
263      * startAngle and sweepAngle are in degrees. StartAngle of zero places start point at the right
264      * middle edge of oval. A positive sweepAngle places arc end point clockwise from start point;
265      * A negative sweepAngle places arc end point counterclockwise from start point. sweepAngle may
266      * exceed 360 degrees, a full circle. Draw a wedge that includes lines from oval center to arc end points
267      * @param oval       rect bounds of oval containing arc to draw
268      * @param startAngle angle in degrees where arc begins
269      * @param sweepAngle sweep angle in degrees, positive is clockwise
270      */
271     virtual void DrawArc(const Rect& oval, scalar startAngle, scalar sweepAngle);
272 
273     /**
274      * @brief Draw arc between end points.
275      * @param oval       rect bounds of oval containing arc to draw
276      * @param startAngle angle in degrees where arc begins
277      * @param sweepAngle sweep angle in degrees, positive is clockwise
278      */
279     virtual void DrawPie(const Rect& oval, scalar startAngle, scalar sweepAngle);
280 
281     /**
282      * @brief If oval is stroked, use pen to stroke width describes the line thickness, else use brush to fill the oval.
283      * @param oval rect bounds of oval
284      */
285     virtual void DrawOval(const Rect& oval);
286 
287     /**
288      * @brief If radius is zero or less, nothing is drawn. If circle is stroked, use pen to
289      * stroke width describes the line thickness, else use brush to fill the circle.
290      * @param centerPt circle center
291      * @param radius   half the diameter of circle
292      */
293     virtual void DrawCircle(const Point& centerPt, scalar radius);
294 
295     /**
296      * @brief Path contains an array of path contour, each of which may be open or closed.
297      * If RRect is filled, Path::PathFillType determines whether path contour
298      * describes inside or outside of fill; If stroked, use pen to stroke width
299      * describes the line thickness, Pen::CapStyle describes line ends, and
300      * Pen::Join describes how corners are drawn.
301      * @param path Path to draw
302      */
303     virtual void DrawPath(const Path& path);
304 
305     /**
306      * @brief              Use brush to fill the canvas.
307      * @param brush        used to fill Canvas
308      */
309     virtual void DrawBackground(const Brush& brush);
310 
311     virtual void DrawShadow(const Path& path, const Point3& planeParams, const Point3& devLightPos, scalar lightRadius,
312         Color ambientColor, Color spotColor, ShadowFlags flag);
313 
314     virtual void DrawShadowStyle(const Path& path, const Point3& planeParams, const Point3& devLightPos,
315         scalar lightRadius, Color ambientColor, Color spotColor, ShadowFlags flag, bool isLimitElevation);
316 
317     // color
318     /**
319      * @brief Fills clip with color color. Mode determines how ARGB is combined with destination.
320      * @param color ColorQuad representing unpremultiplied color.
321      * @param mode  BlendMode used to combine source color and destination.
322      */
323     virtual void DrawColor(ColorQuad color, BlendMode mode = BlendMode::SRC_OVER);
324 
325     /**
326      * @brief Draws Region on the Canvas.
327      * @param region Region to draw.
328      */
329     virtual void DrawRegion(const Region& region);
330 
331     /**
332      * @brief Draws a Coons patch: the interpolation of four cubics with shared corners, associating a color,
333      * and optionally a texture Point, with each corner. Point array cubics specifies four Path cubic
334      * starting at the top-left corner, in clockwise order, sharing every fourth point. The last Path
335      * cubic ends at the first point. Color array color associates colors with corners in top-left,
336      * top-right, bottom-right, bottom-left order. If brush contains Shader, Point array texCoords maps
337      * Shader as texture to corners in top-left, top-right, bottom-right, bottom-left order. If
338      * texCoords is nullptr, Shader is mapped using positions (derived from cubics).
339      * @param cubics    Path cubic array, sharing common points
340      * @param colors	color array, one for each corner
341      * @param texCoords	Point array of texture coordinates, mapping Shader to corners; may be nullptr
342      * @param mode	    combines patch's colors with Shader if present or brush opaque color if not.
343      *                  Ignored if colors is null.
344      */
345     virtual void DrawPatch(const Point cubics[12], const ColorQuad colors[4],
346         const Point texCoords[4], BlendMode mode);
347 
348     /**
349      * @brief If brush or pen contains an Shader and vertices does not contain texCoords,
350      * the shader is mapped using the vertices' positions. If vertices colors are defined
351      * in vertices, and brush/pen contains Shader, BlendMode mode combines vertices colors with Shader.
352      * MaskFilter and PathEffect on paint are ignored.
353      * @param vertices triangle mesh to draw
354      * @param mode	   combines vertices' colors with Shader if present or brush/pen opaque color if not.
355      *                 Ignored if the vertices do not contain color.
356      */
357     virtual void DrawVertices(const Vertices& vertices, BlendMode mode);
358 
359     /**
360      * @brief Draw image stretched proportionally to fit into Rect dst. IRect
361      * center divides the image into nine sections: four sides, four corners, and
362      * the center. Corners are unmodified or scaled down proportionately if their sides
363      * are larger than dst; center and four sides are scaled to fit remaining space, if any.
364      * Additionally transform draw using clip, Matrix, and optional brush. If brush is attached,
365      * apply ColorFilter, alpha, ImageFilter, and BlendMode. If image is COLORTYPE_ALPHA_8, apply Shader.
366      * If brush contains MaskFilter, generate mask from image bounds. Any MaskFilter on paint is
367      * ignored as is paint anti-aliasing state.
368      * @param image  Image containing pixels, dimensions, and format
369      * @param center IRect edge of image corners and sides
370      * @param dst    destination Rect of image to draw to
371      * @param filter what technique to use when sampling the image
372      * @param brush  brush containing MaskFilter; or nullptr
373      */
374     virtual void DrawImageNine(const Image* image, const RectI& center, const Rect& dst,
375         FilterMode filter, const Brush* brush = nullptr);
376 
377     /**
378      * @brief Draws Image image stretched proportionally to fit into Rect dst.
379      * Canvas::Lattice lattice divides image into a rectangular grid.
380      * Each intersection of an even-numbered row and column is fixed;
381      * fixed lattice elements never scale larger than their initial
382      * size and shrink proportionately when all fixed elements exceed the bitmap
383      * dimension. All other grid elements scale to fill the available space, if any.
384      *
385      * If brush is attached, apply ColorFilter, alpha, ImageFilter, and
386      * BlendMode. If image is COLORTYPE_ALPHA_8, apply Shader.
387      * If brush contains MaskFilter, generate mask from image bounds.
388      * Any MaskFilter on paint is ignored as is paint anti-aliasing state.
389      *
390      * @param image   Image containing pixels, dimensions, and format
391      * @param lattice division of bitmap into fixed and variable rectangles
392      * @param dst     destination Rect of image to draw to
393      * @param filter  what technique to use when sampling the image
394      * @param brush   brush containing BlendMode, ColorFilter, ImageFilter, and so on; or nullptr
395      */
396     virtual void DrawImageLattice(const Image* image, const Lattice& lattice, const Rect& dst,
397         FilterMode filter);
398 
399     // opinc calculate realdraw rect
400     virtual bool OpCalculateBefore(const Matrix& matrix);
401     virtual std::shared_ptr<Drawing::OpListHandle> OpCalculateAfter(const Rect& bound);
402 
403     // image
404     /**
405      * @brief Draws many parts of the image (atlas) onto the canvas.
406      * This approach can be optimized when you want to draw many parts of an image on the canvas.
407      * Rect tex selects the area in the atlas, xform transforms each sprite individually rotating or zooming.
408      * MaskFilter and PathEffect on brush are ignored.
409      *
410      * The xform and tex list must contain count entries, and if the colors is present,
411      * it must be the same length as the other two lists, the max count supported is 2000.
412      * Optional parameter colors, if present, are applied to each sprite using BlendMode mode, treating
413      * sprite as source and colors as destination.
414      * Optional parameter cullRect, if present, provides boundary values rendered by all
415      * components of the atlas to be compared to the clip.
416      *
417      * @param atlas    Image containing pixels, dimensions, and format
418      * @param xform    RSXform mappings for sprites in atlas
419      * @param tex      destination Rect of image to draw to
420      * @param colors   for each sprite, blend with it using blendmode; or nullptr
421      * @param count    the number of sprites to draw, the maximum is 2000
422      * @param mode     used to combine colors with sprites
423      * @param sampling SamplingOptions used when sampling from the atlas image
424      * @param cullRect bounds of sprites for efficient clipping; or nullptr
425      */
426     virtual void DrawAtlas(const Image* atlas, const RSXform xform[], const Rect tex[], const ColorQuad colors[],
427         int count, BlendMode mode, const SamplingOptions& sampling, const Rect* cullRect);
428     virtual void DrawBitmap(const Bitmap& bitmap, const scalar px, const scalar py);
429     virtual void DrawImage(const Image& image, const scalar px, const scalar py, const SamplingOptions& sampling);
430     virtual void DrawImageRect(const Image& image, const Rect& src, const Rect& dst, const SamplingOptions& sampling,
431         SrcRectConstraint constraint = SrcRectConstraint::STRICT_SRC_RECT_CONSTRAINT);
432     virtual void DrawImageRect(const Image& image, const Rect& dst, const SamplingOptions& sampling);
433 
434     /**
435      * @brief Clip and Matrix are unchanged by picture contents, as if Save() was called
436      * before and Restore() was called after DrawPicture(). Picture records a series of
437      * draw commands for later playback.
438      * @param picture recorded drawing commands to play
439      */
440     virtual void DrawPicture(const Picture& picture);
441 
442     // temporary interface. Support drawing of SkSVGDOM
443     virtual void DrawSVGDOM(const sk_sp<SkSVGDOM>& svgDom);
444 
445     // text
446     /**
447      * @brief blob contains glyphs, their positions, and paint attributes specific to text:
448      * Typeface, text size, text scale x, text skew x, anti-alias, fake bold,
449      * font embedded bitmaps, pen/brush full hinting spacing, LCD text, linear text,
450      * and subpixel text. TextEncoding must be set to TextEncoding::GLYPH_ID.
451      * Elements of pen/brush: anti-alias, BlendMode, color including alpha,
452      * ColorFilter, MaskFilter, PathEffect, Shader, and Brush::Style; apply to blob.
453      * If attach pen to draw text, set Pen::Cap, Pen::Join, and stroke width;
454      * apply to Path created from blob.
455      * @param blob glyphs, positions, and their paints' text size, typeface, and so on
456      * @param x    horizontal offset applied to blob
457      * @param y    vertical offset applied to blob
458     */
459     virtual void DrawTextBlob(const TextBlob* blob, const scalar x, const scalar y);
460 
461     /**
462      * @brief blob contains glyphs, their positions, and paint attributes specific to text:
463      * Typeface, text size, text scale x, text skew x, anti-alias, fake bold,
464      * font embedded bitmaps, pen/brush full hinting spacing, LCD text, linear text,
465      * and subpixel text. TextEncoding must be set to TextEncoding::GLYPH_ID.
466      * Elements of pen/brush: anti-alias, BlendMode, color including alpha,
467      * ColorFilter, MaskFilter, PathEffect, Shader, and Brush::Style; apply to blob.
468      * If attach pen to draw text, set Pen::Cap, Pen::Join, and stroke width;
469      * apply to Path created from blob.
470      * @param blob glyphs, positions, and their paints' text size, typeface, and so on
471      * @param x    horizontal offset applied to blob
472      * @param y    vertical offset applied to blob
473     */
474     void DrawSingleCharacter(int32_t unicode, const Font& font, scalar x, scalar y);
475 
476     // symbol
477     virtual void DrawSymbol(const DrawingHMSymbolData& symbol, Point locate);
478 
479     // clip
480     /**
481      * @brief Replace the clipping area with the intersection or difference between the
482      * current clipping area and Rect, and use a clipping edge that is aliased or anti-aliased.
483      * @param rect        To combine with clipping area.
484      * @param op          To apply to clip.
485      * @param doAntiAlias true if clip is to be anti-aliased. The default value is false.
486      */
487     virtual void ClipRect(const Rect& rect, ClipOp op = ClipOp::INTERSECT, bool doAntiAlias = false);
488 
489     /**
490      * @brief Replace the clipping area with the intersection or difference between the
491      * current clipping area and RectI, and use a clipping edge.
492      * @param rect        To combine with clipping area.
493      * @param op          To apply to clip.
494      */
495     virtual void ClipIRect(const RectI& rect, ClipOp op = ClipOp::INTERSECT);
496 
497     /**
498      * @brief Replace the clipping area with the intersection or difference of the
499      * current clipping area and Rect, and use a clipping edge that is aliased or anti-aliased.
500      * @param roundRect   To combine with clip.
501      * @param op          To apply to clip.
502      * @param doAntiAlias true if clip is to be anti-aliased. The default value is false.
503      */
504     virtual void ClipRoundRect(const RoundRect& roundRect, ClipOp op = ClipOp::INTERSECT, bool doAntiAlias = false);
505 
506     virtual void ClipRoundRect(const Rect& rect, std::vector<Point>& pts, bool doAntiAlias = false);
507 
508     /*
509      * @brief              Replace the clipping area with the intersection or difference of the
510                            current clipping area and Path, and use a clipping edge that is aliased or anti-aliased.
511      * @param path         To combine with clip.
512      * @param op           To apply to clip.
513      * @param doAntiAlias  true if clip is to be anti-aliased. The default value is false.
514      */
515     virtual void ClipPath(const Path& path, ClipOp op = ClipOp::INTERSECT, bool doAntiAlias = false);
516 
517     /**
518      * @brief Replace the clipping area with the intersection or difference of the
519      * current clipping area and Region, and use a clipping edge that is aliased or anti-aliased.
520      * @param region To combine with clip.
521      * @param op     To apply to clip.The default value is ClipOp::INTERSECT
522      */
523     virtual void ClipRegion(const Region& region, ClipOp op = ClipOp::INTERSECT);
524 
525     /**
526      * @brief Returns true if clip is empty.
527      * @return true if clip is empty
528      */
529     virtual bool IsClipEmpty();
530 
531     /**
532      * @brief Returns true if clip is Rect and not empty.
533      * @return true if clip is rect and not empty
534      */
535     virtual bool IsClipRect();
536 
537     /**
538      * @brief Returns true if clip is empty Rect rect, transformed by Matrix,
539      * can be quickly determined to be outside of clip.
540      * @param rect Rect to compare with clip
541      * @return true if rect, transformed by Matrix, does not intersect clip
542      */
543     virtual bool QuickReject(const Rect& rect);
544 
545     // transform
546     /**
547      * @brief Replaces RSMatrix with matrix. Unlike Concat(), any prior matrix state is overwritten.
548      * @param matrix matrix to copy, replacing existing RSMatrix
549      */
550     virtual void SetMatrix(const Matrix& matrix);
551 
552     /**
553      * @brief Sets RSMatrix to the identity matrix. Any prior matrix state is overwritten.
554      */
555     virtual void ResetMatrix();
556 
557     /**
558      * @brief Replaces RSMatrix with matrix premultiplied with existing RSMatrix.
559      * This has the effect of transforming the drawn geometry by matrix, before
560      * transforming the result with existing RSMatrix.
561      * @param matrix matrix to premultiply with existing RSMatrix
562      */
563     virtual void ConcatMatrix(const Matrix& matrix);
564 
565     /**
566      * @brief Translates RSMatrix by dx along the x-axis and dy along the y-axis.
567      * Mathematically, replaces RSMatrix with a translation matrix premultiplied with RSMatrix.
568      * This has the effect of moving the drawing by (dx, dy) before transforming the result with RSMatrix.
569      * @param dx distance to translate on x-axis
570      * @param dy distance to translate on y-axis
571      */
572     virtual void Translate(scalar dx, scalar dy);
573 
574     /**
575      * @brief Scales RSMatrix by sx on the x-axis and sy on the y-axis.
576      * Mathematically, replaces RSMatrix with a scale matrix premultiplied with RSMatrix.
577      * This has the effect of scaling the drawing by (sx, sy) before transforming the result with RSMatrix.
578      * @param sx amount to scale on x-axis
579      * @param sy amount to scale on y-axis
580      */
581     virtual void Scale(scalar sx, scalar sy);
582 
583     /**
584      * @brief Rotates Matrix by degrees.
585      * @param deg Amount to rotate, in degrees.
586      */
Rotate(scalar deg)587     void Rotate(scalar deg)
588     {
589         Rotate(deg, 0, 0);
590     }
591 
592     /**
593      * @brief Rotates RSMatrix by degrees about a point at (sx, sy). Positive degrees rotates clockwise.
594      * Mathematically, constructs a rotation matrix; premultiplies the rotation matrix by
595      * a translation matrix; then replaces RSMatrix with the resulting matrix premultiplied with RSMatrix.
596      * This has the effect of rotating the drawing about a given point before transforming the result with RSMatrix.
597      * @param deg amount to rotate, in degrees
598      * @param sx  x-axis value of the point to rotate about
599      * @param sy  y-axis value of the point to rotate about
600      */
601     virtual void Rotate(scalar deg, scalar sx, scalar sy);
602 
603     /**
604      * @brief Shear RSMatrix by sx on the x-axis and sy on the y-axis. A positive value of sx
605      * skews the drawing right as y-axis values increase; a positive value of sy skews
606      * the drawing down as x-axis values increase. Mathematically, replaces RSMatrix with a
607      * skew matrix premultiplied with RSMatrix.
608      * This has the effect of skewing the drawing by (sx, sy) before transforming the result with RSMatrix.
609      * @param sx amount to skew on x-axis
610      * @param sy amount to skew on y-axis
611      */
612     virtual void Shear(scalar sx, scalar sy);
613 
614     // state
615     /**
616      * @brief Triggers the immediate execution of all pending draw operations.
617      * If Canvas is associated with GPU surface, resolves all pending GPU operations.
618      * If Canvas is associated with raster surface, has no effect; raster draw
619      * operations are never deferred.
620      */
621     virtual void Flush();
622 
623     /**
624      * @brief Fills clip with color color using BlendMode::SRC.
625      * This has the effect of replacing all pixels contained by clip with color.
626      * @param color unpremultiplied ARGB
627      */
628     virtual void Clear(ColorQuad color);
629 
630     /**
631      * @brief Saves Matrix and clipping area, return the number of saved states.
632      */
633     virtual uint32_t Save();
634 
635     /**
636      * @brief Saves Matrix and clipping area, and allocates Surface for subsequent drawing.
637      * @param saveLayerOps Contains the option used to create the layer.
638      */
639     virtual void SaveLayer(const SaveLayerOps& saveLayerOps);
640 
641     /**
642      * @brief Removes changes to Matrix and clip since Canvas state was last saved.
643      * The state is removed from the stack. Does nothing if the stack is empty.
644      */
645     virtual void Restore();
646 
647     /**
648      * @brief Returns the number of saved states, each containing Matrix and clipping area.
649      *
650      * @return uint32_t type, represent depth of save state stack
651      */
652     virtual uint32_t GetSaveCount() const;
653 
654     /**
655      * @brief Makes Canvas contents undefined.
656      */
657     virtual void Discard();
658 
659     // paint
660     /**
661      * @brief Attach pen to canvas and stroke something.
662      * @param pen tool to stroke
663      * @return CoreCanvas&
664      */
665     virtual CoreCanvas& AttachPen(const Pen& pen);
666 
667     /**
668      * @brief Attach brush to canvas and fill something.
669      * @param brush tool to fill
670      * @return CoreCanvas&
671      */
672     virtual CoreCanvas& AttachBrush(const Brush& brush);
673 
674     /**
675      * @brief Attach paint to canvas to draw something.
676      * @param paint tool to fill or stroke something
677      * @return CoreCanvas&
678      */
679     virtual CoreCanvas& AttachPaint(const Paint& paint);
680 
681     /**
682      * @brief Detach pen from canvas.
683      * @return CoreCanvas&
684      */
685     virtual CoreCanvas& DetachPen();
686 
687     /**
688      * @brief Detach brush from canvas.
689      * @return CoreCanvas&
690      */
691     virtual CoreCanvas& DetachBrush();
692 
693     /**
694      * @brief Detach paint from canvas.
695      * @return CoreCanvas&
696      */
697     virtual CoreCanvas& DetachPaint();
698 
699     virtual ColorQuad GetEnvForegroundColor() const;
700     virtual bool isHighContrastEnabled() const;
701     virtual Drawing::CacheType GetCacheType() const;
702     virtual Drawing::Surface* GetSurface() const;
703 
704     virtual float GetAlpha() const;
705     virtual int GetAlphaSaveCount() const;
706 
707     template<typename T>
GetImpl()708     T* GetImpl() const
709     {
710         return impl_->DowncastingTo<T>();
711     }
712     std::shared_ptr<CoreCanvasImpl> GetCanvasData() const;
713 
GetMutableBrush()714     Paint& GetMutableBrush()
715     {
716         return paintBrush_;
717     }
718 
GetMutablePen()719     Paint& GetMutablePen()
720     {
721         return paintPen_;
722     }
723 
724     virtual bool DrawBlurImage(const Image& image, const HpsBlurParameter& blurParams);
725 
726     /**
727      * @brief                   Get the size after HPS blur downsampling. Only VK will return valid values.
728      * @param blurParams         HPS blur Param is used to calculate the size after downsampling.
729      * @return {width, height}, if return {0, 0}, witch means something error.
730      */
731     virtual std::array<int, 2> CalcHpsBluredImageDimension(const Drawing::HpsBlurParameter& blurParams);
732 
733 protected:
734     CoreCanvas(int32_t width, int32_t height);
735     void BuildNoDraw(int32_t width, int32_t height);
736     void Reset(int32_t width, int32_t height);
737     Paint paintBrush_;
738     Paint paintPen_;
739     Paint defaultPaint_;
740 
741 private:
742     std::shared_ptr<CoreCanvasImpl> impl_;
743 #ifdef RS_ENABLE_GPU
744     std::shared_ptr<GPUContext> gpuContext_;
745 #endif
746 };
747 } // namespace Drawing
748 } // namespace Rosen
749 } // namespace OHOS
750 #endif
751